context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; /// <summary> /// Convert.ToString(System.Object) /// </summary> public class ConvertToString22 { public static int Main() { ConvertToString22 testObj = new ConvertToString22(); TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToString(System.Object)"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; string c_TEST_DESC = "PosTest1: Call Convert.ToString when value implements IConvertible... "; string c_TEST_ID = "P001"; TestConvertableClass tcc = new TestConvertableClass(); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { object myObject = tcc; if (tcc.ToString(null) != Convert.ToString(myObject)) { string errorDesc = "value is not " + Convert.ToString((object)tcc) + " as expected: Actual is " + tcc.ToString(); TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; string c_TEST_DESC = "PosTest2: Verify object is a null reference... "; string c_TEST_ID = "P002"; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { object obj = null; String resValue = Convert.ToString(obj); if (resValue !=String.Empty) { string errorDesc = "value is not \""+ resValue +"\" as expected: Actual is empty"; errorDesc += "\n when object is a null reference"; TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "unexpected exception occurs :" + e); retVal = false; } return retVal; } #endregion #region HelpMethod public class TestConvertableClass : IConvertible { #region IConvertible Members public TypeCode GetTypeCode() { throw new Exception("The method or operation is not implemented."); } public bool ToBoolean(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public byte ToByte(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public char ToChar(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public DateTime ToDateTime(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public decimal ToDecimal(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public double ToDouble(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public short ToInt16(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public int ToInt32(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public long ToInt64(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public sbyte ToSByte(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public float ToSingle(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public string ToString(IFormatProvider provider) { return "this is user-defined class"; } public object ToType(Type conversionType, IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public ushort ToUInt16(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public uint ToUInt32(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public ulong ToUInt64(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } #endregion } #endregion }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Text; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Services.Interfaces; namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver { /// <summary> /// Utility methods for inventory archiving /// </summary> public static class InventoryArchiveUtils { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // Character used for escaping the path delimter ("\/") and itself ("\\") in human escaped strings public static readonly char ESCAPE_CHARACTER = '\\'; // The character used to separate inventory path components (different folders and items) public static readonly char PATH_DELIMITER = '/'; /// <summary> /// Find a folder given a PATH_DELIMITER delimited path starting from a user's root folder /// </summary> /// /// This method does not handle paths that contain multiple delimitors /// /// FIXME: We have no way of distinguishing folders with the same path /// /// FIXME: Delimitors which occur in names themselves are not currently escapable. /// /// <param name="inventoryService"> /// Inventory service to query /// </param> /// <param name="userId"> /// User id to search /// </param> /// <param name="path"> /// The path to the required folder. /// It this is empty or consists only of the PATH_DELIMTER then this folder itself is returned. /// </param> /// <returns>An empty list if the folder is not found, otherwise a list of all folders that match the name</returns> public static List<InventoryFolderBase> FindFolderByPath( IInventoryService inventoryService, UUID userId, string path) { InventoryFolderBase rootFolder = inventoryService.GetRootFolder(userId); if (null == rootFolder) return new List<InventoryFolderBase>(); return FindFolderByPath(inventoryService, rootFolder, path); } /// <summary> /// Find a folder given a PATH_DELIMITER delimited path starting from this folder /// </summary> /// /// This method does not handle paths that contain multiple delimitors /// /// FIXME: We have no way of distinguishing folders with the same path. /// /// FIXME: Delimitors which occur in names themselves are not currently escapable. /// /// <param name="inventoryService"> /// Inventory service to query /// </param> /// <param name="startFolder"> /// The folder from which the path starts /// </param> /// <param name="path"> /// The path to the required folder. /// It this is empty or consists only of the PATH_DELIMTER then this folder itself is returned. /// </param> /// <returns>An empty list if the folder is not found, otherwise a list of all folders that match the name</returns> public static List<InventoryFolderBase> FindFolderByPath( IInventoryService inventoryService, InventoryFolderBase startFolder, string path) { List<InventoryFolderBase> foundFolders = new List<InventoryFolderBase>(); if (path == string.Empty) { foundFolders.Add(startFolder); return foundFolders; } path = path.Trim(); if (path == PATH_DELIMITER.ToString()) { foundFolders.Add(startFolder); return foundFolders; } string[] components = SplitEscapedPath(path); components[0] = UnescapePath(components[0]); //string[] components = path.Split(new string[] { PATH_DELIMITER.ToString() }, 2, StringSplitOptions.None); InventoryCollection contents = inventoryService.GetFolderContent(startFolder.Owner, startFolder.ID); foreach (InventoryFolderBase folder in contents.Folders) { if (folder.Name == components[0]) { if (components.Length > 1) foundFolders.AddRange(FindFolderByPath(inventoryService, folder, components[1])); else foundFolders.Add(folder); } } return foundFolders; } /// <summary> /// Find an item given a PATH_DELIMITOR delimited path starting from the user's root folder. /// /// This method does not handle paths that contain multiple delimitors /// /// FIXME: We do not yet handle situations where folders or items have the same name. We could handle this by some /// XPath like expression /// /// FIXME: Delimitors which occur in names themselves are not currently escapable. /// </summary> /// /// <param name="inventoryService"> /// Inventory service to query /// </param> /// <param name="userId"> /// The user to search /// </param> /// <param name="path"> /// The path to the required item. /// </param> /// <returns>null if the item is not found</returns> public static InventoryItemBase FindItemByPath( IInventoryService inventoryService, UUID userId, string path) { InventoryFolderBase rootFolder = inventoryService.GetRootFolder(userId); if (null == rootFolder) return null; return FindItemByPath(inventoryService, rootFolder, path); } /// <summary> /// Find an item given a PATH_DELIMITOR delimited path starting from this folder. /// /// This method does not handle paths that contain multiple delimitors /// /// FIXME: We do not yet handle situations where folders or items have the same name. We could handle this by some /// XPath like expression /// /// FIXME: Delimitors which occur in names themselves are not currently escapable. /// </summary> /// /// <param name="inventoryService"> /// Inventory service to query /// </param> /// <param name="startFolder"> /// The folder from which the path starts /// </param> /// <param name="path"> /// <param name="path"> /// The path to the required item. /// </param> /// <returns>null if the item is not found</returns> public static InventoryItemBase FindItemByPath( IInventoryService inventoryService, InventoryFolderBase startFolder, string path) { string[] components = SplitEscapedPath(path); components[0] = UnescapePath(components[0]); //string[] components = path.Split(new string[] { PATH_DELIMITER }, 2, StringSplitOptions.None); if (components.Length == 1) { // m_log.DebugFormat( // "FOUND SINGLE COMPONENT [{0}]. Looking for this in [{1}] {2}", // components[0], startFolder.Name, startFolder.ID); List<InventoryItemBase> items = inventoryService.GetFolderItems(startFolder.Owner, startFolder.ID); // m_log.DebugFormat("[INVENTORY ARCHIVE UTILS]: Found {0} items in FindItemByPath()", items.Count); foreach (InventoryItemBase item in items) { // m_log.DebugFormat("[INVENTORY ARCHIVE UTILS]: Inspecting item {0} {1}", item.Name, item.ID); if (item.Name == components[0]) return item; } } else { // m_log.DebugFormat("FOUND COMPONENTS [{0}] and [{1}]", components[0], components[1]); InventoryCollection contents = inventoryService.GetFolderContent(startFolder.Owner, startFolder.ID); foreach (InventoryFolderBase folder in contents.Folders) { if (folder.Name == components[0]) return FindItemByPath(inventoryService, folder, components[1]); } } // We didn't find an item or intermediate folder with the given name return null; } /// <summary> /// Split a human escaped path into two components if it contains an unescaped path delimiter, or one component /// if no delimiter is present /// </summary> /// <param name="path"></param> /// <returns> /// The split path. We leave the components in their originally unescaped state (though we remove the delimiter /// which originally split them if applicable). /// </returns> public static string[] SplitEscapedPath(string path) { // m_log.DebugFormat("SPLITTING PATH {0}", path); bool singleEscapeChar = false; for (int i = 0; i < path.Length; i++) { if (path[i] == ESCAPE_CHARACTER && !singleEscapeChar) { singleEscapeChar = true; } else { if (PATH_DELIMITER == path[i] && !singleEscapeChar) return new string[2] { path.Remove(i), path.Substring(i + 1) }; else singleEscapeChar = false; } } // We didn't find a delimiter return new string[1] { path }; } /// <summary> /// Unescapes a human escaped path. This means that "\\" goes to "\", and "\/" goes to "/" /// </summary> /// <param name="path"></param> /// <returns></returns> public static string UnescapePath(string path) { // m_log.DebugFormat("ESCAPING PATH {0}", path); StringBuilder sb = new StringBuilder(); bool singleEscapeChar = false; for (int i = 0; i < path.Length; i++) { if (path[i] == ESCAPE_CHARACTER && !singleEscapeChar) singleEscapeChar = true; else singleEscapeChar = false; if (singleEscapeChar) { if (PATH_DELIMITER == path[i]) sb.Append(PATH_DELIMITER); } else { sb.Append(path[i]); } } // m_log.DebugFormat("ESCAPED PATH TO {0}", sb); return sb.ToString(); } /// <summary> /// Escape an archive path. /// </summary> /// This has to be done differently from human paths because we can't leave in any "/" characters (due to /// problems if the archive is built from or extracted to a filesystem /// <param name="path"></param> /// <returns></returns> public static string EscapeArchivePath(string path) { // Only encode ampersands (for escaping anything) and / (since this is used as general dir separator). return path.Replace("&", "&amp;").Replace("/", "&#47;"); } /// <summary> /// Unescape an archive path. /// </summary> /// <param name="path"></param> /// <returns></returns> public static string UnescapeArchivePath(string path) { return path.Replace("&#47;", "/").Replace("&amp;", "&"); } } }
namespace Microsoft.Protocols.TestSuites.MS_ASRM { using System.Globalization; using System.Xml; using Common.DataStructures; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> /// This scenario is designed to test the Settings, SendMail and Sync commands. /// </summary> [TestClass] public class S01_Settings_SendMail_Sync : TestSuiteBase { #region Class initialize and clean up /// <summary> /// Initialize the class. /// </summary> /// <param name="testContext">VSTS test context.</param> [ClassInitialize] public static void ClassInitialize(TestContext testContext) { TestClassBase.Initialize(testContext); } /// <summary> /// Clear the class. /// </summary> [ClassCleanup] public static void ClassCleanUp() { TestClassBase.Cleanup(); } #endregion #region MSASRM_S01_TC01_Sync_RightsManagedEmailMessages /// <summary> /// This test case is designed to call Sync command to synchronize a rights-managed e-mail message with different values of RightsManagementSupport element. /// </summary> [TestCategory("MSASRM"), TestMethod()] public void MSASRM_S01_TC01_Sync_RightsManagedEmailMessages() { this.CheckPreconditions(); #region The client logs on User1's account, calls Settings command to get a templateID with all rights allowed. string templateID = this.GetTemplateID("MSASRM_AllRights_AllowedTemplate"); #endregion #region The client logs on User1's account, calls SendMail command with the templateID to send a rights-managed e-mail message to User2, switches to User2, and calls FolderSync command. string subject = this.SendMailAndFolderSync(templateID, false, null); #endregion #region The client logs on User2's account, calls Sync command with RightsManagementSupport element set to true to synchronize changes of Inbox folder in User2's mailbox, and gets the decompressed and decrypted rights-managed e-mail message. Sync item = this.SyncEmail(subject, this.UserTwoInformation.InboxCollectionId, true, true); Site.Assert.IsNotNull(item, "The returned item should not be null."); Site.Assert.IsNull(item.Email.Attachments, "The Attachments element in expected rights-managed e-mail message should be null."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R127"); // Verify MS-ASRM requirement: MS-ASRM_R127 // If the RightsManagementLicense element is not null, represents the message has IRM protection. Site.CaptureRequirementIfIsNotNull( item.Email.RightsManagementLicense, 127, @"[In RightsManagementSupport] If the value of this element[RightsManagementSupport] is TRUE (1), the server will decompress rights-managed email messages before sending them to the client, as specified in section 3.2.4.3. "); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R347"); // Verify MS-ASRM requirement: MS-ASRM_R347 // If the RightsManagementLicense element is not null, represents the message has IRM protection. Site.CaptureRequirementIfIsNotNull( item.Email.RightsManagementLicense, 347, @"[In RightsManagementSupport] If the value of this element[RightsManagementSupport] is TRUE (1), the server will decrypt rights-managed email messages before sending them to the client, as specified in section 3.2.4.3. "); XmlElement lastRawResponse = (XmlElement)this.ASRMAdapter.LastRawResponseXml; string contentExpiryDate = TestSuiteHelper.GetElementInnerText(lastRawResponse, "RightsManagementLicense", "ContentExpiryDate", subject); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R23"); // Verify MS-ASRM requirement: MS-ASRM_R23 Site.CaptureRequirementIfAreEqual<string>( "9999-12-30T23:59:59.999Z", contentExpiryDate, 23, @"[In ContentExpiryDate] The ContentExpiryDate element is set to ""9999-12-30T23:59:59.999Z"" if the rights management license has no expiration date set."); #endregion #region The client logs on User2's account, calls Sync command with RightsManagementSupport element set to false to synchronize changes of Inbox folder in User2's mailbox, and gets the neither decompressed nor decrypted rights-managed e-mail message. item = this.SyncEmail(subject, this.UserTwoInformation.InboxCollectionId, false, true); Site.Assert.IsNotNull(item, "The returned item should not be null."); Site.Assert.IsNotNull(item.Email.Attachments, "The Attachments element in expected rights-managed e-mail message should not be null."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R335"); // Verify MS-ASRM requirement: MS-ASRM_R335 // If the RightsManagementLicense element is null, represents the message has no IRM protection. Site.CaptureRequirementIfIsNull( item.Email.RightsManagementLicense, 335, @"[In RightsManagementSupport] If the value is FALSE (0), the server will not decompress rights-managed email messages before sending them to the client. "); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R348"); // Verify MS-ASRM requirement: MS-ASRM_R348 // If the RightsManagementLicense element is null, represents the message has no IRM protection. Site.CaptureRequirementIfIsNull( item.Email.RightsManagementLicense, 348, @"[In RightsManagementSupport] If the value is FALSE (0), the server will not decrypt rights-managed email messages before sending them to the client. "); #endregion #region The client logs on User2's account, calls Sync command without the RightsManagementSupport element in a request message to synchronize changes of Inbox folder in User2's mailbox, and gets the neither decompressed nor decrypted rights-managed e-mail message. item = this.SyncEmail(subject, this.UserTwoInformation.InboxCollectionId, null, true); Site.Assert.IsNotNull(item, "The returned item should not be null."); Site.Assert.IsNotNull(item.Email.Attachments, "The Attachments element in expected rights-managed e-mail message should not be null."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R128"); // Verify MS-ASRM requirement: MS-ASRM_R128 // If the response contains RightsManagementLicense element as null, and Attachments element not null, just as the same response when RightsManagementSupport is set to false, this requirement can be verified. Site.CaptureRequirementIfIsNull( item.Email.RightsManagementLicense, 128, @"[In RightsManagementSupport] If the RightsManagementSupport element is not included in a request message, a default value of FALSE is assumed."); #endregion } #endregion #region MSASRM_S01_TC02_Sync_Owner_RightsManagedEmailMessages /// <summary> /// This test case is designed to test the Owner element. /// </summary> [TestCategory("MSASRM"), TestMethod()] public void MSASRM_S01_TC02_Sync_Owner_RightsManagedEmailMessages() { this.CheckPreconditions(); #region The client logs on User1's account, calls Settings command to get a templateID with all rights denied except view rights. string templateID = this.GetTemplateID("MSASRM_View_AllowedTemplate"); #endregion #region The client logs on User1's account, calls SendMail command with the templateID to send a rights-managed e-mail message to User2, switches to User2, and call FolderSync command. string subject = this.SendMailAndFolderSync(templateID, true, null); #endregion #region The client logs on User2's account, calls Sync command with RightsManagementSupport element set to true to synchronize changes of Inbox folder in User2's mailbox, and gets the decompressed and decrypted rights-managed e-mail message, checks the Owner element. Sync item = this.SyncEmail(subject, this.UserTwoInformation.InboxCollectionId, true, true); Site.Assert.IsNotNull(item, "The returned item should not be null."); Site.Assert.IsNotNull(item.Email.RightsManagementLicense, "The RightsManagementLicense element in expected rights-managed e-mail message should not be null."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R330"); // Verify MS-ASRM requirement: MS-ASRM_R330 Site.CaptureRequirementIfIsFalse( item.Email.RightsManagementLicense.Owner, 330, @"[In Owner] if the value is FALSE (0), the user is not the owner of the e-mail message."); #endregion #region The client logs on User1's account, calls Sync command with RightsManagementSupport element set to true to synchronize changes of SentItems folder in User1's mailbox, and gets the decompressed and decrypted rights-managed e-mail message, checks the Owner element. this.SwitchUser(this.UserOneInformation, false); item = this.SyncEmail(subject, this.UserOneInformation.SentItemsCollectionId, true, true); Site.Assert.IsNotNull(item, "The returned item should not be null."); Site.Assert.IsNotNull(item.Email.RightsManagementLicense, "The RightsManagementLicense element in expected rights-managed e-mail message should not be null."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R72"); // Verify MS-ASRM requirement: MS-ASRM_R72 Site.CaptureRequirementIfIsTrue( item.Email.RightsManagementLicense.Owner, 72, @"[In Owner] If the value is TRUE (1), the user is the owner of the e-mail message."); Site.Assert.AreEqual<string>(Common.GetMailAddress(this.UserOneInformation.UserName, this.UserOneInformation.UserDomain).ToUpper(CultureInfo.CurrentCulture), item.Email.RightsManagementLicense.ContentOwner.ToUpper(CultureInfo.CurrentCulture), "The value of ContentOwner element should be equal to the User1's e-mail address."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R31"); // Verify MS-ASRM requirement: MS-ASRM_R31 Site.CaptureRequirementIfIsTrue( item.Email.RightsManagementLicense.Owner, 31, @"[In ContentOwner] The Owner element is set to TRUE for the user specified by the ContentOwner element."); #endregion } #endregion #region MSASRM_S01_TC03_Settings_InvalidXMLBody_ActiveSyncVersionNot141 /// <summary> /// This test case is designed to test that the server considers the XML body of the command request to be invalid when ActiveSync version is not equal to 14.1. /// </summary> [TestCategory("MSASRM"), TestMethod()] public void MSASRM_S01_TC03_Settings_InvalidXMLBody_ActiveSyncVersionNot141() { Site.Assume.AreNotEqual<string>("14.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "Implementation does consider the XML body of the command request to be invalid, if the protocol version specified by in the command request is not 14.1."); Site.Assume.AreNotEqual<string>("16.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "Implementation does consider the XML body of the command request to be invalid, if the protocol version specified by in the command request is not 16.0."); #region The client logs on User1's account, calls Settings command and checks the response of Settings command. if (Common.IsRequirementEnabled(418, this.Site)) { SettingsResponse settingsResponse = this.ASRMAdapter.Settings(); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R418"); // Verify MS-ASRM requirement: MS-ASRM_R418 // The value of Status element of Settings response could not be 1, which means the operation is unsuccessful. Site.CaptureRequirementIfAreNotEqual<string>( "1", settingsResponse.ResponseData.Status, 418, @"[In Appendix B: Product Behavior]Implementation does consider the XML body of the command request to be invalid, if the protocol version that is specified by the command request does not support the XML elements that are defined for this protocol. (Exchange Server 2010 and above follow this behavior.)"); } #endregion } #endregion } }
/* * REST API Documentation for the MOTI School Bus Application * * The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus. * * OpenAPI spec version: v1 * * */ using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using SchoolBusAPI.Models; using SchoolBusAPI.ViewModels; using Microsoft.AspNetCore.Http; using AutoMapper; using System; using SchoolBusAPI.Authorization; namespace SchoolBusAPI.Services { /// <summary> /// /// </summary> public interface IUserService { /// <summary> /// /// </summary> /// <remarks>Returns all users</remarks> /// <response code="200">OK</response> /// <response code="404">User not found</response> IActionResult GetUsers(); /// <summary> /// /// </summary> /// <remarks>Deletes a user</remarks> /// <param name="id">id of User to delete</param> /// <response code="200">OK</response> /// <response code="404">User not found</response> IActionResult DeleteUser(int id); /// <summary> /// /// </summary> /// <remarks>Returns data for a particular user</remarks> /// <param name="id">id of User to fetch</param> /// <response code="200">OK</response> /// <response code="404">User not found</response> IActionResult GetUser(int id); /// <summary> /// /// </summary> /// <remarks>Updates a user</remarks> /// <param name="id">id of User to update</param> /// <param name="item"></param> /// <response code="200">OK</response> /// <response code="404">User not found</response> IActionResult UpdateUser(int id, UserViewModel item); /// <summary> /// /// </summary> /// <remarks>Returns the roles for a user</remarks> /// <param name="id">id of User to fetch</param> /// <response code="200">OK</response> /// <response code="404">User not found</response> IActionResult GetUserRoles(int id); /// <summary> /// /// </summary> /// <remarks>Adds a role to a user</remarks> /// <param name="id">id of User to update</param> /// <param name="item"></param> /// <response code="201">Role created for user</response> IActionResult CreateUserRole(int id, UserRoleViewModel item); /// <summary> /// /// </summary> /// <remarks>Updates the roles for a user</remarks> /// <param name="id">id of User to update</param> /// <param name="userRoleId">id of User Role to update</param> /// <param name="item"></param> /// <response code="200">OK</response> /// <response code="404">User not found</response> IActionResult UpdateUserRole(int id, int userRoleId, UserRoleViewModel item); /// <summary> /// /// </summary> /// <remarks>Create new user</remarks> /// <param name="item"></param> /// <response code="201">User created</response> IActionResult CreateUser(UserViewModel item); /// <summary> /// Searches Users /// </summary> /// <remarks>Used for the search users.</remarks> /// <param name="districts">Districts (array of id numbers)</param> /// <param name="surname"></param> /// <param name="includeInactive">True if Inactive users will be returned</param> /// <response code="200">OK</response> IActionResult SearchUsers(int?[] districts, string surname, bool? includeInactive); IActionResult GetInspectors(bool? includeInactive); } /// <summary> /// /// </summary> public class UserService : ServiceBase, IUserService { private readonly DbAppContext _context; /// <summary> /// Create a service and set the database context /// </summary> public UserService(DbAppContext context, IHttpContextAccessor httpContextAccessor, IMapper mapper) : base(httpContextAccessor, context, mapper) { _context = context; } /// <summary> /// /// </summary> /// <remarks>Returns all users</remarks> /// <response code="200">OK</response> /// <response code="404">User not found</response> public virtual IActionResult GetUsers() { var users = _context.Users .AsNoTracking() .Include(x => x.District) .Include(x => x.UserRoles) .ThenInclude(y => y.Role) .ToList(); return new ObjectResult(Mapper.Map<List<UserViewModel>>(users)); } /// <summary> /// /// </summary> /// <remarks>Returns data for a particular user</remarks> /// <param name="id">id of User to fetch</param> /// <response code="200">OK</response> /// <response code="404">User not found</response> public virtual IActionResult GetUser(int id) { var user = _context.Users .AsNoTracking() .Include(x => x.District) .Include(x => x.UserRoles) .ThenInclude(y => y.Role) .FirstOrDefault(x => x.Id == id); if (user == null) { return new StatusCodeResult(404); } user.UserRoles = user.UserRoles .ToList() .Where(r => r.Role.ExpiryDate == null || r.Role.ExpiryDate > DateTime.UtcNow) .ToList(); var userView = Mapper.Map<UserViewModel>(user); return new ObjectResult(userView); } /// <summary> /// /// </summary> /// <remarks>Create new user</remarks> /// <param name="item"></param> /// <response code="201">User created</response> public virtual IActionResult CreateUser(UserViewModel item) { var (userValid, smUserError) = ValidateSmUserId(item); if (!userValid) return smUserError; var (districtValid, districtError) = ValidateDistrict(item); if (!districtValid) return districtError; var user = Mapper.Map<User>(item); _context.Users.Add(user); _context.SaveChanges(); return new ObjectResult(Mapper.Map<UserViewModel>(user)); } /// <summary> /// /// </summary> /// <remarks>Updates a user</remarks> /// <param name="id">id of User to update</param> /// <param name="item"></param> /// <response code="200">OK</response> /// <response code="404">User not found</response> public virtual IActionResult UpdateUser(int id, UserViewModel item) { if (id != item.Id) { return new UnprocessableEntityObjectResult(new Error("Validation Error", 100, $"Id [{id}] mismatches [{item.Id}].")); } var user = _context.Users .Include(x => x.District) .Include(x => x.UserRoles) .ThenInclude(y => y.Role) .FirstOrDefault(x => x.Id == id); if (user == null) { return new StatusCodeResult(404); } var (userValid, smUserError) = ValidateSmUserId(item); if (!userValid) return smUserError; var (districtValid, districtError) = ValidateDistrict(item); if (!districtValid) return districtError; user = Mapper.Map(item, user); user.District = _context.Districts .First(x => x.Id == item.District.Id); _context.SaveChanges(); user.UserRoles = user.UserRoles .ToList() .Where(r => r.Role.ExpiryDate == null || r.Role.ExpiryDate > DateTime.UtcNow) .ToList(); return new ObjectResult(Mapper.Map<UserViewModel>(user)); } /// <summary> /// /// </summary> /// <remarks>Deletes a user</remarks> /// <param name="id">id of User to delete</param> /// <response code="200">OK</response> /// <response code="404">User not found</response> public virtual IActionResult DeleteUser(int id) { var user = _context.Users .Include(x => x.District) .Include(x => x.UserRoles) .ThenInclude(y => y.Role) .FirstOrDefault(x => x.Id == id); if (user == null) { // Not Found return new StatusCodeResult(404); } if (user.UserRoles.Any(x => x.Role.Name == Roles.Inspector) && !IsInspectorRoleRemovable(id)) { return new UnprocessableEntityObjectResult( new Error("Validation Error", 310, $"There are buses assigned to the user. Please reassign the buses to other inspector(s), and then delete the user.")); } user.Active = false; _context.SaveChanges(); user.UserRoles = user.UserRoles .ToList() .Where(r => r.Role.ExpiryDate == null || r.Role.ExpiryDate > DateTime.UtcNow) .ToList(); return new ObjectResult(Mapper.Map<UserViewModel>(user)); } /// <summary> /// /// </summary> /// <remarks>Returns the roles for a user</remarks> /// <param name="id">id of User to fetch</param> /// <response code="200">OK</response> /// <response code="404">User not found</response> public virtual IActionResult GetUserRoles(int id) { var userRoles = _context.UserRoles .AsNoTracking() .Include(x => x.Role) .Where(x => x.UserId == id && (x.Role.ExpiryDate == null || x.Role.ExpiryDate > DateTime.UtcNow)); var result = Mapper.Map<List<UserRoleViewModel>>(userRoles); return new ObjectResult(result); } public virtual IActionResult CreateUserRole(int userId, UserRoleViewModel item) { var (userRoleValid, userRoleError) = ValidateUserRole(userId, item); if (!userRoleValid) return userRoleError; User user = _context.Users .Include(x => x.District) .Include(x => x.UserRoles) .First(x => x.Id == userId); if (user.UserRoles == null) { user.UserRoles = new List<UserRole>(); } // create a new UserRole based on the view model. user.UserRoles.Add(new UserRole { Role = _context.Roles.First(x => x.Id == item.RoleId), EffectiveDate = item.EffectiveDate, ExpiryDate = item.ExpiryDate } ); _context.SaveChanges(); return new StatusCodeResult(201); } public virtual IActionResult UpdateUserRole(int userId, int userRoleId, UserRoleViewModel item) { if (userRoleId != item.Id || userRoleId == 0) { return new UnprocessableEntityObjectResult(new Error("Validation Error", 100, $"Id [{userId}] mismatches [{item.Id}].")); } var (userRoleValid, userRoleError) = ValidateUserRole(userId, item); if (!userRoleValid) return userRoleError; var userRole = _context.UserRoles .Include(x => x.Role) .First(x => x.Id == item.Id); userRole.ExpiryDate = item.ExpiryDate; _context.SaveChanges(); return new StatusCodeResult(201); } /// <summary> /// Searches Users /// </summary> /// <remarks>Used for the search users.</remarks> /// <param name="districts">Districts (array of id numbers)</param> /// <param name="surname"></param> /// <param name="includeInactive">True if Inactive users will be returned</param> /// <response code="200">OK</response> public virtual IActionResult SearchUsers(int?[] districts, string surname, bool? includeInactive) { // Eager loading of related data var data = _context.Users .AsNoTracking() .Include(x => x.District) .Select(x => x); // Note that Districts searches SchoolBus Districts, not SchoolBusOwner Districts if (districts != null) { foreach (int? district in districts) { if (district != null) { data = data.Where(x => x.District.Id == district); } } } if (surname != null) { data = data.Where(x => x.Surname.ToLower().Contains(surname.ToLower())); } if (includeInactive == null || includeInactive == false) { data = data.Where(x => x.Active == true); } // now convert the results to the view model. var result = Mapper.Map<List<UserListViewModel>>(data); return new ObjectResult(result); } public IActionResult GetInspectors(bool? includeInactive = false) { var data = _context.UserRoles .AsNoTracking() .Where(ur => ur.Role.Name == Roles.Inspector); if (includeInactive == null || includeInactive == false) { data = data.Where(ur => !ur.ExpiryDate.HasValue || ur.ExpiryDate == DateTime.MinValue || ur.ExpiryDate > DateTime.Now); } var inspectors = data .Select(ur => ur.User) .Where(u => u.Active == true); var result = Mapper.Map<List<InspectorViewModel>>(inspectors); return new ObjectResult(result); } private (bool success, UnprocessableEntityObjectResult errorResult) ValidateSmUserId(UserViewModel user) { if (user.Id > 0) { if (_context.Users.Any(x => x.Id != user.Id && x.SmUserId.ToUpper() == user.SmUserId.ToUpper())) { return (false, new UnprocessableEntityObjectResult(new Error("Validation Error", 301, $"An active/expired user with ID [{user.SmUserId}] already exists. Please check current user, or re-instate the expired user."))); } } else { if (_context.Users.Any(x => x.SmUserId.ToUpper() == user.SmUserId.ToUpper())) { return (false, new UnprocessableEntityObjectResult(new Error("Validation Error", 302, $"An active/expired user with ID [{user.SmUserId}] already exists. Please check current user, or re-instate the expired user."))); } } return (true, null); } private (bool success, UnprocessableEntityObjectResult errorResult) ValidateDistrict(UserViewModel user) { if (user.District == null) { return (false, new UnprocessableEntityObjectResult(new Error("Validation Error", 303, $"District is mandatory."))); } if (!_context.Districts.Any(x => x.Id == user.District.Id)) { return (false, new UnprocessableEntityObjectResult(new Error("Validation Error", 304, $"District ID [{user.District.Id}] does not exist."))); } return (true, null); } private (bool success, UnprocessableEntityObjectResult errorResult) ValidateUserRole(int userId, UserRoleViewModel userRole) { if (!_context.Users.Any(x => x.Id == userId)) { return (false, new UnprocessableEntityObjectResult(new Error("Validation Error", 305, $"User does not exist."))); } if (!_context.Roles.Any(x => x.Id == userRole.RoleId)) { return (false, new UnprocessableEntityObjectResult(new Error("Validation Error", 306, $"Role does not exist."))); } var userRoleExists = _context.UserRoles.Any(x => x.UserId == userId && x.RoleId == userRole.RoleId); if (userRole.Id == null || userRole.Id == 0) //new user role { if (userRoleExists) return (false, new UnprocessableEntityObjectResult(new Error("Validation Error", 307, $"The role is already assigned to the user."))); } else { if (!userRoleExists) return (false, new UnprocessableEntityObjectResult(new Error("Validation Error", 308, $"The user does not have the role to update."))); } var inspectorRole = _context.Roles .AsNoTracking() .FirstOrDefault(u => u.Name == Roles.Inspector); if (userRole.RoleId == inspectorRole.Id && userRole.ExpiryDate != null && !IsInspectorRoleRemovable(userRole.UserId)) { return (false, new UnprocessableEntityObjectResult(new Error("Validation Error", 309, $"There are buses assigned to the user. Please reassign the buses to other inspector(s), and then remove Inspector role from the user."))); } var role = _context.Roles.First(x => x.Id == userRole.RoleId); if (!User.IsSystemAdmin() && !CurrentUserHasAllThePermissions(userRole.RoleId)) { return (false, new UnprocessableEntityObjectResult(new Error("Authorization Error", 399, $"You don't have enough permissions to handle the role [{role.Name}]"))); } return (true, null); } private bool IsInspectorRoleRemovable(int userId) { return !_context.SchoolBuss.Any(x => x.InspectorId == userId); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; namespace Microsoft.Azure.Commands.Compute.Automation { public partial class InvokeAzureComputeMethodCmdlet : ComputeAutomationBaseCmdlet { protected object CreateVirtualMachineRunCommandDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pResourceGroupName = new RuntimeDefinedParameter(); pResourceGroupName.Name = "ResourceGroupName"; pResourceGroupName.ParameterType = typeof(string); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = true }); pResourceGroupName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ResourceGroupName", pResourceGroupName); var pVMName = new RuntimeDefinedParameter(); pVMName.Name = "VMName"; pVMName.ParameterType = typeof(string); pVMName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = true }); pVMName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("VMName", pVMName); var pParameters = new RuntimeDefinedParameter(); pParameters.Name = "RunCommandInput"; pParameters.ParameterType = typeof(RunCommandInput); pParameters.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = true }); pParameters.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("RunCommandInput", pParameters); var pArgumentList = new RuntimeDefinedParameter(); pArgumentList.Name = "ArgumentList"; pArgumentList.ParameterType = typeof(object[]); pArgumentList.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByStaticParameters", Position = 4, Mandatory = true }); pArgumentList.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ArgumentList", pArgumentList); return dynamicParameters; } protected void ExecuteVirtualMachineRunCommandMethod(object[] invokeMethodInputParameters) { string resourceGroupName = (string)ParseParameter(invokeMethodInputParameters[0]); string vmName = (string)ParseParameter(invokeMethodInputParameters[1]); RunCommandInput parameters = (RunCommandInput)ParseParameter(invokeMethodInputParameters[2]); var result = VirtualMachinesClient.RunCommand(resourceGroupName, vmName, parameters); WriteObject(result); } } public partial class NewAzureComputeArgumentListCmdlet : ComputeAutomationBaseCmdlet { protected PSArgument[] CreateVirtualMachineRunCommandParameters() { string resourceGroupName = string.Empty; string vmName = string.Empty; RunCommandInput parameters = new RunCommandInput(); return ConvertFromObjectsToArguments( new string[] { "ResourceGroupName", "VMName", "Parameters" }, new object[] { resourceGroupName, vmName, parameters }); } } [Cmdlet(VerbsLifecycle.Invoke, "AzureRmVMRunCommand", DefaultParameterSetName = "DefaultParameter", SupportsShouldProcess = true)] [OutputType(typeof(PSRunCommandResult))] public partial class InvokeAzureRmVMRunCommand : ComputeAutomationBaseCmdlet { public override void ExecuteCmdlet() { ExecuteClientAction(() => { if (ShouldProcess(this.VMName, VerbsLifecycle.Invoke)) { string resourceGroupName = this.ResourceGroupName; string vmName = this.VMName; RunCommandInput parameters = new RunCommandInput(); parameters.CommandId = this.CommandId; if (this.ScriptPath != null) { parameters.Script = new List<string>(); PathIntrinsics currentPath = SessionState.Path; var filePath = new System.IO.FileInfo(currentPath.GetUnresolvedProviderPathFromPSPath(this.ScriptPath)); string fileContent = Commands.Common.Authentication.Abstractions.FileUtilities.DataStore.ReadFileAsText(filePath.FullName); parameters.Script = fileContent.Split(new string[] { "\r\n", "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries); } if (this.Parameter != null) { var vParameter = new List<RunCommandInputParameter>(); foreach (var key in this.Parameter.Keys) { RunCommandInputParameter p = new RunCommandInputParameter(); p.Name = key.ToString(); p.Value = this.Parameter[key].ToString(); vParameter.Add(p); } parameters.Parameters = vParameter; } if (this.VM != null) { vmName = VM.Name; resourceGroupName = VM.ResourceGroupName; } var result = VirtualMachinesClient.RunCommand(resourceGroupName, vmName, parameters); var psObject = new PSRunCommandResult(); ComputeAutomationAutoMapperProfile.Mapper.Map<RunCommandResult, PSRunCommandResult>(result, psObject); WriteObject(psObject); } }); } [Parameter( ParameterSetName = "DefaultParameter", Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false)] [AllowNull] [ResourceManager.Common.ArgumentCompleters.ResourceGroupCompleter()] public string ResourceGroupName { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false)] [Alias("Name")] [AllowNull] public string VMName { get; set; } [Parameter( Mandatory = true)] [AllowNull] public string CommandId { get; set; } [Parameter( Mandatory = false)] [AllowNull] public string ScriptPath { get; set; } [Parameter( Mandatory = false)] [AllowNull] public Hashtable Parameter { get; set; } [Alias("VMProfile")] [Parameter( ParameterSetName = "VMParameter", Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] [ValidateNotNullOrEmpty] public Compute.Models.PSVirtualMachine VM { get; set; } [Parameter(Mandatory = false, HelpMessage = "Run cmdlet in the background")] public SwitchParameter AsJob { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Plugin.TextToSpeech.Abstractions; using Java.Util; using Android.Speech.Tts; using Android.App; using Android.OS; namespace Plugin.TextToSpeech { /// <summary> /// Text to speech implementation Android /// </summary> public class TextToSpeech : Java.Lang.Object, ITextToSpeech, Android.Speech.Tts.TextToSpeech.IOnInitListener, IDisposable { Android.Speech.Tts.TextToSpeech textToSpeech; string text; CrossLocale? language; float pitch, speakRate; bool queue; bool initialized; /// <summary> /// Default constructor /// </summary> public TextToSpeech() { } /// <summary> /// Initialize TTS /// </summary> public void Init() { Console.WriteLine("Current version: " + (int)global::Android.OS.Build.VERSION.SdkInt); Android.Util.Log.Info("CrossTTS", "Current version: " + (int)global::Android.OS.Build.VERSION.SdkInt); textToSpeech = new Android.Speech.Tts.TextToSpeech(Application.Context, this); } #region IOnInitListener implementation /// <summary> /// OnInit of TTS /// </summary> /// <param name="status"></param> public void OnInit(OperationResult status) { if (status.Equals(OperationResult.Success)) { initialized = true; Speak(); } } #endregion /// <summary> /// Speak back text /// </summary> /// <param name="text">Text to speak</param> /// <param name="queue">If you want to chain together speak command or cancel current</param> /// <param name="crossLocale">Locale of voice</param> /// <param name="pitch">Pitch of voice</param> /// <param name="speakRate">Speak Rate of voice (All) (0.0 - 2.0f)</param> /// <param name="volume">Volume of voice (iOS/WP) (0.0-1.0)</param> public void Speak(string text, bool queue = false, CrossLocale? crossLocale = null, float? pitch = null, float? speakRate = null, float? volume = null) { this.text = text; this.language = crossLocale; this.pitch = pitch == null ? 1.0f : pitch.Value; this.speakRate = speakRate == null ? 1.0f : speakRate.Value; this.queue = queue; if (textToSpeech == null || !initialized) { Init(); } else { Speak(); } } private void SetDefaultLanguage() { SetDefaultLanguageNonLollipop(); } private void SetDefaultLanguageNonLollipop() { //disable warning because we are checking ahead of time. #pragma warning disable 0618 var sdk = (int)global::Android.OS.Build.VERSION.SdkInt; if (sdk >= 18) { try { #if __ANDROID_18__ if (textToSpeech.DefaultLanguage == null && textToSpeech.Language != null) textToSpeech.SetLanguage(textToSpeech.Language); else if (textToSpeech.DefaultLanguage != null) textToSpeech.SetLanguage(textToSpeech.DefaultLanguage); #endif } catch { if (textToSpeech.Language != null) textToSpeech.SetLanguage(textToSpeech.Language); } } else { if (textToSpeech.Language != null) textToSpeech.SetLanguage(textToSpeech.Language); } #pragma warning restore 0618 } /// <summary> /// In a different method as it can crash on older target/compile for some reason /// </summary> private void SetDefaultLanguageLollipop() { /*if (textToSpeech.DefaultVoice != null) { textToSpeech.SetVoice(textToSpeech.DefaultVoice); if (textToSpeech.DefaultVoice.Locale != null) textToSpeech.SetLanguage(textToSpeech.DefaultVoice.Locale); } else SetDefaultLanguageNonLollipop();*/ } private void Speak() { if (string.IsNullOrWhiteSpace(text)) return; if (!queue && textToSpeech.IsSpeaking) textToSpeech.Stop(); if (language.HasValue && !string.IsNullOrWhiteSpace(language.Value.Language)) { Locale locale = null; if (!string.IsNullOrWhiteSpace(language.Value.Country)) locale = new Locale(language.Value.Language, language.Value.Country); else locale = new Locale(language.Value.Language); var result = textToSpeech.IsLanguageAvailable(locale); if (result == LanguageAvailableResult.CountryAvailable) { textToSpeech.SetLanguage(locale); } else { Console.WriteLine("Locale: " + locale + " was not valid, setting to default."); SetDefaultLanguage(); } } else { SetDefaultLanguage(); } textToSpeech.SetPitch(pitch); textToSpeech.SetSpeechRate(speakRate); textToSpeech.Speak(text, queue ? QueueMode.Add : QueueMode.Flush, null); } /// <summary> /// Get all installed and valide lanaguages /// </summary> /// <returns>List of CrossLocales</returns> public IEnumerable<CrossLocale> GetInstalledLanguages() { if (textToSpeech != null && initialized) { int version = (int)global::Android.OS.Build.VERSION.SdkInt; bool isLollipop = version >= 21; if (isLollipop) { try { //in a different method as it can crash on older target/compile for some reason return GetInstalledLanguagesLollipop(); } catch (Exception ex) { Console.WriteLine("Something went horribly wrong, defaulting to old implementation to get languages: " + ex); } } var languages = new List<CrossLocale>(); var allLocales = Locale.GetAvailableLocales(); foreach (var locale in allLocales) { try { var result = textToSpeech.IsLanguageAvailable(locale); if (result == LanguageAvailableResult.CountryAvailable) { languages.Add(new CrossLocale { Country = locale.Country, Language = locale.Language, DisplayName = locale.DisplayName }); } } catch (Exception ex) { Console.WriteLine("Error checking language; " + locale + " " + ex); } } return languages.GroupBy(c => c.ToString()) .Select(g => g.First()); } else { return Locale.GetAvailableLocales() .Where(a => !string.IsNullOrWhiteSpace(a.Language) && !string.IsNullOrWhiteSpace(a.Country)) .Select(a => new CrossLocale { Country = a.Country, Language = a.Language, DisplayName = a.DisplayName }) .GroupBy(c => c.ToString()) .Select(g => g.First()); } } /// <summary> /// In a different method as it can crash on older target/compile for some reason /// </summary> /// <returns></returns> private IEnumerable<CrossLocale> GetInstalledLanguagesLollipop() { var sdk = (int)global::Android.OS.Build.VERSION.SdkInt; if (sdk < 21) return new List<CrossLocale>(); #if __ANDROID_21__ return textToSpeech.AvailableLanguages .Select(a => new CrossLocale { Country = a.Country, Language = a.Language, DisplayName = a.DisplayName }); #endif } void IDisposable.Dispose() { if (textToSpeech != null) { textToSpeech.Stop(); textToSpeech.Dispose(); textToSpeech = null; } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: BitConverter ** ** ** Purpose: Allows developers to view the base data types as ** an arbitrary array of bits. ** ** ===========================================================*/ namespace System { using System; using System.Runtime.CompilerServices; using System.Diagnostics.Contracts; using System.Security; // The BitConverter class contains methods for // converting an array of bytes to one of the base data // types, as well as for converting a base data type to an // array of bytes. // // Only statics, does not need to be marked with the serializable attribute public static class BitConverter { #if MONO public static readonly bool IsLittleEndian = AmILittleEndian (); static unsafe bool AmILittleEndian () { // binary representations of 1.0: // big endian: 3f f0 00 00 00 00 00 00 // little endian: 00 00 00 00 00 00 f0 3f double d = 1.0; byte *b = (byte*)&d; return (b [0] == 0); } #else // This field indicates the "endianess" of the architecture. // The value is set to true if the architecture is // little endian; false if it is big endian. #if BIGENDIAN public static readonly bool IsLittleEndian /* = false */; #else public static readonly bool IsLittleEndian = true; #endif #endif // Converts a byte into an array of bytes with length one. public static byte[] GetBytes(bool value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 1); byte[] r = new byte[1]; r[0] = (value ? (byte)Boolean.True : (byte)Boolean.False ); return r; } // Converts a char into an array of bytes with length two. public static byte[] GetBytes(char value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 2); return GetBytes((short)value); } // Converts a short into an array of bytes with length // two. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static byte[] GetBytes(short value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 2); byte[] bytes = new byte[2]; fixed(byte* b = bytes) *((short*)b) = value; return bytes; } // Converts an int into an array of bytes with length // four. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static byte[] GetBytes(int value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 4); byte[] bytes = new byte[4]; fixed(byte* b = bytes) *((int*)b) = value; return bytes; } // Converts a long into an array of bytes with length // eight. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static byte[] GetBytes(long value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 8); byte[] bytes = new byte[8]; fixed(byte* b = bytes) *((long*)b) = value; return bytes; } // Converts an ushort into an array of bytes with // length two. [CLSCompliant(false)] public static byte[] GetBytes(ushort value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 2); return GetBytes((short)value); } // Converts an uint into an array of bytes with // length four. [CLSCompliant(false)] public static byte[] GetBytes(uint value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 4); return GetBytes((int)value); } // Converts an unsigned long into an array of bytes with // length eight. [CLSCompliant(false)] public static byte[] GetBytes(ulong value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 8); return GetBytes((long)value); } // Converts a float into an array of bytes with length // four. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static byte[] GetBytes(float value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 4); return GetBytes(*(int*)&value); } // Converts a double into an array of bytes with length // eight. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static byte[] GetBytes(double value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 8); return GetBytes(*(long*)&value); } // Converts an array of bytes into a char. public static char ToChar(byte[] value, int startIndex) { if (value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } if ((uint)startIndex >= value.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } if (startIndex > value.Length - 2) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } Contract.EndContractBlock(); return (char)ToInt16(value, startIndex); } // Converts an array of bytes into a short. [System.Security.SecuritySafeCritical] // auto-generated public static unsafe short ToInt16(byte[] value, int startIndex) { if( value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } if ((uint) startIndex >= value.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } if (startIndex > value.Length -2) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } Contract.EndContractBlock(); fixed( byte * pbyte = &value[startIndex]) { if( startIndex % 2 == 0) { // data is aligned return *((short *) pbyte); } else { if( IsLittleEndian) { return (short)((*pbyte) | (*(pbyte + 1) << 8)) ; } else { return (short)((*pbyte << 8) | (*(pbyte + 1))); } } } } // Converts an array of bytes into an int. [System.Security.SecuritySafeCritical] // auto-generated public static unsafe int ToInt32 (byte[] value, int startIndex) { if( value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } if ((uint) startIndex >= value.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } if (startIndex > value.Length -4) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } Contract.EndContractBlock(); fixed( byte * pbyte = &value[startIndex]) { if( startIndex % 4 == 0) { // data is aligned return *((int *) pbyte); } else { if( IsLittleEndian) { return (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24); } else { return (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3)); } } } } // Converts an array of bytes into a long. [System.Security.SecuritySafeCritical] // auto-generated public static unsafe long ToInt64 (byte[] value, int startIndex) { if (value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } if ((uint) startIndex >= value.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } if (startIndex > value.Length -8) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } Contract.EndContractBlock(); fixed( byte * pbyte = &value[startIndex]) { if( startIndex % 8 == 0) { // data is aligned return *((long *) pbyte); } else { if( IsLittleEndian) { int i1 = (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24); int i2 = (*(pbyte+4)) | (*(pbyte + 5) << 8) | (*(pbyte + 6) << 16) | (*(pbyte + 7) << 24); return (uint)i1 | ((long)i2 << 32); } else { int i1 = (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3)); int i2 = (*(pbyte+4) << 24) | (*(pbyte + 5) << 16) | (*(pbyte + 6) << 8) | (*(pbyte + 7)); return (uint)i2 | ((long)i1 << 32); } } } } // Converts an array of bytes into an ushort. // [CLSCompliant(false)] public static ushort ToUInt16(byte[] value, int startIndex) { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); if ((uint)startIndex >= value.Length) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); if (startIndex > value.Length - 2) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); Contract.EndContractBlock(); return (ushort)ToInt16(value, startIndex); } // Converts an array of bytes into an uint. // [CLSCompliant(false)] public static uint ToUInt32(byte[] value, int startIndex) { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); if ((uint)startIndex >= value.Length) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); if (startIndex > value.Length - 4) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); Contract.EndContractBlock(); return (uint)ToInt32(value, startIndex); } // Converts an array of bytes into an unsigned long. // [CLSCompliant(false)] public static ulong ToUInt64(byte[] value, int startIndex) { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); if ((uint)startIndex >= value.Length) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); if (startIndex > value.Length - 8) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); Contract.EndContractBlock(); return (ulong)ToInt64(value, startIndex); } // Converts an array of bytes into a float. [System.Security.SecuritySafeCritical] // auto-generated unsafe public static float ToSingle (byte[] value, int startIndex) { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); if ((uint)startIndex >= value.Length) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); if (startIndex > value.Length - 4) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); Contract.EndContractBlock(); int val = ToInt32(value, startIndex); return *(float*)&val; } // Converts an array of bytes into a double. [System.Security.SecuritySafeCritical] // auto-generated unsafe public static double ToDouble (byte[] value, int startIndex) { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); if ((uint)startIndex >= value.Length) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); if (startIndex > value.Length - 8) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); Contract.EndContractBlock(); long val = ToInt64(value, startIndex); return *(double*)&val; } private static char GetHexValue(int i) { Contract.Assert( i >=0 && i <16, "i is out of range."); if (i<10) { return (char)(i + '0'); } return (char)(i - 10 + 'A'); } // Converts an array of bytes into a String. public static String ToString (byte[] value, int startIndex, int length) { if (value == null) { throw new ArgumentNullException("byteArray"); } if (startIndex < 0 || startIndex >= value.Length && startIndex > 0) { // Don't throw for a 0 length array. throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex")); } if (length < 0) { throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive")); } if (startIndex > value.Length - length) { throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall")); } Contract.EndContractBlock(); if (length == 0) { return string.Empty; } if (length > (Int32.MaxValue / 3)) { // (Int32.MaxValue / 3) == 715,827,882 Bytes == 699 MB throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_LengthTooLarge", (Int32.MaxValue / 3))); } int chArrayLength = length * 3; char[] chArray = new char[chArrayLength]; int i = 0; int index = startIndex; for (i = 0; i < chArrayLength; i += 3) { byte b = value[index++]; chArray[i]= GetHexValue(b/16); chArray[i+1] = GetHexValue(b%16); chArray[i+2] = '-'; } // We don't need the last '-' character return new String(chArray, 0, chArray.Length - 1); } // Converts an array of bytes into a String. public static String ToString(byte [] value) { if (value == null) throw new ArgumentNullException("value"); Contract.Ensures(Contract.Result<String>() != null); Contract.EndContractBlock(); return ToString(value, 0, value.Length); } // Converts an array of bytes into a String. public static String ToString (byte [] value, int startIndex) { if (value == null) throw new ArgumentNullException("value"); Contract.Ensures(Contract.Result<String>() != null); Contract.EndContractBlock(); return ToString(value, startIndex, value.Length - startIndex); } /*==================================ToBoolean=================================== **Action: Convert an array of bytes to a boolean value. We treat this array ** as if the first 4 bytes were an Int4 an operate on this value. **Returns: True if the Int4 value of the first 4 bytes is non-zero. **Arguments: value -- The byte array ** startIndex -- The position within the array. **Exceptions: See ToInt4. ==============================================================================*/ // Converts an array of bytes into a boolean. public static bool ToBoolean(byte[] value, int startIndex) { if (value==null) throw new ArgumentNullException("value"); if (startIndex < 0) throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (startIndex > value.Length - 1) throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); Contract.EndContractBlock(); return (value[startIndex]==0)?false:true; } [SecuritySafeCritical] public static unsafe long DoubleToInt64Bits(double value) { // If we're on a big endian machine, what should this method do? You could argue for // either big endian or little endian, depending on whether you are writing to a file that // should be used by other programs on that processor, or for compatibility across multiple // formats. Because this is ambiguous, we're excluding this from the Portable Library & Win8 Profile. // If we ever run on big endian machines, produce two versions where endianness is specified. Contract.Assert(IsLittleEndian, "This method is implemented assuming little endian with an ambiguous spec."); return *((long *)&value); } [SecuritySafeCritical] public static unsafe double Int64BitsToDouble(long value) { // If we're on a big endian machine, what should this method do? You could argue for // either big endian or little endian, depending on whether you are writing to a file that // should be used by other programs on that processor, or for compatibility across multiple // formats. Because this is ambiguous, we're excluding this from the Portable Library & Win8 Profile. // If we ever run on big endian machines, produce two versions where endianness is specified. Contract.Assert(IsLittleEndian, "This method is implemented assuming little endian with an ambiguous spec."); return *((double*)&value); } } }
using System; using MonoTouch.Dialog; using System.Drawing; #if XAMCORE_2_0 using UIKit; using Foundation; using CoreGraphics; #else using MonoTouch.UIKit; using MonoTouch.Foundation; using MonoTouch.CoreGraphics; #endif #if !XAMCORE_2_0 using nint = global::System.Int32; using nuint = global::System.UInt32; using nfloat = global::System.Single; using CGSize = global::System.Drawing.SizeF; using CGPoint = global::System.Drawing.PointF; using CGRect = global::System.Drawing.RectangleF; #endif namespace MonoTouch.Dialog { // public class SignatureElement : UIViewElement // { // private const string CELL_IDENTIFIER = "SignatureCell"; // private DrawView _drawView; // // public SignatureElement (UIViewController parent) : base(string.Empty, new DrawView(new CGRect(5f,5f,1000,200), parent), false) // { // base.Flags = UIViewElement.CellFlags.DisableSelection; // _drawView = (DrawView)base.View; // } // // public override UITableViewCell GetCell (UITableView tv) // { // var cell = base.GetCell (tv); // cell.ContentView.Frame.Height = _drawView.Frame.Height + 50; // _drawView.Frame.Width = cell.Frame.Width - 10; // // return cell; // } // } public class CapturePhotoElement : Element, IElementSizing { public bool IsReadOnly { get; set; } public bool Mandatory { get; set; } public UIImage Value { get; set; } public string Base64Value { get { if (Value != null) { return Convert.ToBase64String(this.Value.AsJPEG().ToArray()); } else { return string.Empty; } } set { if (!String.IsNullOrWhiteSpace(value)) this.Value = UIImage.LoadFromData(NSData.FromArray(Convert.FromBase64String(value))); else this.Value = null; } } protected bool _showSelector = false; protected string _selectorCancelLabel = "Cancel"; protected string _selectorTakePhotoLabel = "Take photo"; protected string _selectorPickImageLabel = "Pick image"; protected string _deleteButtonLabel = "Delete"; float newHeight = 1024f; static NSString hkey = new NSString("CapturePhotoElement"); public CapturePhotoElement(string caption) : base(caption) { } public CapturePhotoElement(string caption, string base64value, bool showSelector, string selectorTakePhotoLabel, string selectorPickImageLabel,string deleteButton, bool isReadOnly) : this(caption) { this.Base64Value = base64value; this._showSelector = showSelector; if (!string.IsNullOrWhiteSpace(selectorPickImageLabel)) this._selectorPickImageLabel = selectorPickImageLabel; if (!string.IsNullOrWhiteSpace(selectorTakePhotoLabel)) this._selectorTakePhotoLabel = selectorTakePhotoLabel; this.IsReadOnly = isReadOnly; } public CapturePhotoElement(string caption, string base64value) : this(caption, base64value, false, null, null,null, false) { } protected override NSString CellKey { get { return hkey; } } #region IElementSizing implementation public virtual nfloat GetHeight(UITableView tableView, NSIndexPath indexPath) { return 200; } #endregion protected override UITableViewCellStyle CellStyle => UITableViewCellStyle.Default; public override UITableViewCell GetCell(UITableView tv) { //var cell = tv.DequeueReusableCell(CellKey); var cell = base.GetCell(tv); // if (cell == null) //{ // cell = new UITableViewCell(UITableViewCellStyle.Default, CellKey); // cell.SelectionStyle = UITableViewCellSelectionStyle.Blue; //} cell.Accessory = UITableViewCellAccessory.DisclosureIndicator; //cell.TextLabel.Font = UIFont.BoldSystemFontOfSize(17); //s.agostini cell.TextLabel.Text = Caption; if (this.Mandatory) cell.TextLabel.Text += '*'; //cell.TextLabel.TextColor = UIColor.Purple; if (!IsReadOnly) { if (this.Value != null) { cell.BackgroundColor = UIColor.FromRGB(1f, 1f, 0.8f); cell.ImageView.Image = this.Value; //cell.ImageView.Frame.X = 20; } else { cell.BackgroundColor = UIColor.White; cell.ImageView.Image = this.Value; } } else { cell.SelectionStyle = UITableViewCellSelectionStyle.None; cell.Selected = false; cell.ImageView.Image = this.Value; } return cell; } // We use this class to dispose the web control when it is not // in use, as it could be a bit of a pig, and we do not want to // wait for the GC to kick-in. /* class CapturePhotoViewController : UIViewController { public CapturePhotoViewController (SignatureElement container) : base () { this.View.BackgroundColor = UIColor.FromWhiteAlpha (1f, 0.3f); } public override void ViewWillDisappear (bool animated) { base.ViewWillDisappear (animated); } public bool Autorotate { get; set; } // public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation) // { // return Autorotate; // } } */ public override void Selected(DialogViewController dvc, UITableView tableView, NSIndexPath path) { if (IsReadOnly) { return; } else { var PhotoVC = new PhotoViewController(_selectorPickImageLabel, _selectorTakePhotoLabel,_deleteButtonLabel) { Title = Caption }; dvc.ActivateController(PhotoVC); PhotoVC.SendResponse += (s, e) => { //if (e.Value != null) Value = e.Value; //OnSendResponse(e.Value); }; } } //public event EventHandler<CapturePhotoEventArgs> SendResponse; //private void OnSendResponse(UIImage image) //{ // if (SendResponse != null) // { // SendResponse(this, new CapturePhotoEventArgs { Value = image }); // } //} //public class CapturePhotoEventArgs : EventArgs //{ // public UIImage Value { get; set; } //} } }
using System.Collections.Generic; using Content.Server.Weapon.Ranged.Ammunition.Components; using Content.Server.Weapon.Ranged.Barrels.Components; using Content.Shared.Examine; using Content.Shared.Interaction; using Content.Shared.Verbs; using Content.Shared.Weapons.Ranged.Barrels.Components; using Robust.Shared.Audio; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.GameStates; using Robust.Shared.Localization; using Robust.Shared.Map; using Robust.Shared.Player; namespace Content.Server.Weapon.Ranged; public sealed partial class GunSystem { private void AddToggleBoltVerb(EntityUid uid, BoltActionBarrelComponent component, GetVerbsEvent<InteractionVerb> args) { if (args.Hands == null || !args.CanAccess || !args.CanInteract) return; InteractionVerb verb = new() { Text = component.BoltOpen ? Loc.GetString("close-bolt-verb-get-data-text") : Loc.GetString("open-bolt-verb-get-data-text"), Act = () => component.BoltOpen = !component.BoltOpen }; args.Verbs.Add(verb); } private void OnBoltExamine(EntityUid uid, BoltActionBarrelComponent component, ExaminedEvent args) { args.PushMarkup(Loc.GetString("bolt-action-barrel-component-on-examine", ("caliber", component.Caliber))); } private void OnBoltFireAttempt(EntityUid uid, BoltActionBarrelComponent component, GunFireAttemptEvent args) { if (args.Cancelled) return; if (component.BoltOpen || component.ChamberContainer.ContainedEntity == null) args.Cancel(); } private void OnBoltMapInit(EntityUid uid, BoltActionBarrelComponent component, MapInitEvent args) { if (component.FillPrototype != null) { component.UnspawnedCount += component.Capacity; if (component.UnspawnedCount > 0) { component.UnspawnedCount--; var chamberEntity = EntityManager.SpawnEntity(component.FillPrototype, EntityManager.GetComponent<TransformComponent>(uid).Coordinates); component.ChamberContainer.Insert(chamberEntity); } } UpdateBoltAppearance(component); } public void UpdateBoltAppearance(BoltActionBarrelComponent component) { if (!TryComp(component.Owner, out AppearanceComponent? appearanceComponent)) return; appearanceComponent.SetData(BarrelBoltVisuals.BoltOpen, component.BoltOpen); appearanceComponent.SetData(AmmoVisuals.AmmoCount, component.ShotsLeft); appearanceComponent.SetData(AmmoVisuals.AmmoMax, component.Capacity); } private void OnBoltInit(EntityUid uid, BoltActionBarrelComponent component, ComponentInit args) { component.SpawnedAmmo = new Stack<EntityUid>(component.Capacity - 1); component.AmmoContainer = uid.EnsureContainer<Container>($"{component.GetType()}-ammo-container", out var existing); if (existing) { foreach (var entity in component.AmmoContainer.ContainedEntities) { component.SpawnedAmmo.Push(entity); component.UnspawnedCount--; } } component.ChamberContainer = uid.EnsureContainer<ContainerSlot>($"{component.GetType()}-chamber-container"); if (TryComp(uid, out AppearanceComponent? appearanceComponent)) { appearanceComponent.SetData(MagazineBarrelVisuals.MagLoaded, true); } component.Dirty(EntityManager); UpdateBoltAppearance(component); } private void OnBoltUse(EntityUid uid, BoltActionBarrelComponent component, UseInHandEvent args) { if (args.Handled) return; args.Handled = true; if (component.BoltOpen) { component.BoltOpen = false; _popup.PopupEntity(Loc.GetString("bolt-action-barrel-component-bolt-closed"), uid, Filter.Entities(args.User)); return; } CycleBolt(component, true); } private void CycleBolt(BoltActionBarrelComponent component, bool manual = false) { TryEjectChamber(component); TryFeedChamber(component); if (component.ChamberContainer.ContainedEntity == null && manual) { component.BoltOpen = true; if (_container.TryGetContainingContainer(component.Owner, out var container)) { _popup.PopupEntity(Loc.GetString("bolt-action-barrel-component-bolt-opened"), container.Owner, Filter.Entities(container.Owner)); } return; } else { SoundSystem.Play(Filter.Pvs(component.Owner), component.SoundCycle.GetSound(), component.Owner, AudioParams.Default.WithVolume(-2)); } component.Dirty(EntityManager); UpdateBoltAppearance(component); } public bool TryEjectChamber(BoltActionBarrelComponent component) { if (component.ChamberContainer.ContainedEntity is {Valid: true} chambered) { if (!component.ChamberContainer.Remove(chambered)) return false; if (TryComp(chambered, out AmmoComponent? ammoComponent) && !ammoComponent.Caseless) EjectCasing(chambered); return true; } return false; } public bool TryFeedChamber(BoltActionBarrelComponent component) { if (component.ChamberContainer.ContainedEntity != null) { return false; } if (component.SpawnedAmmo.TryPop(out var next)) { component.AmmoContainer.Remove(next); component.ChamberContainer.Insert(next); return true; } else if (component.UnspawnedCount > 0) { component.UnspawnedCount--; var ammoEntity = EntityManager.SpawnEntity(component.FillPrototype, EntityManager.GetComponent<TransformComponent>(component.Owner).Coordinates); component.ChamberContainer.Insert(ammoEntity); return true; } return false; } private void OnBoltInteractUsing(EntityUid uid, BoltActionBarrelComponent component, InteractUsingEvent args) { if (args.Handled) return; if (TryInsertBullet(args.User, args.Used, component)) args.Handled = true; } public bool TryInsertBullet(EntityUid user, EntityUid ammo, BoltActionBarrelComponent component) { if (!TryComp(ammo, out AmmoComponent? ammoComponent)) return false; if (ammoComponent.Caliber != component.Caliber) { _popup.PopupEntity(Loc.GetString("bolt-action-barrel-component-try-insert-bullet-wrong-caliber"), component.Owner, Filter.Entities(user)); return false; } if (!component.BoltOpen) { _popup.PopupEntity(Loc.GetString("bolt-action-barrel-component-try-insert-bullet-bolt-closed"), component.Owner, Filter.Entities(user)); return false; } if (component.ChamberContainer.ContainedEntity == null) { component.ChamberContainer.Insert(ammo); SoundSystem.Play(Filter.Pvs(component.Owner), component.SoundInsert.GetSound(), component.Owner, AudioParams.Default.WithVolume(-2)); component.Dirty(EntityManager); UpdateBoltAppearance(component); return true; } if (component.AmmoContainer.ContainedEntities.Count < component.Capacity - 1) { component.AmmoContainer.Insert(ammo); component.SpawnedAmmo.Push(ammo); SoundSystem.Play(Filter.Pvs(component.Owner), component.SoundInsert.GetSound(), component.Owner, AudioParams.Default.WithVolume(-2)); component.Dirty(EntityManager); UpdateBoltAppearance(component); return true; } _popup.PopupEntity(Loc.GetString("bolt-action-barrel-component-try-insert-bullet-no-room"), component.Owner, Filter.Entities(user)); return false; } private void OnBoltGetState(EntityUid uid, BoltActionBarrelComponent component, ref ComponentGetState args) { (int, int)? count = (component.ShotsLeft, component.Capacity); var chamberedExists = component.ChamberContainer.ContainedEntity != null; // (Is one chambered?, is the bullet spend) var chamber = (chamberedExists, false); if (chamberedExists && TryComp<AmmoComponent?>(component.ChamberContainer.ContainedEntity!.Value, out var ammo)) { chamber.Item2 = ammo.Spent; } args.State = new BoltActionBarrelComponentState( chamber, component.FireRateSelector, count, component.SoundGunshot.GetSound()); } public EntityUid? PeekAmmo(BoltActionBarrelComponent component) { return component.ChamberContainer.ContainedEntity; } public EntityUid? TakeProjectile(BoltActionBarrelComponent component, EntityCoordinates spawnAt) { if (component.AutoCycle) { CycleBolt(component); } else { component.Dirty(EntityManager); } if (component.ChamberContainer.ContainedEntity is not {Valid: true} chamberEntity) return null; var ammoComponent = EntityManager.GetComponentOrNull<AmmoComponent>(chamberEntity); return ammoComponent == null ? null : TakeBullet(ammoComponent, spawnAt); } }
namespace Doozestan.Domain.Migrations { using System; using System.Data.Entity.Migrations; public partial class integrated : DbMigration { public override void Up() { CreateTable( "dbo.ClientClaims", c => new { Id = c.Int(nullable: false, identity: true), Type = c.String(nullable: false, maxLength: 250), Value = c.String(nullable: false, maxLength: 250), Client_Id = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Clients", t => t.Client_Id, cascadeDelete: true) .Index(t => t.Client_Id); CreateTable( "dbo.Clients", c => new { Id = c.Int(nullable: false, identity: true), Enabled = c.Boolean(nullable: false), ClientId = c.String(nullable: false, maxLength: 200), ClientName = c.String(nullable: false, maxLength: 200), ClientUri = c.String(maxLength: 2000), LogoUri = c.String(), RequireConsent = c.Boolean(nullable: false), AllowRememberConsent = c.Boolean(nullable: false), AllowAccessTokensViaBrowser = c.Boolean(nullable: false), Flow = c.Int(nullable: false), AllowClientCredentialsOnly = c.Boolean(nullable: false), LogoutUri = c.String(), LogoutSessionRequired = c.Boolean(nullable: false), RequireSignOutPrompt = c.Boolean(nullable: false), AllowAccessToAllScopes = c.Boolean(nullable: false), IdentityTokenLifetime = c.Int(nullable: false), AccessTokenLifetime = c.Int(nullable: false), AuthorizationCodeLifetime = c.Int(nullable: false), AbsoluteRefreshTokenLifetime = c.Int(nullable: false), SlidingRefreshTokenLifetime = c.Int(nullable: false), RefreshTokenUsage = c.Int(nullable: false), UpdateAccessTokenOnRefresh = c.Boolean(nullable: false), RefreshTokenExpiration = c.Int(nullable: false), AccessTokenType = c.Int(nullable: false), EnableLocalLogin = c.Boolean(nullable: false), IncludeJwtId = c.Boolean(nullable: false), AlwaysSendClientClaims = c.Boolean(nullable: false), PrefixClientClaims = c.Boolean(nullable: false), AllowAccessToAllGrantTypes = c.Boolean(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.ClientCorsOrigins", c => new { Id = c.Int(nullable: false, identity: true), Origin = c.String(nullable: false, maxLength: 150), Client_Id = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Clients", t => t.Client_Id, cascadeDelete: true) .Index(t => t.Client_Id); CreateTable( "dbo.ClientCustomGrantTypes", c => new { Id = c.Int(nullable: false, identity: true), GrantType = c.String(nullable: false, maxLength: 250), Client_Id = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Clients", t => t.Client_Id, cascadeDelete: true) .Index(t => t.Client_Id); CreateTable( "dbo.ClientIdPRestrictions", c => new { Id = c.Int(nullable: false, identity: true), Provider = c.String(nullable: false, maxLength: 200), Client_Id = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Clients", t => t.Client_Id, cascadeDelete: true) .Index(t => t.Client_Id); CreateTable( "dbo.ClientPostLogoutRedirectUris", c => new { Id = c.Int(nullable: false, identity: true), Uri = c.String(nullable: false, maxLength: 2000), Client_Id = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Clients", t => t.Client_Id, cascadeDelete: true) .Index(t => t.Client_Id); CreateTable( "dbo.ClientRedirectUris", c => new { Id = c.Int(nullable: false, identity: true), Uri = c.String(nullable: false, maxLength: 2000), Client_Id = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Clients", t => t.Client_Id, cascadeDelete: true) .Index(t => t.Client_Id); CreateTable( "dbo.ClientScopes", c => new { Id = c.Int(nullable: false, identity: true), Scope = c.String(nullable: false, maxLength: 200), Client_Id = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Clients", t => t.Client_Id, cascadeDelete: true) .Index(t => t.Client_Id); CreateTable( "dbo.ClientSecrets", c => new { Id = c.Int(nullable: false, identity: true), Value = c.String(nullable: false, maxLength: 250), Type = c.String(maxLength: 250), Description = c.String(maxLength: 2000), Expiration = c.DateTimeOffset(precision: 7), Client_Id = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Clients", t => t.Client_Id, cascadeDelete: true) .Index(t => t.Client_Id); CreateTable( "dbo.Consents", c => new { Subject = c.String(nullable: false, maxLength: 200), ClientId = c.String(nullable: false, maxLength: 200), Scopes = c.String(nullable: false, maxLength: 2000), }) .PrimaryKey(t => new { t.Subject, t.ClientId }); CreateTable( "dbo.Game", c => new { Id = c.Int(nullable: false, identity: true), Title = c.String(maxLength: 300), StartDate = c.DateTime(), EndDate = c.DateTime(), Status = c.Int(), WinnerId = c.String(maxLength: 128), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Tournament", c => new { Id = c.Int(nullable: false, identity: true), GameId = c.Int(nullable: false), UserId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Game", t => t.GameId) .Index(t => t.GameId); CreateTable( "dbo.Logs", c => new { Id = c.Int(nullable: false, identity: true), EventDateTime = c.DateTime(nullable: false), EventLevel = c.String(nullable: false, maxLength: 100), UserName = c.String(nullable: false, maxLength: 100), MachineName = c.String(nullable: false, maxLength: 100), EventMessage = c.String(nullable: false), ErrorSource = c.String(), ErrorClass = c.String(maxLength: 500), ErrorMethod = c.String(), InnerErrorMessage = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.ScopeClaims", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 200), Description = c.String(maxLength: 1000), AlwaysIncludeInIdToken = c.Boolean(nullable: false), Scope_Id = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Scopes", t => t.Scope_Id, cascadeDelete: true) .Index(t => t.Scope_Id); CreateTable( "dbo.Scopes", c => new { Id = c.Int(nullable: false, identity: true), Enabled = c.Boolean(nullable: false), Name = c.String(nullable: false, maxLength: 200), DisplayName = c.String(maxLength: 200), Description = c.String(maxLength: 1000), Required = c.Boolean(nullable: false), Emphasize = c.Boolean(nullable: false), Type = c.Int(nullable: false), IncludeAllClaimsForUser = c.Boolean(nullable: false), ClaimsRule = c.String(maxLength: 200), ShowInDiscoveryDocument = c.Boolean(nullable: false), AllowUnrestrictedIntrospection = c.Boolean(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.ScopeSecrets", c => new { Id = c.Int(nullable: false, identity: true), Description = c.String(maxLength: 1000), Expiration = c.DateTimeOffset(precision: 7), Type = c.String(maxLength: 250), Value = c.String(nullable: false, maxLength: 250), Scope_Id = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Scopes", t => t.Scope_Id, cascadeDelete: true) .Index(t => t.Scope_Id); CreateTable( "dbo.Tokens", c => new { Key = c.String(nullable: false, maxLength: 128), TokenType = c.Short(nullable: false), SubjectId = c.String(maxLength: 200), ClientId = c.String(nullable: false, maxLength: 200), JsonCode = c.String(nullable: false), Expiry = c.DateTimeOffset(nullable: false, precision: 7), }) .PrimaryKey(t => new { t.Key, t.TokenType }); } public override void Down() { DropForeignKey("dbo.ScopeClaims", "Scope_Id", "dbo.Scopes"); DropForeignKey("dbo.ScopeSecrets", "Scope_Id", "dbo.Scopes"); DropForeignKey("dbo.Tournament", "GameId", "dbo.Game"); DropForeignKey("dbo.ClientClaims", "Client_Id", "dbo.Clients"); DropForeignKey("dbo.ClientSecrets", "Client_Id", "dbo.Clients"); DropForeignKey("dbo.ClientScopes", "Client_Id", "dbo.Clients"); DropForeignKey("dbo.ClientRedirectUris", "Client_Id", "dbo.Clients"); DropForeignKey("dbo.ClientPostLogoutRedirectUris", "Client_Id", "dbo.Clients"); DropForeignKey("dbo.ClientIdPRestrictions", "Client_Id", "dbo.Clients"); DropForeignKey("dbo.ClientCustomGrantTypes", "Client_Id", "dbo.Clients"); DropForeignKey("dbo.ClientCorsOrigins", "Client_Id", "dbo.Clients"); DropIndex("dbo.ScopeSecrets", new[] { "Scope_Id" }); DropIndex("dbo.ScopeClaims", new[] { "Scope_Id" }); DropIndex("dbo.Tournament", new[] { "GameId" }); DropIndex("dbo.ClientSecrets", new[] { "Client_Id" }); DropIndex("dbo.ClientScopes", new[] { "Client_Id" }); DropIndex("dbo.ClientRedirectUris", new[] { "Client_Id" }); DropIndex("dbo.ClientPostLogoutRedirectUris", new[] { "Client_Id" }); DropIndex("dbo.ClientIdPRestrictions", new[] { "Client_Id" }); DropIndex("dbo.ClientCustomGrantTypes", new[] { "Client_Id" }); DropIndex("dbo.ClientCorsOrigins", new[] { "Client_Id" }); DropIndex("dbo.ClientClaims", new[] { "Client_Id" }); DropTable("dbo.Tokens"); DropTable("dbo.ScopeSecrets"); DropTable("dbo.Scopes"); DropTable("dbo.ScopeClaims"); DropTable("dbo.Logs"); DropTable("dbo.Tournament"); DropTable("dbo.Game"); DropTable("dbo.Consents"); DropTable("dbo.ClientSecrets"); DropTable("dbo.ClientScopes"); DropTable("dbo.ClientRedirectUris"); DropTable("dbo.ClientPostLogoutRedirectUris"); DropTable("dbo.ClientIdPRestrictions"); DropTable("dbo.ClientCustomGrantTypes"); DropTable("dbo.ClientCorsOrigins"); DropTable("dbo.Clients"); DropTable("dbo.ClientClaims"); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using QuantConnect.Orders; using QuantConnect.Orders.Fees; using static QuantConnect.StringExtensions; namespace QuantConnect.Securities { /// <summary> /// Provides a base class for all buying power models /// </summary> public class BuyingPowerModel : IBuyingPowerModel { private decimal _initialMarginRequirement; private decimal _maintenanceMarginRequirement; /// <summary> /// The percentage used to determine the required unused buying power for the account. /// </summary> protected decimal RequiredFreeBuyingPowerPercent; /// <summary> /// Initializes a new instance of the <see cref="BuyingPowerModel"/> with no leverage (1x) /// </summary> public BuyingPowerModel() : this(1m) { } /// <summary> /// Initializes a new instance of the <see cref="BuyingPowerModel"/> /// </summary> /// <param name="initialMarginRequirement">The percentage of an order's absolute cost /// that must be held in free cash in order to place the order</param> /// <param name="maintenanceMarginRequirement">The percentage of the holding's absolute /// cost that must be held in free cash in order to avoid a margin call</param> /// <param name="requiredFreeBuyingPowerPercent">The percentage used to determine the required /// unused buying power for the account.</param> public BuyingPowerModel( decimal initialMarginRequirement, decimal maintenanceMarginRequirement, decimal requiredFreeBuyingPowerPercent ) { if (initialMarginRequirement < 0 || initialMarginRequirement > 1) { throw new ArgumentException("Initial margin requirement must be between 0 and 1"); } if (maintenanceMarginRequirement < 0 || maintenanceMarginRequirement > 1) { throw new ArgumentException("Maintenance margin requirement must be between 0 and 1"); } if (requiredFreeBuyingPowerPercent < 0 || requiredFreeBuyingPowerPercent > 1) { throw new ArgumentException("Free Buying Power Percent requirement must be between 0 and 1"); } _initialMarginRequirement = initialMarginRequirement; _maintenanceMarginRequirement = maintenanceMarginRequirement; RequiredFreeBuyingPowerPercent = requiredFreeBuyingPowerPercent; } /// <summary> /// Initializes a new instance of the <see cref="BuyingPowerModel"/> /// </summary> /// <param name="leverage">The leverage</param> /// <param name="requiredFreeBuyingPowerPercent">The percentage used to determine the required /// unused buying power for the account.</param> public BuyingPowerModel(decimal leverage, decimal requiredFreeBuyingPowerPercent = 0) { if (leverage < 1) { throw new ArgumentException("Leverage must be greater than or equal to 1."); } if (requiredFreeBuyingPowerPercent < 0 || requiredFreeBuyingPowerPercent > 1) { throw new ArgumentException("Free Buying Power Percent requirement must be between 0 and 1"); } _initialMarginRequirement = 1 / leverage; _maintenanceMarginRequirement = 1 / leverage; RequiredFreeBuyingPowerPercent = requiredFreeBuyingPowerPercent; } /// <summary> /// Gets the current leverage of the security /// </summary> /// <param name="security">The security to get leverage for</param> /// <returns>The current leverage in the security</returns> public virtual decimal GetLeverage(Security security) { return 1 / _initialMarginRequirement; } /// <summary> /// Sets the leverage for the applicable securities, i.e, equities /// </summary> /// <remarks> /// This is added to maintain backwards compatibility with the old margin/leverage system /// </remarks> /// <param name="security"></param> /// <param name="leverage">The new leverage</param> public virtual void SetLeverage(Security security, decimal leverage) { if (leverage < 1) { throw new ArgumentException("Leverage must be greater than or equal to 1."); } var margin = 1 / leverage; _initialMarginRequirement = margin; _maintenanceMarginRequirement = margin; } /// <summary> /// Gets the total margin required to execute the specified order in units of the account currency including fees /// </summary> /// <param name="parameters">An object containing the portfolio, the security and the order</param> /// <returns>The total margin in terms of the currency quoted in the order</returns> public virtual InitialMargin GetInitialMarginRequiredForOrder( InitialMarginRequiredForOrderParameters parameters ) { //Get the order value from the non-abstract order classes (MarketOrder, LimitOrder, StopMarketOrder) //Market order is approximated from the current security price and set in the MarketOrder Method in QCAlgorithm. var fees = parameters.Security.FeeModel.GetOrderFee( new OrderFeeParameters(parameters.Security, parameters.Order)).Value; var feesInAccountCurrency = parameters.CurrencyConverter. ConvertToAccountCurrency(fees).Amount; var orderMargin = this.GetInitialMarginRequirement(parameters.Security, parameters.Order.Quantity); return orderMargin + Math.Sign(orderMargin) * feesInAccountCurrency; } /// <summary> /// Gets the margin currently allocated to the specified holding /// </summary> /// <param name="parameters">An object containing the security and holdings quantity/cost/value</param> /// <returns>The maintenance margin required for the provided holdings quantity/cost/value</returns> public virtual MaintenanceMargin GetMaintenanceMargin(MaintenanceMarginParameters parameters) { return parameters.AbsoluteHoldingsValue * _maintenanceMarginRequirement; } /// <summary> /// Gets the margin cash available for a trade /// </summary> /// <param name="portfolio">The algorithm's portfolio</param> /// <param name="security">The security to be traded</param> /// <param name="direction">The direction of the trade</param> /// <returns>The margin available for the trade</returns> protected virtual decimal GetMarginRemaining( SecurityPortfolioManager portfolio, Security security, OrderDirection direction ) { var totalPortfolioValue = portfolio.TotalPortfolioValue; var result = portfolio.GetMarginRemaining(totalPortfolioValue); if (direction != OrderDirection.Hold) { var holdings = security.Holdings; //If the order is in the same direction as holdings, our remaining cash is our cash //In the opposite direction, our remaining cash is 2 x current value of assets + our cash if (holdings.IsLong) { switch (direction) { case OrderDirection.Sell: result += // portion of margin to close the existing position this.GetMaintenanceMargin(security) + // portion of margin to open the new position this.GetInitialMarginRequirement(security, security.Holdings.AbsoluteQuantity); break; } } else if (holdings.IsShort) { switch (direction) { case OrderDirection.Buy: result += // portion of margin to close the existing position this.GetMaintenanceMargin(security) + // portion of margin to open the new position this.GetInitialMarginRequirement(security, security.Holdings.AbsoluteQuantity); break; } } } result -= totalPortfolioValue * RequiredFreeBuyingPowerPercent; return result < 0 ? 0 : result; } /// <summary> /// The margin that must be held in order to increase the position by the provided quantity /// </summary> /// <param name="parameters">An object containing the security and quantity of shares</param> /// <returns>The initial margin required for the provided security and quantity</returns> public virtual InitialMargin GetInitialMarginRequirement(InitialMarginParameters parameters) { var security = parameters.Security; var quantity = parameters.Quantity; return security.QuoteCurrency.ConversionRate * security.SymbolProperties.ContractMultiplier * security.Price * quantity * _initialMarginRequirement; } /// <summary> /// Check if there is sufficient buying power to execute this order. /// </summary> /// <param name="parameters">An object containing the portfolio, the security and the order</param> /// <returns>Returns buying power information for an order</returns> public virtual HasSufficientBuyingPowerForOrderResult HasSufficientBuyingPowerForOrder(HasSufficientBuyingPowerForOrderParameters parameters) { // short circuit the div 0 case if (parameters.Order.Quantity == 0) { return parameters.Sufficient(); } var ticket = parameters.Portfolio.Transactions.GetOrderTicket(parameters.Order.Id); if (ticket == null) { return parameters.Insufficient( $"Null order ticket for id: {parameters.Order.Id}" ); } if (parameters.Order.Type == OrderType.OptionExercise) { // for option assignment and exercise orders we look into the requirements to process the underlying security transaction var option = (Option.Option) parameters.Security; var underlying = option.Underlying; if (option.IsAutoExercised(underlying.Close) && underlying.IsTradable) { var quantity = option.GetExerciseQuantity(parameters.Order.Quantity); var newOrder = new LimitOrder { Id = parameters.Order.Id, Time = parameters.Order.Time, LimitPrice = option.StrikePrice, Symbol = underlying.Symbol, Quantity = quantity }; // we continue with this call for underlying var parametersForUnderlying = parameters.ForUnderlying(newOrder); var freeMargin = underlying.BuyingPowerModel.GetBuyingPower(parametersForUnderlying.Portfolio, parametersForUnderlying.Security, parametersForUnderlying.Order.Direction); // we add the margin used by the option itself freeMargin += GetMaintenanceMargin(MaintenanceMarginParameters.ForQuantityAtCurrentPrice(option, -parameters.Order.Quantity)); var initialMarginRequired = underlying.BuyingPowerModel.GetInitialMarginRequiredForOrder( new InitialMarginRequiredForOrderParameters(parameters.Portfolio.CashBook, underlying, newOrder)); return HasSufficientBuyingPowerForOrder(parametersForUnderlying, ticket, freeMargin, initialMarginRequired); } return parameters.Sufficient(); } return HasSufficientBuyingPowerForOrder(parameters, ticket); } private HasSufficientBuyingPowerForOrderResult HasSufficientBuyingPowerForOrder(HasSufficientBuyingPowerForOrderParameters parameters, OrderTicket ticket, decimal? freeMarginToUse = null, decimal? initialMarginRequired = null) { // When order only reduces or closes a security position, capital is always sufficient if (parameters.Security.Holdings.Quantity * parameters.Order.Quantity < 0 && Math.Abs(parameters.Security.Holdings.Quantity) >= Math.Abs(parameters.Order.Quantity)) { return parameters.Sufficient(); } var freeMargin = freeMarginToUse ?? GetMarginRemaining(parameters.Portfolio, parameters.Security, parameters.Order.Direction); var initialMarginRequiredForOrder = initialMarginRequired ?? GetInitialMarginRequiredForOrder( new InitialMarginRequiredForOrderParameters( parameters.Portfolio.CashBook, parameters.Security, parameters.Order )); // pro-rate the initial margin required for order based on how much has already been filled var percentUnfilled = (Math.Abs(parameters.Order.Quantity) - Math.Abs(ticket.QuantityFilled)) / Math.Abs(parameters.Order.Quantity); var initialMarginRequiredForRemainderOfOrder = percentUnfilled * initialMarginRequiredForOrder; if (Math.Abs(initialMarginRequiredForRemainderOfOrder) > freeMargin) { return parameters.Insufficient(Invariant($"Id: {parameters.Order.Id}, ") + Invariant($"Initial Margin: {initialMarginRequiredForRemainderOfOrder.Normalize()}, ") + Invariant($"Free Margin: {freeMargin.Normalize()}") ); } return parameters.Sufficient(); } /// <summary> /// Get the maximum market order quantity to obtain a delta in the buying power used by a security. /// The deltas sign defines the position side to apply it to, positive long, negative short. /// </summary> /// <param name="parameters">An object containing the portfolio, the security and the delta buying power</param> /// <returns>Returns the maximum allowed market order quantity and if zero, also the reason</returns> /// <remarks>Used by the margin call model to reduce the position by a delta percent.</remarks> public virtual GetMaximumOrderQuantityResult GetMaximumOrderQuantityForDeltaBuyingPower( GetMaximumOrderQuantityForDeltaBuyingPowerParameters parameters) { var usedBuyingPower = parameters.Security.BuyingPowerModel.GetReservedBuyingPowerForPosition( new ReservedBuyingPowerForPositionParameters(parameters.Security)).AbsoluteUsedBuyingPower; var signedUsedBuyingPower = usedBuyingPower * (parameters.Security.Holdings.IsLong ? 1 : -1); var targetBuyingPower = signedUsedBuyingPower + parameters.DeltaBuyingPower; var target = 0m; if (parameters.Portfolio.TotalPortfolioValue != 0) { target = targetBuyingPower / parameters.Portfolio.TotalPortfolioValue; } return GetMaximumOrderQuantityForTargetBuyingPower( new GetMaximumOrderQuantityForTargetBuyingPowerParameters(parameters.Portfolio, parameters.Security, target, parameters.MinimumOrderMarginPortfolioPercentage, parameters.SilenceNonErrorReasons)); } /// <summary> /// Get the maximum market order quantity to obtain a position with a given buying power percentage. /// Will not take into account free buying power. /// </summary> /// <param name="parameters">An object containing the portfolio, the security and the target signed buying power percentage</param> /// <returns>Returns the maximum allowed market order quantity and if zero, also the reason</returns> /// <remarks>This implementation ensures that our resulting holdings is less than the target, but it does not necessarily /// maximize the holdings to meet the target. To do that we need a minimizing algorithm that reduces the difference between /// the target final margin value and the target holdings margin.</remarks> public virtual GetMaximumOrderQuantityResult GetMaximumOrderQuantityForTargetBuyingPower(GetMaximumOrderQuantityForTargetBuyingPowerParameters parameters) { // this is expensive so lets fetch it once var totalPortfolioValue = parameters.Portfolio.TotalPortfolioValue; // adjust target buying power to comply with required Free Buying Power Percent var signedTargetFinalMarginValue = parameters.TargetBuyingPower * (totalPortfolioValue - totalPortfolioValue * RequiredFreeBuyingPowerPercent); // if targeting zero, simply return the negative of the quantity if (signedTargetFinalMarginValue == 0) { return new GetMaximumOrderQuantityResult(-parameters.Security.Holdings.Quantity, string.Empty, false); } // we use initial margin requirement here to avoid the duplicate PortfolioTarget.Percent situation: // PortfolioTarget.Percent(1) -> fills -> PortfolioTarget.Percent(1) _could_ detect free buying power if we use Maintenance requirement here var currentSignedUsedMargin = this.GetInitialMarginRequirement(parameters.Security, parameters.Security.Holdings.Quantity); // remove directionality, we'll work in the land of absolutes var absFinalOrderMargin = Math.Abs(signedTargetFinalMarginValue - currentSignedUsedMargin); var direction = signedTargetFinalMarginValue > currentSignedUsedMargin ? OrderDirection.Buy : OrderDirection.Sell; // determine the unit price in terms of the account currency var utcTime = parameters.Security.LocalTime.ConvertToUtc(parameters.Security.Exchange.TimeZone); // determine the margin required for 1 unit, positive since we are working with absolutes var absUnitMargin = this.GetInitialMarginRequirement(parameters.Security, 1); if (absUnitMargin == 0) { return new GetMaximumOrderQuantityResult(0, parameters.Security.Symbol.GetZeroPriceMessage()); } // compute the initial order quantity var absOrderQuantity = Math.Abs(GetAmountToOrder(currentSignedUsedMargin, signedTargetFinalMarginValue, absUnitMargin, parameters.Security.SymbolProperties.LotSize)); if (absOrderQuantity == 0) { string reason = null; if (!parameters.SilenceNonErrorReasons) { reason = $"The order quantity is less than the lot size of {parameters.Security.SymbolProperties.LotSize} " + "and has been rounded to zero."; } return new GetMaximumOrderQuantityResult(0, reason, false); } var minimumValue = totalPortfolioValue * parameters.MinimumOrderMarginPortfolioPercentage; if (minimumValue > absFinalOrderMargin // if margin remaining is negative allow the order to pass so we can reduce the position && parameters.Portfolio.GetMarginRemaining(totalPortfolioValue) > 0) { string reason = null; if (!parameters.SilenceNonErrorReasons) { reason = $"The target order margin {absFinalOrderMargin} is less than the minimum {minimumValue}."; } return new GetMaximumOrderQuantityResult(0, reason, false); } // Use the following loop to converge on a value that places us under our target allocation when adjusted for fees var lastOrderQuantity = 0m; // For safety check var signedTargetHoldingsMargin = ((direction == OrderDirection.Sell ? -1 : 1) * absOrderQuantity + parameters.Security.Holdings.Quantity) * absUnitMargin; decimal orderFees = 0; do { // If our order target holdings is larger than our target margin allocated we need to recalculate our order size if (Math.Abs(signedTargetHoldingsMargin) > Math.Abs(signedTargetFinalMarginValue)) { absOrderQuantity = Math.Abs(GetAmountToOrder(currentSignedUsedMargin, signedTargetFinalMarginValue, absUnitMargin, parameters.Security.SymbolProperties.LotSize, absOrderQuantity * (direction == OrderDirection.Sell ? -1 : 1))); } if (absOrderQuantity <= 0) { var sign = direction == OrderDirection.Buy ? 1 : -1; return new GetMaximumOrderQuantityResult(0, Invariant($"The order quantity is less than the lot size of {parameters.Security.SymbolProperties.LotSize} ") + Invariant($"and has been rounded to zero.Target order margin {absFinalOrderMargin * sign}. Order fees ") + Invariant($"{orderFees}. Order quantity {absOrderQuantity * sign}. Margin unit {absUnitMargin}."), false ); } // generate the order var order = new MarketOrder(parameters.Security.Symbol, absOrderQuantity, utcTime); var fees = parameters.Security.FeeModel.GetOrderFee( new OrderFeeParameters(parameters.Security, order)).Value; orderFees = parameters.Portfolio.CashBook.ConvertToAccountCurrency(fees).Amount; // Update our target portfolio margin allocated when considering fees, then calculate the new FinalOrderMargin signedTargetFinalMarginValue = (totalPortfolioValue - orderFees - totalPortfolioValue * RequiredFreeBuyingPowerPercent) * parameters.TargetBuyingPower; absFinalOrderMargin = Math.Abs(signedTargetFinalMarginValue - currentSignedUsedMargin); // Start safe check after first loop if (lastOrderQuantity == absOrderQuantity) { var sign = direction == OrderDirection.Buy ? 1 : -1; var message = Invariant($"GetMaximumOrderQuantityForTargetBuyingPower failed to converge on the target margin: {signedTargetFinalMarginValue}; ") + Invariant($"the following information can be used to reproduce the issue. Total Portfolio Cash: {parameters.Portfolio.Cash}; ") + Invariant($"Leverage: {parameters.Security.Leverage}; Order Fee: {orderFees}; Lot Size: {parameters.Security.SymbolProperties.LotSize}; ") + Invariant($"Per Unit Margin: {absUnitMargin}; Current Holdings: {parameters.Security.Holdings}; Target Percentage: %{parameters.TargetBuyingPower * 100}; ") + Invariant($"Current Order Target Margin: {absFinalOrderMargin * sign}; Current Order Margin: {absOrderQuantity * absUnitMargin * sign}"); throw new ArgumentException(message); } lastOrderQuantity = absOrderQuantity; // Update our target holdings margin signedTargetHoldingsMargin = ((direction == OrderDirection.Sell ? -1 : 1) * absOrderQuantity + parameters.Security.Holdings.Quantity) * absUnitMargin; } // Ensure that our target holdings margin will be less than or equal to our target allocated margin while (Math.Abs(signedTargetHoldingsMargin) > Math.Abs(signedTargetFinalMarginValue)); // add directionality back in return new GetMaximumOrderQuantityResult((direction == OrderDirection.Sell ? -1 : 1) * absOrderQuantity); } /// <summary> /// Helper function that determines the amount to order to get to a given target safely. /// Meaning it will either be at or just below target always. /// </summary> /// <param name="currentMargin">Current margin</param> /// <param name="targetMargin">Target margin</param> /// <param name="perUnitMargin">Margin required for each unit</param> /// <param name="lotSize">Lot size of the security we are ordering</param> /// <returns>The size of the order to get safely to our target</returns> public static decimal GetAmountToOrder(decimal currentMargin, decimal targetMargin, decimal perUnitMargin, decimal lotSize, decimal? currentOrderSize = null) { // Determine the amount to order to put us at our target var orderSize = (targetMargin - currentMargin) / perUnitMargin; // Determine if we are under our target var underTarget = false; // For negative target, we are under if target is a larger negative number if (targetMargin < 0 && targetMargin - currentMargin < 0) { underTarget = true; } // For positive target, we are under if target is a larger positive number else if (targetMargin > 0 && targetMargin - currentMargin > 0) { underTarget = true; } // Determine our rounding mode MidpointRounding roundingMode; if (underTarget) { // Negative orders need to be rounded "up" so we don't go over target // Positive orders need to be rounded "down" so we don't go over target roundingMode = orderSize < 0 ? MidpointRounding.ToPositiveInfinity : MidpointRounding.ToNegativeInfinity; } else { // Negative orders need to be rounded "down" so we are under our target // Positive orders need to be rounded "up" so we are under our target roundingMode = orderSize < 0 ? MidpointRounding.ToNegativeInfinity : MidpointRounding.ToPositiveInfinity; } // For handling precision errors in OrderSize calculation if (currentOrderSize.HasValue && orderSize % lotSize == 0 && orderSize == currentOrderSize.Value) { // Force an adjustment if (roundingMode == MidpointRounding.ToPositiveInfinity) { orderSize += lotSize; } else { orderSize -= lotSize; } return orderSize; } // Round this order size appropriately return orderSize.DiscretelyRoundBy(lotSize, roundingMode); } /// <summary> /// Gets the amount of buying power reserved to maintain the specified position /// </summary> /// <param name="parameters">A parameters object containing the security</param> /// <returns>The reserved buying power in account currency</returns> public virtual ReservedBuyingPowerForPosition GetReservedBuyingPowerForPosition(ReservedBuyingPowerForPositionParameters parameters) { var maintenanceMargin = this.GetMaintenanceMargin(parameters.Security); return parameters.ResultInAccountCurrency(maintenanceMargin); } /// <summary> /// Gets the buying power available for a trade /// </summary> /// <param name="parameters">A parameters object containing the algorithm's portfolio, security, and order direction</param> /// <returns>The buying power available for the trade</returns> public virtual BuyingPower GetBuyingPower(BuyingPowerParameters parameters) { var marginRemaining = GetMarginRemaining(parameters.Portfolio, parameters.Security, parameters.Direction); return parameters.ResultInAccountCurrency(marginRemaining); } } }
// 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 gaxgrpc = Google.Api.Gax.Grpc; using gagr = Google.Api.Gax.ResourceNames; using proto = Google.Protobuf; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.WebRisk.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedWebRiskServiceClientTest { [xunit::FactAttribute] public void ComputeThreatListDiffRequestObject() { moq::Mock<WebRiskService.WebRiskServiceClient> mockGrpcClient = new moq::Mock<WebRiskService.WebRiskServiceClient>(moq::MockBehavior.Strict); ComputeThreatListDiffRequest request = new ComputeThreatListDiffRequest { ThreatType = ThreatType.Malware, VersionToken = proto::ByteString.CopyFromUtf8("version_token1850f275"), Constraints = new ComputeThreatListDiffRequest.Types.Constraints(), }; ComputeThreatListDiffResponse expectedResponse = new ComputeThreatListDiffResponse { RecommendedNextDiff = new wkt::Timestamp(), ResponseType = ComputeThreatListDiffResponse.Types.ResponseType.Diff, Additions = new ThreatEntryAdditions(), Removals = new ThreatEntryRemovals(), NewVersionToken = proto::ByteString.CopyFromUtf8("new_version_tokenc8bdd85d"), Checksum = new ComputeThreatListDiffResponse.Types.Checksum(), }; mockGrpcClient.Setup(x => x.ComputeThreatListDiff(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); WebRiskServiceClient client = new WebRiskServiceClientImpl(mockGrpcClient.Object, null); ComputeThreatListDiffResponse response = client.ComputeThreatListDiff(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ComputeThreatListDiffRequestObjectAsync() { moq::Mock<WebRiskService.WebRiskServiceClient> mockGrpcClient = new moq::Mock<WebRiskService.WebRiskServiceClient>(moq::MockBehavior.Strict); ComputeThreatListDiffRequest request = new ComputeThreatListDiffRequest { ThreatType = ThreatType.Malware, VersionToken = proto::ByteString.CopyFromUtf8("version_token1850f275"), Constraints = new ComputeThreatListDiffRequest.Types.Constraints(), }; ComputeThreatListDiffResponse expectedResponse = new ComputeThreatListDiffResponse { RecommendedNextDiff = new wkt::Timestamp(), ResponseType = ComputeThreatListDiffResponse.Types.ResponseType.Diff, Additions = new ThreatEntryAdditions(), Removals = new ThreatEntryRemovals(), NewVersionToken = proto::ByteString.CopyFromUtf8("new_version_tokenc8bdd85d"), Checksum = new ComputeThreatListDiffResponse.Types.Checksum(), }; mockGrpcClient.Setup(x => x.ComputeThreatListDiffAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ComputeThreatListDiffResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); WebRiskServiceClient client = new WebRiskServiceClientImpl(mockGrpcClient.Object, null); ComputeThreatListDiffResponse responseCallSettings = await client.ComputeThreatListDiffAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ComputeThreatListDiffResponse responseCancellationToken = await client.ComputeThreatListDiffAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ComputeThreatListDiff() { moq::Mock<WebRiskService.WebRiskServiceClient> mockGrpcClient = new moq::Mock<WebRiskService.WebRiskServiceClient>(moq::MockBehavior.Strict); ComputeThreatListDiffRequest request = new ComputeThreatListDiffRequest { ThreatType = ThreatType.Malware, VersionToken = proto::ByteString.CopyFromUtf8("version_token1850f275"), Constraints = new ComputeThreatListDiffRequest.Types.Constraints(), }; ComputeThreatListDiffResponse expectedResponse = new ComputeThreatListDiffResponse { RecommendedNextDiff = new wkt::Timestamp(), ResponseType = ComputeThreatListDiffResponse.Types.ResponseType.Diff, Additions = new ThreatEntryAdditions(), Removals = new ThreatEntryRemovals(), NewVersionToken = proto::ByteString.CopyFromUtf8("new_version_tokenc8bdd85d"), Checksum = new ComputeThreatListDiffResponse.Types.Checksum(), }; mockGrpcClient.Setup(x => x.ComputeThreatListDiff(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); WebRiskServiceClient client = new WebRiskServiceClientImpl(mockGrpcClient.Object, null); ComputeThreatListDiffResponse response = client.ComputeThreatListDiff(request.ThreatType, request.VersionToken, request.Constraints); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ComputeThreatListDiffAsync() { moq::Mock<WebRiskService.WebRiskServiceClient> mockGrpcClient = new moq::Mock<WebRiskService.WebRiskServiceClient>(moq::MockBehavior.Strict); ComputeThreatListDiffRequest request = new ComputeThreatListDiffRequest { ThreatType = ThreatType.Malware, VersionToken = proto::ByteString.CopyFromUtf8("version_token1850f275"), Constraints = new ComputeThreatListDiffRequest.Types.Constraints(), }; ComputeThreatListDiffResponse expectedResponse = new ComputeThreatListDiffResponse { RecommendedNextDiff = new wkt::Timestamp(), ResponseType = ComputeThreatListDiffResponse.Types.ResponseType.Diff, Additions = new ThreatEntryAdditions(), Removals = new ThreatEntryRemovals(), NewVersionToken = proto::ByteString.CopyFromUtf8("new_version_tokenc8bdd85d"), Checksum = new ComputeThreatListDiffResponse.Types.Checksum(), }; mockGrpcClient.Setup(x => x.ComputeThreatListDiffAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ComputeThreatListDiffResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); WebRiskServiceClient client = new WebRiskServiceClientImpl(mockGrpcClient.Object, null); ComputeThreatListDiffResponse responseCallSettings = await client.ComputeThreatListDiffAsync(request.ThreatType, request.VersionToken, request.Constraints, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ComputeThreatListDiffResponse responseCancellationToken = await client.ComputeThreatListDiffAsync(request.ThreatType, request.VersionToken, request.Constraints, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SearchUrisRequestObject() { moq::Mock<WebRiskService.WebRiskServiceClient> mockGrpcClient = new moq::Mock<WebRiskService.WebRiskServiceClient>(moq::MockBehavior.Strict); SearchUrisRequest request = new SearchUrisRequest { Uri = "uri3db70593", ThreatTypes = { ThreatType.SocialEngineering, }, }; SearchUrisResponse expectedResponse = new SearchUrisResponse { Threat = new SearchUrisResponse.Types.ThreatUri(), }; mockGrpcClient.Setup(x => x.SearchUris(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); WebRiskServiceClient client = new WebRiskServiceClientImpl(mockGrpcClient.Object, null); SearchUrisResponse response = client.SearchUris(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SearchUrisRequestObjectAsync() { moq::Mock<WebRiskService.WebRiskServiceClient> mockGrpcClient = new moq::Mock<WebRiskService.WebRiskServiceClient>(moq::MockBehavior.Strict); SearchUrisRequest request = new SearchUrisRequest { Uri = "uri3db70593", ThreatTypes = { ThreatType.SocialEngineering, }, }; SearchUrisResponse expectedResponse = new SearchUrisResponse { Threat = new SearchUrisResponse.Types.ThreatUri(), }; mockGrpcClient.Setup(x => x.SearchUrisAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SearchUrisResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); WebRiskServiceClient client = new WebRiskServiceClientImpl(mockGrpcClient.Object, null); SearchUrisResponse responseCallSettings = await client.SearchUrisAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SearchUrisResponse responseCancellationToken = await client.SearchUrisAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SearchUris() { moq::Mock<WebRiskService.WebRiskServiceClient> mockGrpcClient = new moq::Mock<WebRiskService.WebRiskServiceClient>(moq::MockBehavior.Strict); SearchUrisRequest request = new SearchUrisRequest { Uri = "uri3db70593", ThreatTypes = { ThreatType.SocialEngineering, }, }; SearchUrisResponse expectedResponse = new SearchUrisResponse { Threat = new SearchUrisResponse.Types.ThreatUri(), }; mockGrpcClient.Setup(x => x.SearchUris(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); WebRiskServiceClient client = new WebRiskServiceClientImpl(mockGrpcClient.Object, null); SearchUrisResponse response = client.SearchUris(request.Uri, request.ThreatTypes); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SearchUrisAsync() { moq::Mock<WebRiskService.WebRiskServiceClient> mockGrpcClient = new moq::Mock<WebRiskService.WebRiskServiceClient>(moq::MockBehavior.Strict); SearchUrisRequest request = new SearchUrisRequest { Uri = "uri3db70593", ThreatTypes = { ThreatType.SocialEngineering, }, }; SearchUrisResponse expectedResponse = new SearchUrisResponse { Threat = new SearchUrisResponse.Types.ThreatUri(), }; mockGrpcClient.Setup(x => x.SearchUrisAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SearchUrisResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); WebRiskServiceClient client = new WebRiskServiceClientImpl(mockGrpcClient.Object, null); SearchUrisResponse responseCallSettings = await client.SearchUrisAsync(request.Uri, request.ThreatTypes, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SearchUrisResponse responseCancellationToken = await client.SearchUrisAsync(request.Uri, request.ThreatTypes, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SearchHashesRequestObject() { moq::Mock<WebRiskService.WebRiskServiceClient> mockGrpcClient = new moq::Mock<WebRiskService.WebRiskServiceClient>(moq::MockBehavior.Strict); SearchHashesRequest request = new SearchHashesRequest { HashPrefix = proto::ByteString.CopyFromUtf8("hash_prefix0c2a6688"), ThreatTypes = { ThreatType.SocialEngineering, }, }; SearchHashesResponse expectedResponse = new SearchHashesResponse { Threats = { new SearchHashesResponse.Types.ThreatHash(), }, NegativeExpireTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.SearchHashes(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); WebRiskServiceClient client = new WebRiskServiceClientImpl(mockGrpcClient.Object, null); SearchHashesResponse response = client.SearchHashes(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SearchHashesRequestObjectAsync() { moq::Mock<WebRiskService.WebRiskServiceClient> mockGrpcClient = new moq::Mock<WebRiskService.WebRiskServiceClient>(moq::MockBehavior.Strict); SearchHashesRequest request = new SearchHashesRequest { HashPrefix = proto::ByteString.CopyFromUtf8("hash_prefix0c2a6688"), ThreatTypes = { ThreatType.SocialEngineering, }, }; SearchHashesResponse expectedResponse = new SearchHashesResponse { Threats = { new SearchHashesResponse.Types.ThreatHash(), }, NegativeExpireTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.SearchHashesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SearchHashesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); WebRiskServiceClient client = new WebRiskServiceClientImpl(mockGrpcClient.Object, null); SearchHashesResponse responseCallSettings = await client.SearchHashesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SearchHashesResponse responseCancellationToken = await client.SearchHashesAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SearchHashes() { moq::Mock<WebRiskService.WebRiskServiceClient> mockGrpcClient = new moq::Mock<WebRiskService.WebRiskServiceClient>(moq::MockBehavior.Strict); SearchHashesRequest request = new SearchHashesRequest { HashPrefix = proto::ByteString.CopyFromUtf8("hash_prefix0c2a6688"), ThreatTypes = { ThreatType.SocialEngineering, }, }; SearchHashesResponse expectedResponse = new SearchHashesResponse { Threats = { new SearchHashesResponse.Types.ThreatHash(), }, NegativeExpireTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.SearchHashes(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); WebRiskServiceClient client = new WebRiskServiceClientImpl(mockGrpcClient.Object, null); SearchHashesResponse response = client.SearchHashes(request.HashPrefix, request.ThreatTypes); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SearchHashesAsync() { moq::Mock<WebRiskService.WebRiskServiceClient> mockGrpcClient = new moq::Mock<WebRiskService.WebRiskServiceClient>(moq::MockBehavior.Strict); SearchHashesRequest request = new SearchHashesRequest { HashPrefix = proto::ByteString.CopyFromUtf8("hash_prefix0c2a6688"), ThreatTypes = { ThreatType.SocialEngineering, }, }; SearchHashesResponse expectedResponse = new SearchHashesResponse { Threats = { new SearchHashesResponse.Types.ThreatHash(), }, NegativeExpireTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.SearchHashesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SearchHashesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); WebRiskServiceClient client = new WebRiskServiceClientImpl(mockGrpcClient.Object, null); SearchHashesResponse responseCallSettings = await client.SearchHashesAsync(request.HashPrefix, request.ThreatTypes, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SearchHashesResponse responseCancellationToken = await client.SearchHashesAsync(request.HashPrefix, request.ThreatTypes, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateSubmissionRequestObject() { moq::Mock<WebRiskService.WebRiskServiceClient> mockGrpcClient = new moq::Mock<WebRiskService.WebRiskServiceClient>(moq::MockBehavior.Strict); CreateSubmissionRequest request = new CreateSubmissionRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Submission = new Submission(), }; Submission expectedResponse = new Submission { Uri = "uri3db70593", }; mockGrpcClient.Setup(x => x.CreateSubmission(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); WebRiskServiceClient client = new WebRiskServiceClientImpl(mockGrpcClient.Object, null); Submission response = client.CreateSubmission(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateSubmissionRequestObjectAsync() { moq::Mock<WebRiskService.WebRiskServiceClient> mockGrpcClient = new moq::Mock<WebRiskService.WebRiskServiceClient>(moq::MockBehavior.Strict); CreateSubmissionRequest request = new CreateSubmissionRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Submission = new Submission(), }; Submission expectedResponse = new Submission { Uri = "uri3db70593", }; mockGrpcClient.Setup(x => x.CreateSubmissionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Submission>(stt::Task.FromResult(expectedResponse), null, null, null, null)); WebRiskServiceClient client = new WebRiskServiceClientImpl(mockGrpcClient.Object, null); Submission responseCallSettings = await client.CreateSubmissionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Submission responseCancellationToken = await client.CreateSubmissionAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateSubmission() { moq::Mock<WebRiskService.WebRiskServiceClient> mockGrpcClient = new moq::Mock<WebRiskService.WebRiskServiceClient>(moq::MockBehavior.Strict); CreateSubmissionRequest request = new CreateSubmissionRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Submission = new Submission(), }; Submission expectedResponse = new Submission { Uri = "uri3db70593", }; mockGrpcClient.Setup(x => x.CreateSubmission(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); WebRiskServiceClient client = new WebRiskServiceClientImpl(mockGrpcClient.Object, null); Submission response = client.CreateSubmission(request.Parent, request.Submission); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateSubmissionAsync() { moq::Mock<WebRiskService.WebRiskServiceClient> mockGrpcClient = new moq::Mock<WebRiskService.WebRiskServiceClient>(moq::MockBehavior.Strict); CreateSubmissionRequest request = new CreateSubmissionRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Submission = new Submission(), }; Submission expectedResponse = new Submission { Uri = "uri3db70593", }; mockGrpcClient.Setup(x => x.CreateSubmissionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Submission>(stt::Task.FromResult(expectedResponse), null, null, null, null)); WebRiskServiceClient client = new WebRiskServiceClientImpl(mockGrpcClient.Object, null); Submission responseCallSettings = await client.CreateSubmissionAsync(request.Parent, request.Submission, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Submission responseCancellationToken = await client.CreateSubmissionAsync(request.Parent, request.Submission, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateSubmissionResourceNames() { moq::Mock<WebRiskService.WebRiskServiceClient> mockGrpcClient = new moq::Mock<WebRiskService.WebRiskServiceClient>(moq::MockBehavior.Strict); CreateSubmissionRequest request = new CreateSubmissionRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Submission = new Submission(), }; Submission expectedResponse = new Submission { Uri = "uri3db70593", }; mockGrpcClient.Setup(x => x.CreateSubmission(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); WebRiskServiceClient client = new WebRiskServiceClientImpl(mockGrpcClient.Object, null); Submission response = client.CreateSubmission(request.ParentAsProjectName, request.Submission); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateSubmissionResourceNamesAsync() { moq::Mock<WebRiskService.WebRiskServiceClient> mockGrpcClient = new moq::Mock<WebRiskService.WebRiskServiceClient>(moq::MockBehavior.Strict); CreateSubmissionRequest request = new CreateSubmissionRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Submission = new Submission(), }; Submission expectedResponse = new Submission { Uri = "uri3db70593", }; mockGrpcClient.Setup(x => x.CreateSubmissionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Submission>(stt::Task.FromResult(expectedResponse), null, null, null, null)); WebRiskServiceClient client = new WebRiskServiceClientImpl(mockGrpcClient.Object, null); Submission responseCallSettings = await client.CreateSubmissionAsync(request.ParentAsProjectName, request.Submission, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Submission responseCancellationToken = await client.CreateSubmissionAsync(request.ParentAsProjectName, request.Submission, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using FileHelpers.Events; namespace FileHelpers { /// <summary>An internal class used to store information about the Record Type.</summary> /// <remarks>Is public to provide extensibility of DataStorage from outside the library.</remarks> internal sealed partial class RecordInfo : IRecordInfo { // -------------------------------------- // Constructor and Init Methods #region IRecordInfo Members /// <summary> /// Hint about record size /// </summary> public int SizeHint { get; private set; } /// <summary> /// Class we are defining /// </summary> public Type RecordType { get; private set; } /// <summary> /// Do we skip empty lines? /// </summary> public bool IgnoreEmptyLines { get; set; } /// <summary> /// Do we skip lines with completely blank lines /// </summary> public bool IgnoreEmptySpaces { get; private set; } /// <summary> /// Comment prefix /// </summary> public string CommentMarker { get; set; } /// <summary> /// Number of fields we are processing /// </summary> public int FieldCount { get { return this.Fields.Length; } } /// <summary> /// List of fields and the extraction details /// </summary> public FieldBase[] Fields { get; private set; } /// <summary> /// Number of lines to skip at beginning of file /// </summary> public int IgnoreFirst { get; set; } /// <summary> /// Number of lines to skip at end of file /// </summary> public int IgnoreLast { get; set; } /// <summary> /// DO we need to issue a Notify read /// </summary> public bool NotifyRead { get; private set; } /// <summary> /// Do we need to issue a Notify Write /// </summary> public bool NotifyWrite { get; private set; } /// <summary> /// Can the comment prefix have leading whitespace /// </summary> public bool CommentAnyPlace { get; set; } /// <summary> /// Include or skip a record based upon a defined RecordCondition interface /// </summary> public RecordCondition RecordCondition { get; set; } /// <summary> /// Skip or include a record based upon a regular expression /// </summary> public Regex RecordConditionRegEx { get; private set; } /// <summary> /// Include or exclude a record based upon presence of a string /// </summary> public string RecordConditionSelector { get; set; } /// <summary> /// Operations are the functions that perform creation or extraction of data from objects /// these are created dynamically from the record conditions /// </summary> public RecordOperations Operations { get; private set; } private Dictionary<string, int> mMapFieldIndex; /// <summary> /// Is this record layout delimited /// </summary> public bool IsDelimited { get { return Fields[0] is DelimitedField; } } #endregion #region " Constructor " private RecordInfo() {} /// <summary> /// Read the attributes of the class and create an array /// of how to process the file /// </summary> /// <param name="recordType">Class we are analysing</param> private RecordInfo(Type recordType) { SizeHint = 32; RecordConditionSelector = String.Empty; RecordCondition = RecordCondition.None; CommentAnyPlace = true; RecordType = recordType; InitRecordFields(); Operations = new RecordOperations(this); } /// <summary> /// Create a list of fields we are extracting and set /// the size hint for record I/O /// </summary> private void InitRecordFields() { //Debug.Assert(false, "TODO: Add RecordFilter to the engine."); var recordAttribute = Attributes.GetFirstInherited<TypedRecordAttribute>(RecordType); if (recordAttribute == null) { throw new BadUsageException(Messages.Errors.ClassWithOutRecordAttribute .ClassName(RecordType.Name) .Text); } if (ReflectionHelper.GetDefaultConstructor(RecordType) == null) { throw new BadUsageException(Messages.Errors.ClassWithOutDefaultConstructor .ClassName(RecordType.Name) .Text); } Attributes.WorkWithFirst<IgnoreFirstAttribute>( RecordType, a => IgnoreFirst = a.NumberOfLines); Attributes.WorkWithFirst<IgnoreLastAttribute>( RecordType, a => IgnoreLast = a.NumberOfLines); Attributes.WorkWithFirst<IgnoreEmptyLinesAttribute>( RecordType, a => { IgnoreEmptyLines = true; IgnoreEmptySpaces = a.IgnoreSpaces; }); #pragma warning disable CS0618 // Type or member is obsolete Attributes.WorkWithFirst<IgnoreCommentedLinesAttribute>( #pragma warning restore CS0618 // Type or member is obsolete RecordType, a => { IgnoreEmptyLines = true; CommentMarker = a.CommentMarker; CommentAnyPlace = a.AnyPlace; }); Attributes.WorkWithFirst<ConditionalRecordAttribute>( RecordType, a => { RecordCondition = a.Condition; RecordConditionSelector = a.ConditionSelector; if (RecordCondition == RecordCondition.ExcludeIfMatchRegex || RecordCondition == RecordCondition.IncludeIfMatchRegex) { RecordConditionRegEx = new Regex(RecordConditionSelector, RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); } }); if (CheckInterface(RecordType, typeof (INotifyRead))) NotifyRead = true; if (CheckInterface(RecordType, typeof (INotifyWrite))) NotifyWrite = true; // Create fields // Search for cached fields var fields = new List<FieldInfo>(ReflectionHelper.RecursiveGetFields(RecordType)); Fields = CreateCoreFields(fields, recordAttribute); if (FieldCount == 0) { throw new BadUsageException(Messages.Errors.ClassWithOutFields .ClassName(RecordType.Name) .Text); } if (recordAttribute is FixedLengthRecordAttribute) { // Defines the initial size of the StringBuilder SizeHint = 0; for (int i = 0; i < FieldCount; i++) SizeHint += ((FixedLengthField) Fields[i]).FieldLength; } } #endregion #region " CreateFields " /// <summary> /// Parse the attributes on the class and create an ordered list of /// fields we are extracting from the record /// </summary> /// <param name="fields">Complete list of fields in class</param> /// <param name="recordAttribute">Type of record, fixed or delimited</param> /// <returns>List of fields we are extracting</returns> private static FieldBase[] CreateCoreFields(IList<FieldInfo> fields, TypedRecordAttribute recordAttribute) { var resFields = new List<FieldBase>(); // count of Properties var automaticFields = 0; // count of normal fields var genericFields = 0; for (int i = 0; i < fields.Count; i++) { FieldBase currentField = FieldBase.CreateField(fields[i], recordAttribute); if (currentField == null) continue; if (currentField.FieldInfo.IsDefined(typeof (CompilerGeneratedAttribute), false)) automaticFields++; else genericFields++; // Add to the result resFields.Add(currentField); if (resFields.Count > 1) CheckForOrderProblems(currentField, resFields); } if (automaticFields > 0 && genericFields > 0 && SumOrder(resFields) == 0) { throw new BadUsageException(Messages.Errors.MixOfStandardAndAutoPropertiesFields .ClassName(resFields[0].FieldInfo.DeclaringType.Name) .Text); } SortFieldsByOrder(resFields); if (resFields.Count > 0) { resFields[0].IsFirst = true; resFields[resFields.Count - 1].IsLast = true; } CheckForOptionalAndArrayProblems(resFields); return resFields.ToArray(); } private static int SumOrder(List<FieldBase> fields) { int res = 0; foreach (var field in fields) { res += field.FieldOrder ?? 0; } return res; } /// <summary> /// Check that once one field is optional all following fields are optional /// <para/> /// Check that arrays in the middle of a record are of fixed length /// </summary> /// <param name="resFields">List of fields to extract</param> private static void CheckForOptionalAndArrayProblems(List<FieldBase> resFields) { for (int i = 0; i < resFields.Count; i++) { var currentField = resFields[i]; // Dont check the first field if (i < 1) continue; FieldBase prevField = resFields[i - 1]; //prevField.NextIsOptional = currentField.IsOptional; // Check for optional problems. Previous is optional but current is not if (prevField.IsOptional && currentField.IsOptional == false && currentField.InNewLine == false) { throw new BadUsageException(Messages.Errors.ExpectingFieldOptional .FieldName(prevField.FieldInfo.Name) .Text); } // Check for an array array in the middle of a record that is not a fixed length if (prevField.IsArray) { if (prevField.ArrayMinLength == Int32.MinValue) { throw new BadUsageException(Messages.Errors.MissingFieldArrayLenghtInNotLastField .FieldName(prevField.FieldInfo.Name) .Text); } if (prevField.ArrayMinLength != prevField.ArrayMaxLength) { throw new BadUsageException(Messages.Errors.SameMinMaxLengthForArrayNotLastField .FieldName(prevField.FieldInfo.Name) .Text); } } } } /// <summary> /// Sort fields by the order if supplied /// </summary> /// <param name="resFields">List of fields to use</param> private static void SortFieldsByOrder(List<FieldBase> resFields) { if (resFields.FindAll(x => x.FieldOrder.HasValue).Count > 0) resFields.Sort((x, y) => x.FieldOrder.Value.CompareTo(y.FieldOrder.Value)); } /// <summary> /// Confirm all fields are either ordered or unordered /// </summary> /// <param name="currentField">Newest field</param> /// <param name="resFields">Other fields we have found</param> private static void CheckForOrderProblems(FieldBase currentField, List<FieldBase> resFields) { if (currentField.FieldOrder.HasValue) { // If one field has order number set, all others must also have an order number var fieldWithoutOrder = resFields.Find(x => x.FieldOrder.HasValue == false); if (fieldWithoutOrder != null) { throw new BadUsageException(Messages.Errors.PartialFieldOrder .FieldName(fieldWithoutOrder.FieldInfo.Name) .Text); } // No other field should have the same order number var fieldWithSameOrder = resFields.Find(x => x != currentField && x.FieldOrder == currentField.FieldOrder); if (fieldWithSameOrder != null) { throw new BadUsageException(Messages.Errors.SameFieldOrder .FieldName1(currentField.FieldInfo.Name) .FieldName2(fieldWithSameOrder.FieldInfo.Name) .Text); } } else { // No other field should have order number set var fieldWithOrder = resFields.Find(x => x.FieldOrder.HasValue); if (fieldWithOrder != null) { var autoPropertyName = FieldBase.AutoPropertyName(currentField.FieldInfo); if (string.IsNullOrEmpty(autoPropertyName)) throw new BadUsageException(Messages.Errors.PartialFieldOrder .FieldName(currentField.FieldInfo.Name) .Text); else throw new BadUsageException(Messages.Errors.PartialFieldOrderInAutoProperty .PropertyName(autoPropertyName) .Text); } } } #endregion #region " FieldIndexes " /// <summary> /// Get the index number of the fieldname in the field list /// </summary> /// <param name="fieldName">Fieldname to search for</param> /// <returns>Index in field list</returns> public int GetFieldIndex(string fieldName) { if (mMapFieldIndex == null) { // Initialize field index map mMapFieldIndex = new Dictionary<string, int>(FieldCount, StringComparer.Ordinal); for (int i = 0; i < FieldCount; i++) { mMapFieldIndex.Add(Fields[i].FieldInfo.Name, i); if (Fields[i].FieldInfo.Name != Fields[i].FieldFriendlyName) mMapFieldIndex.Add(Fields[i].FieldFriendlyName, i); } } int res; if (!mMapFieldIndex.TryGetValue(fieldName, out res)) { throw new BadUsageException(Messages.Errors.FieldNotFound .FieldName(fieldName) .ClassName(RecordType.Name) .Text); } return res; } #endregion #region " GetFieldInfo " /// <summary> /// Get field information base on name /// </summary> /// <param name="name">name to find details for</param> /// <returns>Field information</returns> public FieldInfo GetFieldInfo(string name) { foreach (var field in Fields) { if (field.FieldInfo.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) return field.FieldInfo; } return null; } #endregion /// <summary> /// Return the record type information for the record /// </summary> /// <param name="type">Type of object to create</param> /// <returns>Record info for that type</returns> public static IRecordInfo Resolve(Type type) { return RecordInfoFactory.Resolve(type); } /// <summary> /// Create an new instance of the record information /// </summary> /// <returns>Deep copy of the RecordInfo class</returns> public object Clone() { var res = new RecordInfo { CommentAnyPlace = CommentAnyPlace, CommentMarker = CommentMarker, IgnoreEmptyLines = IgnoreEmptyLines, IgnoreEmptySpaces = IgnoreEmptySpaces, IgnoreFirst = IgnoreFirst, IgnoreLast = IgnoreLast, NotifyRead = NotifyRead, NotifyWrite = NotifyWrite, RecordCondition = RecordCondition, RecordConditionRegEx = RecordConditionRegEx, RecordConditionSelector = RecordConditionSelector, RecordType = RecordType, SizeHint = SizeHint }; res.Operations = Operations.Clone(res); res.Fields = new FieldBase[Fields.Length]; for (int i = 0; i < Fields.Length; i++) res.Fields[i] = (FieldBase) Fields[i].Clone(); return res; } //internal static bool CheckGenericInterface(Type type, Type interfaceType, params Type[] genericsArgs) //{ // foreach (var inteImp in type.GetInterfaces()) { // if (inteImp.IsGenericType && // inteImp.GetGenericTypeDefinition() == interfaceType) { // var args = inteImp.GetGenericArguments(); // if (args.Length == genericsArgs.Length) { // bool fail = false; // for (int i = 0; i < args.Length; i++) { // if (args[i] != genericsArgs[i]) { // fail = true; // break; // } // } // if (!fail) // return true; // } // throw new BadUsageException("The class: " + type.Name + " must implement the interface " + // interfaceType.MakeGenericType(genericsArgs) + " and not " + inteImp); // } // } // return false; //} /// <summary> /// Check whether the type implements the INotifyRead or INotifyWrite interfaces /// </summary> /// <param name="type">Type to check interface</param> /// <param name="interfaceType">Interface generic type we are checking for eg INotifyRead&lt;&gt;</param> /// <returns>Whether we found interface</returns> internal static bool CheckInterface(Type type, Type interfaceType) { return type.GetInterface(interfaceType.FullName) != null; } } }
/* * Copyright 2002-2015 Drew Noakes * * Modified by Yakov Danilov <yakodani@gmail.com> for Imazen LLC (Ported from Java to C#) * 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. * * More information about this project is available at: * * https://drewnoakes.com/code/exif/ * https://github.com/drewnoakes/metadata-extractor */ using System; using System.Collections.Generic; using Com.Drew.Imaging.Tiff; using Com.Drew.Lang; using JetBrains.Annotations; using Sharpen; namespace Com.Drew.Metadata.Tiff { /// <summary> /// Adapter between the /// <see cref="Com.Drew.Imaging.Tiff.TiffHandler"/> /// interface and the /// <see cref="Com.Drew.Metadata.Metadata"/> /// / /// <see cref="Com.Drew.Metadata.Directory"/> /// object model. /// </summary> /// <author>Drew Noakes https://drewnoakes.com</author> public abstract class DirectoryTiffHandler : TiffHandler { private readonly Stack<Com.Drew.Metadata.Directory> _directoryStack = new Stack<Com.Drew.Metadata.Directory>(); protected internal Com.Drew.Metadata.Directory _currentDirectory; protected internal readonly Com.Drew.Metadata.Metadata _metadata; protected internal DirectoryTiffHandler(Com.Drew.Metadata.Metadata metadata, Type initialDirectoryClass) { _metadata = metadata; try { _currentDirectory = (Directory)System.Activator.CreateInstance(initialDirectoryClass); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (MemberAccessException e) { throw new RuntimeException(e); } _metadata.AddDirectory(_currentDirectory); } public virtual void EndingIFD() { _currentDirectory = _directoryStack.IsEmpty() ? null : _directoryStack.Pop(); } protected internal virtual void PushDirectory([NotNull] Type directoryClass) { _directoryStack.Push(_currentDirectory); try { _currentDirectory = (Directory)System.Activator.CreateInstance(directoryClass); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (MemberAccessException e) { throw new RuntimeException(e); } _metadata.AddDirectory(_currentDirectory); } public virtual void Warn([NotNull] string message) { _currentDirectory.AddError(message); } public virtual void Error([NotNull] string message) { _currentDirectory.AddError(message); } public virtual void SetByteArray(int tagId, [NotNull] sbyte[] bytes) { _currentDirectory.SetByteArray(tagId, bytes); } public virtual void SetString(int tagId, [NotNull] string @string) { _currentDirectory.SetString(tagId, @string); } public virtual void SetRational(int tagId, [NotNull] Rational rational) { _currentDirectory.SetRational(tagId, rational); } public virtual void SetRationalArray(int tagId, [NotNull] Rational[] array) { _currentDirectory.SetRationalArray(tagId, array); } public virtual void SetFloat(int tagId, float float32) { _currentDirectory.SetFloat(tagId, float32); } public virtual void SetFloatArray(int tagId, [NotNull] float[] array) { _currentDirectory.SetFloatArray(tagId, array); } public virtual void SetDouble(int tagId, double double64) { _currentDirectory.SetDouble(tagId, double64); } public virtual void SetDoubleArray(int tagId, [NotNull] double[] array) { _currentDirectory.SetDoubleArray(tagId, array); } public virtual void SetInt8s(int tagId, sbyte int8s) { // NOTE Directory stores all integral types as int32s, except for int32u and long _currentDirectory.SetInt(tagId, int8s); } public virtual void SetInt8sArray(int tagId, [NotNull] sbyte[] array) { // NOTE Directory stores all integral types as int32s, except for int32u and long _currentDirectory.SetByteArray(tagId, array); } public virtual void SetInt8u(int tagId, short int8u) { // NOTE Directory stores all integral types as int32s, except for int32u and long _currentDirectory.SetInt(tagId, int8u); } public virtual void SetInt8uArray(int tagId, [NotNull] short[] array) { // TODO create and use a proper setter for short[] _currentDirectory.SetObjectArray(tagId, array); } public virtual void SetInt16s(int tagId, int int16s) { // TODO create and use a proper setter for int16u? _currentDirectory.SetInt(tagId, int16s); } public virtual void SetInt16sArray(int tagId, [NotNull] short[] array) { // TODO create and use a proper setter for short[] _currentDirectory.SetObjectArray(tagId, array); } public virtual void SetInt16u(int tagId, int int16u) { // TODO create and use a proper setter for _currentDirectory.SetInt(tagId, int16u); } public virtual void SetInt16uArray(int tagId, [NotNull] int[] array) { // TODO create and use a proper setter for short[] _currentDirectory.SetObjectArray(tagId, array); } public virtual void SetInt32s(int tagId, int int32s) { _currentDirectory.SetInt(tagId, int32s); } public virtual void SetInt32sArray(int tagId, [NotNull] int[] array) { _currentDirectory.SetIntArray(tagId, array); } public virtual void SetInt32u(int tagId, long int32u) { _currentDirectory.SetLong(tagId, int32u); } public virtual void SetInt32uArray(int tagId, [NotNull] long[] array) { // TODO create and use a proper setter for short[] _currentDirectory.SetObjectArray(tagId, array); } public abstract void Completed(RandomAccessReader arg1, int arg2); public abstract bool CustomProcessTag(int arg1, ICollection<int?> arg2, int arg3, RandomAccessReader arg4, int arg5, int arg6); public abstract bool HasFollowerIfd(); public abstract bool IsTagIfdPointer(int arg1); public abstract void SetTiffMarker(int arg1); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Build.Engine { using System; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; using Newtonsoft.Json.Linq; using Microsoft.DocAsCode.Common; using Microsoft.DocAsCode.Exceptions; public class Template { private const string Primary = ".primary"; private const string Auxiliary = ".aux"; private readonly object _locker = new object(); private readonly ResourcePoolManager<ITemplateRenderer> _rendererPool = null; private readonly ResourcePoolManager<ITemplatePreprocessor> _preprocessorPool = null; private readonly string _script; public string Name { get; } public string ScriptName { get; } public string Extension { get; } public string Type { get; } public TemplateType TemplateType { get; } public IEnumerable<TemplateResourceInfo> Resources { get; } public bool ContainsGetOptions { get; } public bool ContainsModelTransformation { get; } public bool ContainsTemplateRenderer { get; } public Template(string name, DocumentBuildContext context, TemplateRendererResource templateResource, TemplatePreprocessorResource scriptResource, ResourceCollection resourceCollection, int maxParallelism) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } Name = name; var templateInfo = GetTemplateInfo(Name); Extension = templateInfo.Extension; Type = templateInfo.DocumentType; TemplateType = templateInfo.TemplateType; _script = scriptResource?.Content; if (!string.IsNullOrWhiteSpace(_script)) { ScriptName = Name + ".js"; _preprocessorPool = ResourcePool.Create(() => CreatePreprocessor(resourceCollection, scriptResource, context), maxParallelism); try { using (var preprocessor = _preprocessorPool.Rent()) { ContainsGetOptions = preprocessor.Resource.GetOptionsFunc != null; ContainsModelTransformation = preprocessor.Resource.TransformModelFunc != null; } } catch (Exception e) { _preprocessorPool = null; Logger.LogWarning($"{ScriptName} is not a valid template preprocessor, ignored: {e.Message}"); } } if (!string.IsNullOrEmpty(templateResource?.Content) && resourceCollection != null) { _rendererPool = ResourcePool.Create(() => CreateRenderer(resourceCollection, templateResource), maxParallelism); ContainsTemplateRenderer = true; } if (!ContainsGetOptions && !ContainsModelTransformation && !ContainsTemplateRenderer) { Logger.LogWarning($"Template {name} contains neither preprocessor to process model nor template to render model. Please check if the template is correctly defined. Allowed preprocessor functions are [exports.getOptions] and [exports.transform]."); } Resources = ExtractDependentResources(Name); } /// <summary> /// exports.getOptions = function (model) { /// return { /// bookmarks : { /// uid1: "bookmark1" /// }, /// isShared: true /// } /// /// } /// </summary> /// <param name="model"></param> /// <returns></returns> public TransformModelOptions GetOptions(object model) { if (_preprocessorPool == null || !ContainsGetOptions) { return null; } object obj; using (var lease = _preprocessorPool.Rent()) { try { obj = lease.Resource.GetOptionsFunc(model); } catch (Exception e) { throw new InvalidPreprocessorException($"Error running GetOptions function inside template preprocessor: {e.Message}"); } } if (obj == null) { return null; } var config = JObject.FromObject(obj).ToObject<TransformModelOptions>(); return config; } /// <summary> /// Transform from raw model to view model /// TODO: refactor to merge model and attrs into one input model /// </summary> /// <param name="model">The raw model</param> /// <param name="attrs">The system generated attributes</param> /// <returns>The view model</returns> public object TransformModel(object model) { if (_preprocessorPool == null || !ContainsModelTransformation) { return model; } using (var lease = _preprocessorPool.Rent()) { try { return lease.Resource.TransformModelFunc(model); } catch (Exception e) { throw new InvalidPreprocessorException($"Error running Transform function inside template preprocessor: {e.Message}"); } } } /// <summary> /// Transform from view model to the final result using template /// Supported template languages are mustache and liquid /// </summary> /// <param name="model">The input view model</param> /// <returns>The output after applying template</returns> public string Transform(object model) { if (_rendererPool == null || !ContainsTemplateRenderer || model == null) { return null; } using (var lease = _rendererPool.Rent()) { return lease.Resource.Render(model); } } private static TemplateInfo GetTemplateInfo(string templateName) { // Remove folder templateName = Path.GetFileName(templateName); var splitterIndex = templateName.IndexOf('.'); if (splitterIndex < 0) { return new TemplateInfo(templateName, string.Empty, TemplateType.Default); } var type = templateName.Substring(0, splitterIndex); var extension = templateName.Substring(splitterIndex); TemplateType templateType = TemplateType.Default; if (extension.EndsWith(Primary)) { templateType = TemplateType.Primary; extension = extension.Substring(0, extension.Length - Primary.Length); } else if (extension.EndsWith(Auxiliary)) { templateType = TemplateType.Auxiliary; extension = extension.Substring(0, extension.Length - Auxiliary.Length); } return new TemplateInfo(type, extension, templateType); } /// <summary> /// Dependent files are defined in following syntax in Mustache template leveraging Mustache Comments /// {{! include('file') }} /// file path can be wrapped by quote ' or double quote " or none /// </summary> /// <param name="template"></param> private IEnumerable<TemplateResourceInfo> ExtractDependentResources(string templateName) { if (_rendererPool == null) { yield break; } using (var lease = _rendererPool.Rent()) { var _renderer = lease.Resource; if (_renderer.Dependencies == null) { yield break; } foreach (var dependency in _renderer.Dependencies) { yield return new TemplateResourceInfo(dependency); } } } private static ITemplatePreprocessor CreatePreprocessor(ResourceCollection resourceCollection, TemplatePreprocessorResource scriptResource, DocumentBuildContext context) { return new TemplateJintPreprocessor(resourceCollection, scriptResource, context); } private static ITemplateRenderer CreateRenderer(ResourceCollection resourceCollection, TemplateRendererResource templateResource) { if (templateResource.Type == TemplateRendererType.Liquid) { return LiquidTemplateRenderer.Create(resourceCollection, templateResource); } else { return new MustacheTemplateRenderer(resourceCollection, templateResource); } } private sealed class TemplateInfo { public string DocumentType { get; } public string Extension { get; } public TemplateType TemplateType { get; } public TemplateInfo(string documentType, string extension, TemplateType type) { DocumentType = documentType; Extension = extension; TemplateType = type; } } } }
using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; using System.Diagnostics; namespace KiloWatt.Animation.Physics { public struct AABB { public AABB(Vector3 lo, Vector3 hi) { Lo = lo; Hi = hi; } public void Set(float ax, float ay, float az, float bx, float by, float bz) { Lo.X = ax; Lo.Y = ay; Lo.Z = az; Hi.X = bx; Hi.Y = by; Hi.Z = bz; } public void Set(Vector3 a, Vector3 b) { Lo.X = Math.Min(a.X, b.X); Hi.X = Math.Max(a.X, b.X); Lo.Y = Math.Min(a.Y, b.Y); Hi.Y = Math.Max(a.Y, b.Y); Lo.Z = Math.Min(a.Z, b.Z); Hi.Z = Math.Max(a.Z, b.Z); } public void Set(Vector3 center, float radius) { Lo.X = center.X - radius; Lo.Y = center.Y - radius; Lo.Z = center.Z - radius; Hi.X = center.X + radius; Hi.Y = center.Y + radius; Hi.Z = center.Z + radius; } public void Inflate(float ds) { System.Diagnostics.Debug.Assert(ds >= 0); Lo.X -= ds; Lo.Y -= ds; Lo.Z -= ds; Hi.X += ds; Hi.Y += ds; Hi.Z += ds; } public void Include(Vector3 pt) { if (Lo.X > pt.X) Lo.X = pt.X; if (Hi.X < pt.X) Hi.X = pt.X; if (Lo.Y > pt.Y) Lo.Y = pt.Y; if (Hi.Y < pt.Y) Hi.Y = pt.Y; if (Lo.Z > pt.Z) Lo.Z = pt.Z; if (Hi.Z < pt.Z) Hi.Z = pt.Z; } public void Set(Vector3 start, Vector3 dim, float len) { Set(start, start + dim * len); } public Vector3 Lo; public Vector3 Hi; public Vector3 Center { get { return (Lo + Hi) * 0.5f; } } public Vector3 HalfDim { get { return (Hi - Lo) * 0.5f; } } public bool Empty { get { return Hi.X <= Lo.X || Hi.Y <= Lo.Y || Hi.Z <= Lo.Z; } } public bool Overlaps(AABB other) { return Overlaps(ref other, 0); } public bool Overlaps(ref AABB other, float expand) { if (other.Lo.X >= Hi.X + expand || other.Hi.X <= Lo.X - expand) return false; if (other.Lo.Y >= Hi.Y + expand || other.Hi.Y <= Lo.Y - expand) return false; if (other.Lo.Z >= Hi.Z + expand || other.Hi.Z <= Lo.Z - expand) return false; return true; } public void SetUnion(AABB other) { Lo.X = Math.Min(Lo.X, other.Lo.X); Lo.Y = Math.Min(Lo.Y, other.Lo.Y); Lo.Z = Math.Min(Lo.Z, other.Lo.Z); Hi.X = Math.Max(Hi.X, other.Hi.X); Hi.Y = Math.Max(Hi.Y, other.Hi.Y); Hi.Z = Math.Max(Hi.Z, other.Hi.Z); } public bool SetIntersection(AABB other) { if (Empty) { Lo = other.Lo; Hi = other.Hi; } else if (!other.Empty) { Lo.X = Math.Max(Lo.X, other.Lo.X); Lo.Y = Math.Max(Lo.Y, other.Lo.Y); Lo.Z = Math.Max(Lo.Z, other.Lo.Z); Hi.X = Math.Min(Hi.X, other.Hi.X); Hi.Y = Math.Min(Hi.Y, other.Hi.Y); Hi.Z = Math.Min(Hi.Z, other.Hi.Z); } if (Hi.X > Lo.X && Hi.Y > Lo.Y && Hi.Z > Lo.Z) return true; Hi = Lo; return false; } public override string ToString() { return String.Format("{0}-{1}", Lo, Hi); } public bool Intersects(ref Ray collRay, ref float dd) { return Intersects(ref collRay, ref dd, 0); } public bool Intersects(ref Ray collRay, ref float dd, float expand) { float minI = 0; float maxI = dd; Vector3 lo = Lo - new Vector3(expand, expand, expand); Vector3 hi = Hi + new Vector3(expand, expand, expand); if (Math.Abs(collRay.Direction.X) < 1e-10f) { if (collRay.Position.X < lo.X || collRay.Position.X > hi.X) return false; } else { float d = 1.0f / collRay.Direction.X; if (collRay.Direction.X > 0) { minI = Math.Max(minI, (lo.X - collRay.Position.X) * d); maxI = Math.Min(maxI, (hi.X - collRay.Position.X) * d); } else { minI = Math.Max(minI, (hi.X - collRay.Position.X) * d); maxI = Math.Min(maxI, (lo.X - collRay.Position.X) * d); } if (minI >= maxI) return false; } if (Math.Abs(collRay.Direction.Y) < 1e-10f) { if (collRay.Position.Y < lo.Y || collRay.Position.Y > hi.Y) return false; } else { float d = 1.0f / collRay.Direction.Y; if (collRay.Direction.Y > 0) { minI = Math.Max(minI, (lo.Y - collRay.Position.Y) * d); maxI = Math.Min(maxI, (hi.Y - collRay.Position.Y) * d); } else { minI = Math.Max(minI, (hi.Y - collRay.Position.Y) * d); maxI = Math.Min(maxI, (lo.Y - collRay.Position.Y) * d); } if (minI >= maxI) return false; } if (Math.Abs(collRay.Direction.Z) < 1e-10f) { if (collRay.Position.Z < lo.Z || collRay.Position.Z > hi.Z) return false; } else { float d = 1.0f / collRay.Direction.Z; if (collRay.Direction.Z > 0) { minI = Math.Max(minI, (lo.Z - collRay.Position.Z) * d); maxI = Math.Min(maxI, (hi.Z - collRay.Position.Z) * d); } else { minI = Math.Max(minI, (hi.Z - collRay.Position.Z) * d); maxI = Math.Min(maxI, (lo.Z - collRay.Position.Z) * d); } if (minI >= maxI) return false; } dd = minI; return true; } public bool Contains(Vector3 c) { return (Lo.X <= c.X && Lo.Y <= c.Y && Lo.Z <= c.Z && Hi.X > c.X && Hi.Y > c.Y && Hi.Z > c.Z); } internal Vector3 Vertex(int p) { return new Vector3( ((p & 1) == 0) ? Lo.X : Hi.X, ((p & 2) == 0) ? Lo.Y : Hi.Y, ((p & 4) == 0) ? Lo.Z : Hi.Z); } static int[] HasVerts = new int[8 * 3] { 1, 2, 4, 0, 3, 5, 1, 2, 6, 0, 3, 7, 0, 5, 6, 1, 4, 7, 2, 5, 6, 3, 4, 7, }; internal bool HasEdgeBetweenVertices(int i, int j, out Ray ray) { int q = i + i + i; bool ret = (HasVerts[q] == j) || (HasVerts[q + 1] == j) || (HasVerts[q + 2] == j); ray = new Ray( new Vector3(((i & 1) == 0) ? Lo.X : Hi.X, ((i & 2) == 0) ? Lo.Y : Hi.Y, ((i & 4) == 0) ? Lo.Z : Hi.Z), new Vector3((i & 1) - (j & 1), ((i & 4) - (j & 4)) * 0.25f, ((i & 2) - (j & 2)) * 0.5f)); Debug.Assert(ret == false || (ray.Direction.Y == 0 && ray.Direction.Z == 0) || (ray.Direction.Z == 0 && ray.Direction.X == 0) || (ray.Direction.X == 0 && ray.Direction.Y == 0)); Debug.Assert(ret == false || ray.Direction.LengthSquared() == 1); return ret; } internal bool Overlaps(ref BoundingSphere sphere, float expand) { // find the point in the box that's closest to the center Vector3 c = sphere.Center; Vector3.Min(ref c, ref Hi, out c); Vector3.Max(ref c, ref Lo, out c); Vector3.Subtract(ref c, ref sphere.Center, out c); // calculate distance squared between that and center float d2; Vector3.Dot(ref c, ref c, out d2); // if within range, we overlap return (sphere.Radius + expand) * (sphere.Radius + expand) >= d2; } } }
using System; using System.Data; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Text; using Epi.Analysis; using Epi.Windows.Dialogs; using Epi.Windows.Analysis; using Epi.Data.Services; namespace Epi.Windows.Analysis.Dialogs { /// <summary> /// Dialog for Frequency command /// </summary> public partial class ComplexSampleFrequencyDialog : CommandDesignDialog { #region Private Fields private Project currentProject; private string SetClauses = null; #endregion #region Constructor /// <summary> /// Default constructor - NOT TO BE USED FOR INSTANTIATION /// </summary> [Obsolete("Use of default constructor not allowed", true)] public ComplexSampleFrequencyDialog() { InitializeComponent(); } /// <summary> /// Constructor for the Frequency dialog /// </summary> /// <param name="frm"></param> public ComplexSampleFrequencyDialog(Epi.Windows.Analysis.Forms.AnalysisMainForm frm) : base(frm) { InitializeComponent(); Construct(); } private void Construct() { if (!this.DesignMode) // designer throws an error { this.btnOK.Click += new System.EventHandler(this.btnOK_Click); this.btnSaveOnly.Click += new System.EventHandler(this.btnSaveOnly_Click); } //IProjectHost host = Module.GetService(typeof(IProjectHost)) as IProjectHost; //if (host == null) //{ // throw new GeneralException("No project is hosted by service provider."); //} //// get project reference //Project project = host.CurrentProject; //if (project == null) //{ // //A native DB has been read, no longer need to show error message // //throw new GeneralException("You must first open a project."); // //MessageBox.Show("You must first open a project."); // //this.Close(); //} //else //{ // currentProject = project; //} } #endregion Constructors #region Private Properties private string txtWeightVar = string.Empty; private string txtPSUVar = string.Empty; #endregion Private Properties #region Protected Methods /// <summary> /// Generates the command text /// </summary> protected override void GenerateCommand() { StringBuilder command = new StringBuilder(); command.Append(CommandNames.FREQ); if (this.cbxAllExcept.Checked) { command.Append(StringLiterals.SPACE); command.Append(StringLiterals.STAR); command.Append(StringLiterals.SPACE); command.Append("EXCEPT"); } if (this.lbxVariables.Items.Count > 0) { foreach (string item in lbxVariables.Items) { command.Append(StringLiterals.SPACE); command.Append(item.ToString()); } } else { command.Append(StringLiterals.SPACE).Append(StringLiterals.STAR); } if (lbxStratifyBy.Items.Count > 0) { string strStVar = CommandNames.STRATAVAR + StringLiterals.EQUAL; foreach (string s in lbxStratifyBy.Items) { strStVar = strStVar + s + StringLiterals.SPACE; } command.Append(StringLiterals.SPACE).Append(strStVar.Trim()); } if (cmbWeight.Text != string.Empty) { command.Append(StringLiterals.SPACE); command.Append(CommandNames.WEIGHTVAR); command.Append(StringLiterals.EQUAL); command.Append(cmbWeight.Text.ToString()); } if (txtOutput.Text != string.Empty) { command.Append(StringLiterals.SPACE); command.Append(CommandNames.OUTTABLE); command.Append(StringLiterals.EQUAL); command.Append(txtOutput.Text.ToString()); } if (!string.IsNullOrEmpty(this.SetClauses)) { command.Append(StringLiterals.SPACE); command.Append(this.SetClauses); } command.Append(StringLiterals.SPACE); command.Append("PSUVAR="); command.Append(cmbPSU.Text); CommandText = command.ToString(); } /// <summary> /// Output Table /// </summary> protected void OutputTable() { } /// <summary> /// Validates user input /// </summary> /// <returns>True/False depending upon whether error messages were found</returns> protected override bool ValidateInput() { base.ValidateInput(); if (this.lbxVariables.Items.Count == 0) { if (this.cbxAllExcept.Checked) { ErrorMessages.Add(SharedStrings.SELECT_EXCLUSION_VARIABLES); } else { ErrorMessages.Add(SharedStrings.SELECT_VARIABLE); } } if (this.cmbPSU.SelectedIndex == -1) { ErrorMessages.Add(SharedStrings.MUST_SELECT_PSU); } //if (!string.IsNullOrEmpty(txtOutput.Text.Trim())) //{ // currentProject.CollectedData.TableExists(txtOutput.Text.Trim()); // ErrorMessages.Add(SharedStrings.TABLE_EXISTS_OUTPUT); //} return (ErrorMessages.Count == 0); } #endregion //Protected Methods #region Private methods //private void LoadVariables(ComboBox cmb, DataTable tbl, bool numericOnly) //{ // String cn = ColumnNames.NAME; // String dt = ColumnNames.DATA_TYPE; // string s; // foreach (DataRow row in tbl.Rows) // { // if (!numericOnly || (Int32.Parse(row[dt].ToString()) == (Int32)DataType.Number)) // { // s = row[cn].ToString(); // if (s != ColumnNames.REC_STATUS && s != ColumnNames.UNIQUE_KEY) // { // cmb.Items.Add(row[cn].ToString()); // } // } // } //} #endregion #region Public Methods /// <summary> /// Sets enabled property of OK and Save Only /// </summary> public override void CheckForInputSufficiency() { bool inputValid = ValidateInput(); btnOK.Enabled = inputValid; btnSaveOnly.Enabled = inputValid; } #endregion Public Methods #region Event Handlers /// <summary> /// Handles the Click event for btnClear. /// Clears items from the comboboxes and reloads the dialog. /// </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) { cmbVariables.Items.Clear(); cmbStratifyBy.Items.Clear(); cmbWeight.Items.Clear(); cmbPSU.Items.Clear(); cbxAllExcept.Checked = false; lbxVariables.Items.Clear(); lbxStratifyBy.Items.Clear(); cmbWeight.Text = string.Empty; cmbPSU.Text = string.Empty; txtOutput.Text = string.Empty; cmbStratifyBy.Text = string.Empty; ComplexSampleFrequencyDialog_Load(this, null); CheckForInputSufficiency(); } /// <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 cmbVariables_SelectedIndexChanged(object sender, EventArgs e) { if (cmbVariables.Text != StringLiterals.STAR) { string s = cmbVariables.Text; lbxVariables.Items.Add(s); cmbStratifyBy.Items.Remove(s); cmbWeight.Items.Remove(s); cmbPSU.Items.Remove(s); cmbVariables.Items.Remove(s); CheckForInputSufficiency(); } } /// <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 cmbStratifyBy_SelectedIndexChanged(object sender, EventArgs e) { if (cmbStratifyBy.Text != StringLiterals.SPACE) { string s = cmbStratifyBy.Text; lbxStratifyBy.Items.Add(s); cmbStratifyBy.Items.Remove(s); cmbVariables.Items.Remove(s); cmbWeight.Items.Remove(s); cmbPSU.Items.Remove(s); } } /// <summary> /// Handles the Attach Event for the form, fills all of the dialogs with a list of variables. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void ComplexSampleFrequencyDialog_Load(object sender, EventArgs e) { VariableType scopeWord = VariableType.DataSource | VariableType.DataSourceRedefined | VariableType.Standard; FillVariableCombo(cmbVariables, scopeWord); //cmbVariables.Items.Add("*"); cmbVariables.SelectedIndex = -1; FillVariableCombo(cmbStratifyBy, scopeWord); cmbStratifyBy.SelectedIndex = -1; FillVariableCombo(cmbWeight, scopeWord); cmbWeight.SelectedIndex = -1; FillVariableCombo(cmbPSU, scopeWord); cmbPSU.SelectedIndex = -1; } /// <summary> /// Handles the Selected Index Change event for lbxVariables. /// Moves the variable name back to the comboboxes /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void lbxVariables_SelectedIndexChanged(object sender, EventArgs e) { if (lbxVariables.SelectedIndex >= 0) // prevent the remove below from re-entering { string s = lbxVariables.SelectedItem.ToString(); cmbVariables.Items.Add(s); cmbStratifyBy.Items.Add(s); cmbPSU.Items.Add(s); cmbWeight.Items.Add(s); lbxVariables.Items.Remove(s); } CheckForInputSufficiency(); } /// <summary> /// Handles the Selected Index Change event for lbxStratifyBy. /// Moves the variable name back to the comboboxes. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void lbxStratifyBy_SelectedIndexChanged(object sender, EventArgs e) { if (lbxStratifyBy.SelectedIndex >= 0) // prevent the remove below from re-entering { string s = this.lbxStratifyBy.SelectedItem.ToString(); cmbVariables.Items.Add(s); cmbStratifyBy.Items.Add(s); cmbPSU.Items.Add(s); cmbWeight.Items.Add(s); lbxStratifyBy.Items.Remove(s); } } /// <summary> /// Handles the Click event for btnSettings. /// Instantiates a new Settings dialog, sets its dialog mode = True. /// Shows the dialog and returns any settings. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void btnSettings_Click(object sender, EventArgs e) { SetDialog SD = new SetDialog(mainForm); SD.isDialogMode = true; SD.ShowDialog(); SetClauses = SD.CommandText; SD.Close(); } /// <summary> /// Handles the Selected Index Change event for cmbPSU. /// Removes the variable name from the other comboboxes. /// Returns the old variable name (if any) to the other comboboxes. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbPSU_SelectedIndexChanged(object sender, EventArgs e) { if (cmbPSU.SelectedIndex >= 0) { string s = this.txtPSUVar; if ((s.Length > 0) && (s != cmbPSU.Text)) { cmbVariables.Items.Add(s); cmbStratifyBy.Items.Add(s); cmbWeight.Items.Add(s); } s = this.cmbPSU.SelectedItem.ToString(); cmbVariables.Items.Remove(s); cmbStratifyBy.Items.Remove(s); cmbWeight.Items.Remove(s); this.txtPSUVar = s; } CheckForInputSufficiency(); } /// <summary> /// Handles the Selected Index Change event for cmbWeight. /// Removes the variable name from the other comboboxes. /// Returns the old variable name (if any) to the other comboboxes. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbWeight_SelectedIndexChanged(object sender, EventArgs e) { //Get the old variable chosen that was saved to the txt string. string strOld = txtWeightVar; string strNew = cmbWeight.Text; //make sure it isn't "" or the same as the new variable picked. if ((strOld.Length > 0) && (strOld != strNew)) { cmbVariables.Items.Add(strOld); cmbStratifyBy.Items.Add(strOld); cmbPSU.Items.Add(strOld); } if (cmbWeight.SelectedIndex >= 0) { cmbVariables.Items.Remove(strNew); cmbStratifyBy.Items.Remove(strNew); cmbPSU.Items.Remove(strNew); this.txtWeightVar = strNew; } } /// <summary> /// Handles the KeyDown event for cmbWeight. /// Allows to delete the optional value for Weight. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbWeight_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Delete) { //SelectedIndexChanged will add the var back to the other DDLs cmbWeight.Text = ""; cmbWeight.SelectedIndex = -1; } } /// <summary> /// Handles the Click event for cmbWeight. /// Saves the content of the text to the temp storage or resets it. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbWeight_Click(object sender, EventArgs e) { txtWeightVar = (cmbWeight.SelectedIndex >= 0) ? cmbWeight.Text : String.Empty; } /// <summary> /// Handles the Click event for cmbPSU. /// Saves the content of the text to the temp storage or resets it. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbPSU_Click(object sender, EventArgs e) { txtPSUVar = (cmbPSU.SelectedIndex >= 0) ? cmbPSU.Text : String.Empty; } /// <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-freq.html"); } #endregion //Event Handlers } }
// 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.Ads.GoogleAds.V10.Services { /// <summary>Settings for <see cref="AdGroupAdLabelServiceClient"/> instances.</summary> public sealed partial class AdGroupAdLabelServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="AdGroupAdLabelServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="AdGroupAdLabelServiceSettings"/>.</returns> public static AdGroupAdLabelServiceSettings GetDefault() => new AdGroupAdLabelServiceSettings(); /// <summary> /// Constructs a new <see cref="AdGroupAdLabelServiceSettings"/> object with default settings. /// </summary> public AdGroupAdLabelServiceSettings() { } private AdGroupAdLabelServiceSettings(AdGroupAdLabelServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); MutateAdGroupAdLabelsSettings = existing.MutateAdGroupAdLabelsSettings; OnCopy(existing); } partial void OnCopy(AdGroupAdLabelServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AdGroupAdLabelServiceClient.MutateAdGroupAdLabels</c> and /// <c>AdGroupAdLabelServiceClient.MutateAdGroupAdLabelsAsync</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 MutateAdGroupAdLabelsSettings { 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="AdGroupAdLabelServiceSettings"/> object.</returns> public AdGroupAdLabelServiceSettings Clone() => new AdGroupAdLabelServiceSettings(this); } /// <summary> /// Builder class for <see cref="AdGroupAdLabelServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class AdGroupAdLabelServiceClientBuilder : gaxgrpc::ClientBuilderBase<AdGroupAdLabelServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public AdGroupAdLabelServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public AdGroupAdLabelServiceClientBuilder() { UseJwtAccessWithScopes = AdGroupAdLabelServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref AdGroupAdLabelServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AdGroupAdLabelServiceClient> task); /// <summary>Builds the resulting client.</summary> public override AdGroupAdLabelServiceClient Build() { AdGroupAdLabelServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<AdGroupAdLabelServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<AdGroupAdLabelServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private AdGroupAdLabelServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return AdGroupAdLabelServiceClient.Create(callInvoker, Settings); } private async stt::Task<AdGroupAdLabelServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return AdGroupAdLabelServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => AdGroupAdLabelServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => AdGroupAdLabelServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => AdGroupAdLabelServiceClient.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>AdGroupAdLabelService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage labels on ad group ads. /// </remarks> public abstract partial class AdGroupAdLabelServiceClient { /// <summary> /// The default endpoint for the AdGroupAdLabelService 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 AdGroupAdLabelService scopes.</summary> /// <remarks> /// The default AdGroupAdLabelService 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="AdGroupAdLabelServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="AdGroupAdLabelServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="AdGroupAdLabelServiceClient"/>.</returns> public static stt::Task<AdGroupAdLabelServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new AdGroupAdLabelServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="AdGroupAdLabelServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="AdGroupAdLabelServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="AdGroupAdLabelServiceClient"/>.</returns> public static AdGroupAdLabelServiceClient Create() => new AdGroupAdLabelServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="AdGroupAdLabelServiceClient"/> 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="AdGroupAdLabelServiceSettings"/>.</param> /// <returns>The created <see cref="AdGroupAdLabelServiceClient"/>.</returns> internal static AdGroupAdLabelServiceClient Create(grpccore::CallInvoker callInvoker, AdGroupAdLabelServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } AdGroupAdLabelService.AdGroupAdLabelServiceClient grpcClient = new AdGroupAdLabelService.AdGroupAdLabelServiceClient(callInvoker); return new AdGroupAdLabelServiceClientImpl(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 AdGroupAdLabelService client</summary> public virtual AdGroupAdLabelService.AdGroupAdLabelServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Creates and removes ad group ad labels. /// Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [LabelError]() /// [MutateError]() /// [NewResourceCreationError]() /// [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 MutateAdGroupAdLabelsResponse MutateAdGroupAdLabels(MutateAdGroupAdLabelsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates and removes ad group ad labels. /// Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [LabelError]() /// [MutateError]() /// [NewResourceCreationError]() /// [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<MutateAdGroupAdLabelsResponse> MutateAdGroupAdLabelsAsync(MutateAdGroupAdLabelsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates and removes ad group ad labels. /// Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [LabelError]() /// [MutateError]() /// [NewResourceCreationError]() /// [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<MutateAdGroupAdLabelsResponse> MutateAdGroupAdLabelsAsync(MutateAdGroupAdLabelsRequest request, st::CancellationToken cancellationToken) => MutateAdGroupAdLabelsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates and removes ad group ad labels. /// Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [LabelError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. ID of the customer whose ad group ad labels are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on ad group ad labels. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateAdGroupAdLabelsResponse MutateAdGroupAdLabels(string customerId, scg::IEnumerable<AdGroupAdLabelOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateAdGroupAdLabels(new MutateAdGroupAdLabelsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates and removes ad group ad labels. /// Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [LabelError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. ID of the customer whose ad group ad labels are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on ad group ad labels. /// </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<MutateAdGroupAdLabelsResponse> MutateAdGroupAdLabelsAsync(string customerId, scg::IEnumerable<AdGroupAdLabelOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateAdGroupAdLabelsAsync(new MutateAdGroupAdLabelsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates and removes ad group ad labels. /// Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [LabelError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. ID of the customer whose ad group ad labels are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on ad group ad labels. /// </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<MutateAdGroupAdLabelsResponse> MutateAdGroupAdLabelsAsync(string customerId, scg::IEnumerable<AdGroupAdLabelOperation> operations, st::CancellationToken cancellationToken) => MutateAdGroupAdLabelsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>AdGroupAdLabelService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage labels on ad group ads. /// </remarks> public sealed partial class AdGroupAdLabelServiceClientImpl : AdGroupAdLabelServiceClient { private readonly gaxgrpc::ApiCall<MutateAdGroupAdLabelsRequest, MutateAdGroupAdLabelsResponse> _callMutateAdGroupAdLabels; /// <summary> /// Constructs a client wrapper for the AdGroupAdLabelService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="AdGroupAdLabelServiceSettings"/> used within this client.</param> public AdGroupAdLabelServiceClientImpl(AdGroupAdLabelService.AdGroupAdLabelServiceClient grpcClient, AdGroupAdLabelServiceSettings settings) { GrpcClient = grpcClient; AdGroupAdLabelServiceSettings effectiveSettings = settings ?? AdGroupAdLabelServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callMutateAdGroupAdLabels = clientHelper.BuildApiCall<MutateAdGroupAdLabelsRequest, MutateAdGroupAdLabelsResponse>(grpcClient.MutateAdGroupAdLabelsAsync, grpcClient.MutateAdGroupAdLabels, effectiveSettings.MutateAdGroupAdLabelsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateAdGroupAdLabels); Modify_MutateAdGroupAdLabelsApiCall(ref _callMutateAdGroupAdLabels); 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_MutateAdGroupAdLabelsApiCall(ref gaxgrpc::ApiCall<MutateAdGroupAdLabelsRequest, MutateAdGroupAdLabelsResponse> call); partial void OnConstruction(AdGroupAdLabelService.AdGroupAdLabelServiceClient grpcClient, AdGroupAdLabelServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC AdGroupAdLabelService client</summary> public override AdGroupAdLabelService.AdGroupAdLabelServiceClient GrpcClient { get; } partial void Modify_MutateAdGroupAdLabelsRequest(ref MutateAdGroupAdLabelsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Creates and removes ad group ad labels. /// Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [LabelError]() /// [MutateError]() /// [NewResourceCreationError]() /// [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 MutateAdGroupAdLabelsResponse MutateAdGroupAdLabels(MutateAdGroupAdLabelsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateAdGroupAdLabelsRequest(ref request, ref callSettings); return _callMutateAdGroupAdLabels.Sync(request, callSettings); } /// <summary> /// Creates and removes ad group ad labels. /// Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [LabelError]() /// [MutateError]() /// [NewResourceCreationError]() /// [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<MutateAdGroupAdLabelsResponse> MutateAdGroupAdLabelsAsync(MutateAdGroupAdLabelsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateAdGroupAdLabelsRequest(ref request, ref callSettings); return _callMutateAdGroupAdLabels.Async(request, callSettings); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics.Contracts; using Microsoft.VisualStudio.Text; using Microsoft.RestrictedUsage.CSharp.Core; using Microsoft.RestrictedUsage.CSharp.Extensions; using Microsoft.RestrictedUsage.CSharp.Semantics; using Microsoft.RestrictedUsage.CSharp.Utilities; using Microsoft.RestrictedUsage.CSharp.Syntax; using Microsoft.RestrictedUsage.CSharp.Compiler; using Microsoft.Cci.Contracts; using Microsoft.Cci; using System.Runtime.InteropServices; using UtilitiesNamespace; namespace ContractAdornments { public static class IntellisenseContractsHelper { public static CSharpMember GetSemanticMember(this ParseTreeNode parseTreeNode, Compilation comp, SourceFile sourceFile) { Contract.Requires(parseTreeNode != null); Contract.Requires(comp != null); Contract.Requires(sourceFile != null); Contract.Ensures(Contract.Result<CSharpMember>() == null || Contract.Result<CSharpMember>().IsMethod || Contract.Result<CSharpMember>().IsConstructor || Contract.Result<CSharpMember>().IsProperty || Contract.Result<CSharpMember>().IsIndexer); // The CSharp model can throw internal exceptions at unexpected moments, so we filter them here: try { CSharpMember semanticMember; if (parseTreeNode.IsAnyMember()) { semanticMember = comp.GetMemberFromMemberDeclaration(parseTreeNode); if (semanticMember == null) return null; goto Success; } //Can we get our expression tree? var expressionTree = comp.FindExpressionTree(sourceFile, parseTreeNode); if (expressionTree == null) return null; //Can we get our expression? var expression = expressionTree.FindLeafExpression(parseTreeNode); if (expression == null) return null; //Can we get our semanticMember? semanticMember = expression.FindExpressionExplicitMember(); if (semanticMember == null) { MEMGRPExpression memgrpExpr = expression as MEMGRPExpression; if (memgrpExpr != null) { var foo = memgrpExpr.OwningCall; if (foo != null) { semanticMember = foo.mwi; } if (semanticMember == null && memgrpExpr.mps != null && memgrpExpr.mps.Text == "$Item$") { if (memgrpExpr.Object != null && memgrpExpr.Object.Type != null) { var type = memgrpExpr.Object.Type; if (type.Members == null) goto TryNext; // find indexer member for (int i = 0; i < type.Members.Count; i++) { var mem = type.Members[i]; if (mem == null) continue; if (mem.IsIndexer) { semanticMember = mem; break; } } } } } } TryNext: ; Success: //Is our semanticMember a method? if (semanticMember == null || !(semanticMember.IsMethod || semanticMember.IsConstructor || semanticMember.IsProperty || semanticMember.IsIndexer)) return null; //Unistantiate semanticMember = semanticMember.Uninstantiate(); return semanticMember; } catch (ArgumentException) { return null; } } public static ParseTreeNode GetAnyCallNodeAboveTriggerPoint(ITrackingPoint triggerPoint, ITextSnapshot snapshot, ParseTree parseTree) { Contract.Requires(snapshot != null); Contract.Requires(parseTree != null); Contract.Requires(triggerPoint != null); //Can we get our position? var pos = triggerPoint.Convert(snapshot); if (pos == default(Position)) return null; //Can we get our leaf node? var leafNode = parseTree.FindLeafNode(pos); if (leafNode == null) return null; //Is anyone in our ancestry a call node? var nodeInQuestion = leafNode; ParseTreeNode ptn = null; while (nodeInQuestion != null) { //Is the node in question a node call? var asCall = nodeInQuestion.AsAnyCall(); if (asCall != null) { ptn = asCall; break; } var asCtorCall = nodeInQuestion.AsAnyCreation(); if (asCtorCall != null) { ptn = asCtorCall; break; } //Climp higher up our ancestry for the next iteration nodeInQuestion = nodeInQuestion.Parent; } //Did we successfully find a call node? return ptn; } public static ParseTreeNode GetTargetAtTriggerPoint(ITrackingPoint triggerPoint, ITextSnapshot snapshot, ParseTree parseTree) { Contract.Requires(snapshot != null); Contract.Requires(parseTree != null); Contract.Requires(triggerPoint != null); //Can we get our position? var pos = triggerPoint.Convert(snapshot); if (pos == default(Position)) return null; //Can we get our leaf node? var leafNode = parseTree.FindLeafNode(pos); if (leafNode == null) return null; var asPropDecl = leafNode.AsProperty(); if (asPropDecl != null) { return asPropDecl; } //Is our leaf node a name? var asName = leafNode.AsAnyName(); if (asName == null) return null; //Is anyone in our ancestry a call node? var nodeInQuestion = leafNode; var lastNonBinaryOperatorNode = leafNode; var lastNode = leafNode; while (nodeInQuestion != null) { //Is the node in question a node call? var asCall = nodeInQuestion.AsAnyCall(); if (asCall != null) { //Make sure we aren't on the right side of the call if (asCall.Right == lastNode) return null; return asCall; } var asProp = nodeInQuestion.AsDot(); if (asProp != null) { //Make sure we aren't on the left side of the dot if (asProp.Right == lastNode && asProp.Right.IsName()) { return asProp; } } var asCtorCall = nodeInQuestion.AsAnyCreation(); if (asCtorCall != null) { return asCtorCall; } var declNode = nodeInQuestion.AsAnyMember(); if (declNode != null) { if (lastNode == leafNode) { return declNode; } return null; } NamedAssignmentNode na = nodeInQuestion as NamedAssignmentNode; if (na != null) { if (na.Identifier == asName) { return na; } } //Is our parent a binary operator? var asBinaryOperator = nodeInQuestion.AsAnyBinaryOperator(); if (asBinaryOperator != null) { //Make sure we are always on the rightmost of any binary operator if (asBinaryOperator.Right != lastNonBinaryOperatorNode) return null; } else lastNonBinaryOperatorNode = nodeInQuestion; //Climp higher up our ancestry for the next iteration lastNode = nodeInQuestion; nodeInQuestion = nodeInQuestion.Parent; } //Did we successfully find a call node? if (nodeInQuestion == null) return null; if (nodeInQuestion.Kind != NodeKind.Call) return null; var callNode = nodeInQuestion.AsAnyCall(); return callNode; } public static string FormatContracts(IMethodContract methodContracts) { //Did we get proper contracts? if (methodContracts == null) { //Return a message saying we failed to get contracts return "(Failed to properly get contracts)"; } //Do we have any contracts? if (IsEmptyContract(methodContracts)) { //Return a message saying we don't have any contracts return null; } //Initialize our string builder var sb = new StringBuilder(); //Append the 'Contracts' header sb.Append("Contracts: "); sb.Append('\n'); //Append purity if (methodContracts.IsPure) { sb.Append(" "); sb.Append("[Pure]"); sb.Append('\n'); } FormatPrePostThrows(methodContracts, sb); //Can we get our result from the string builder? var result = sb.ToString(); //Trim the new lines from the end result = result.TrimEnd('\n'); result = SmartFormat(result); //Return our result return result; } private static bool IsEmptyContract(IMethodContract methodContracts) { Contract.Ensures(Contract.Result<bool>() || methodContracts != null); return methodContracts == null || (methodContracts == ContractDummy.MethodContract) || (!methodContracts.IsPure && methodContracts.Preconditions.Count() < 1 && methodContracts.Postconditions.Count() < 1 && methodContracts.ThrownExceptions.Count() < 1); } static string IndentString = Environment.NewLine + " "; private static void FormatPrePostThrows(IMethodContract methodContracts, StringBuilder sb) { Contract.Requires(methodContracts != null); Contract.Requires(sb != null); if (methodContracts.Postconditions != null) { //Append our preconditions foreach (var pre in methodContracts.Preconditions) { if (pre == null) continue; if (pre.OriginalSource == null) continue; sb.Append(" "); sb.Append("requires "); sb.Append(pre.OriginalSource.Replace(Environment.NewLine, IndentString)); sb.Append('\n'); } } if (methodContracts.Postconditions != null) { //Append our postconditions foreach (var post in methodContracts.Postconditions) { if (post == null) continue; if (post.OriginalSource == null) continue; sb.Append(" "); sb.Append("ensures "); sb.Append(post.OriginalSource.Replace(Environment.NewLine, IndentString)); sb.Append('\n'); } } if (methodContracts.ThrownExceptions != null) { //Append our on throw conditions foreach (var onThrow in methodContracts.ThrownExceptions) { if (onThrow == null) continue; if (onThrow.ExceptionType == null) continue; if (onThrow.Postcondition == null) continue; if (onThrow.Postcondition.OriginalSource == null) continue; sb.Append(" "); sb.Append("ensures on throw of "); var onThrowType = TypeHelper.GetTypeName(onThrow.ExceptionType, NameFormattingOptions.OmitContainingType | NameFormattingOptions.OmitContainingNamespace); sb.Append(onThrowType); sb.Append(" that "); sb.Append(onThrow.Postcondition.OriginalSource.Replace(Environment.NewLine, IndentString)); sb.Append('\n'); } } } private static string SmartFormat(string result) { if (string.IsNullOrEmpty(result)) return result; if (ContractsPackageAccessor.Current.VSOptionsPage != null && ContractsPackageAccessor.Current.VSOptionsPage.SmartFormatting) { var startTime = DateTime.Now; var trySmartReplace = result; try { //Simplify how contracts look trySmartReplace = trySmartReplace.SmartReplace("Contract.OldValue<{0}>({1})", "old({1})"); trySmartReplace = trySmartReplace.SmartReplace("Contract.OldValue({0})", "old({0})"); trySmartReplace = trySmartReplace.SmartReplace("Contract.Result<{0}>()", "result"); trySmartReplace = trySmartReplace.SmartReplace("Contract.ValueAtReturn<{0}>({1})", "out({1})"); trySmartReplace = trySmartReplace.SmartReplace("Contract.ValueAtReturn({0})", "out({0})"); trySmartReplace = trySmartReplace.SmartReplace("Contract.ForAll<{0}>({1})", "forall({1})"); trySmartReplace = trySmartReplace.SmartReplace("Contract.ForAll({0})", "forall({0})"); } catch (Exception) { trySmartReplace = null; ContractsPackageAccessor.Current.Logger.WriteToLog("Error: Smart formatting failed!"); ContractsPackageAccessor.Current.Logger.WriteToLog(result); } if (trySmartReplace != null) result = trySmartReplace; var elapsedTime = DateTime.Now - startTime; ContractsPackageAccessor.Current.Logger.WriteToLog("\t(Smart formatting took " + elapsedTime.Milliseconds + "ms)"); } return result; } internal static string FormatPropertyContracts(IMethodContract getter, IMethodContract setter) { //Initialize our string builder var sb = new StringBuilder(); //Append the 'Contracts' header //sb.Append("Contracts: "); //sb.Append('\n'); if (!IsEmptyContract(getter)) { sb.Append("get "); sb.Append('\n'); FormatPrePostThrows(getter, sb); } if (!IsEmptyContract(setter)) { sb.Append("set "); sb.Append('\n'); FormatPrePostThrows(setter, sb); } //Can we get our result from the string builder? var result = sb.ToString(); if (result == "") return null; //Trim the new lines from the end result = result.TrimEnd('\n'); result = SmartFormat(result); //Return our result return result; } } }
using System; using System.IO.Ports; using System.Text; using com.bangbits.metering.logging; using com.bangbits.metering.utils; namespace com.bangbits.metering.connection { /// <summary> /// SerialMeterConnection is an implementation of IMeterConnection for binary communication over /// a serial port. You supply the class the name of the serial port upon instantiation and /// it then provides a single (overloaded, synchronous) request-response method called /// SendCommand(...). Due to this class often being used in association with optical /// synchronous interfaces, echo/crosstalk detection and filtering is build into the class /// for compensation purposes. /// /// </summary> public class SerialMeterConnection: IMeterConnection { private ILoggingBridge logger = new NoOpLoggingBridge(); protected SerialPort port = new SerialPort(); public const byte CR = 0x0A; public const byte LF = 0x0D; int lineNo = 0; public SerialMeterConnection () { CrosstalkCompensationEnabled = false; DtrEnable = false; RtsEnable = true; /* ReadTimeout = 700; WriteTimeout = 500; NewLine = Encoding.ASCII.GetString(new byte[]{LF}); */ /* logger.info( "Instantiated SerialMeterConnection with parameters {0}{1}{2}@{3}", DataBits, StopBits, Handshake, BaudRate); */ } /* public SerialMeterConnection (string portName) : this(portName, new NoOpLoggingBridge()) { } // The name of the serial port is the only mandatory setting public SerialMeterConnection (string portName, ILoggingBridge logger) { port = new SerialPort(); PortName = portName; CrosstalkCompensationEnabled = false; BaudRate = 300; Parity = Parity.Even; DataBits = 7; StopBits = StopBits.One; Handshake = Handshake.None; Encoding = new ASCIIEncoding(); DtrEnable = false; RtsEnable = true; ReadTimeout = 700; WriteTimeout = 500; NewLine = Encoding.ASCII.GetString(new byte[]{LF}); this.logger = logger; } */ /// <summary> /// Gets or sets a value indicating whether this <see cref="com.bangbits.metering.connection.SerialMeterConnection"/> has crosstalk /// compensation enabled. Crosstalk compensation can be used if you, during synchronous operation, receive feedback from /// your own transmission. Ideally you should reduce the sensetivity of the receiver and/or the transmission output, but /// it can also be handled by software, with a little overhead. /// </summary> /// <value> /// <c>true</c> if crosstalk compensation is enabled; otherwise, <c>false</c>. /// </value> public bool CrosstalkCompensationEnabled { get; set; } public int LineNo { get { return lineNo; } } // SerialPort delegation public string PortName { get { return port.PortName; } set { port.PortName = value; } } public int BaudRate { get { return port.BaudRate; } set { port.BaudRate = value; } } public Parity Parity { get { return port.Parity; } set { port.Parity = value; } } public int DataBits { get { return port.DataBits; } set { port.DataBits = value; } } public StopBits StopBits { get { return port.StopBits; } set { port.StopBits = value; } } public Handshake Handshake { get { return port.Handshake; } set { port.Handshake = value; } } public Encoding Encoding { get { return port.Encoding; } set { port.Encoding = value; } } public bool DtrEnable { get { return port.DtrEnable; } set { port.DtrEnable = value; } } public bool RtsEnable { get { return port.RtsEnable; } set { port.RtsEnable = value; } } public int ReadTimeout { get { return port.ReadTimeout; } set { port.ReadTimeout = value; } } public int WriteTimeout { get { return port.WriteTimeout; } set { port.WriteTimeout = value; } } public string NewLine { get { return port.NewLine; } set { port.NewLine = value; } } public ILoggingBridge Logger { get { return this.logger; } set { this.logger = value; } } public int ReadByte() { return port.ReadByte(); } public string ReadLine() { lineNo++; return port.ReadLine(); } public void Dispose() { Close(); } public void Close() { if(IsOpen) { port.Close(); } } public bool IsOpen { get { return (port != null && port.IsOpen ); } } private void AssertPortOpenness () { if (!port.IsOpen) { try { port.Open (); logger.info( "Opened SerialMeterConnection with parameters {0}{1}{2}@{3}", DataBits, StopBits, Handshake, BaudRate); } catch (System.IO.IOException exception) { throw new MeterException("Permission denied. Check permissions for " + PortName + ", fix with 'usermod -a -G dialout <USER_NAME>'"); } System.Threading.Thread.Sleep (100); if (!port.IsOpen) { throw new MeterException("Failed opening port " + PortName ); } } } public byte[] SendCommand(byte[] request) { WriteLine(request); byte[] response = ReadLineAsBinary(); // Are we dealing with echo/crosstalk if(CrosstalkCompensationEnabled && response.ContentEquals(request)) { // Ignore previous response and fetch new one response = ReadLineAsBinary(); logger.warn("Echo/crosstalk detected! Software compensation is being utilized, but for" + "optimal performance, try lowering receiver sensitivity and/or transmitter output power."); } return response; } protected byte[] ReadLineAsBinary() { byte[] response = Encoding.ASCII.GetBytes(ReadLine()); LogInput(response); return response; } protected void WriteLine(byte[] request) { AssertPortOpenness(); LogOutput(request); port.Write(request, 0, request.Length); port.WriteLine(""); } protected void LogInput(byte[] response) { Log("-> ", response); } protected void LogOutput(byte[] request) { Log("<- ", request); } protected virtual void Log(string text, byte[] data) { foreach(byte b in data) { text += " " + b.ToHex(); } logger.info( text + "\t" + Encoding.ASCII.GetString(data)); } } }
// 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.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor; using Microsoft.CodeAnalysis.GenerateType; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.GenerateType { [ExportLanguageService(typeof(IGenerateTypeService), LanguageNames.CSharp), Shared] internal class CSharpGenerateTypeService : AbstractGenerateTypeService<CSharpGenerateTypeService, SimpleNameSyntax, ObjectCreationExpressionSyntax, ExpressionSyntax, TypeDeclarationSyntax, ArgumentSyntax> { private static readonly SyntaxAnnotation s_annotation = new SyntaxAnnotation(); protected override string DefaultFileExtension { get { return ".cs"; } } protected override ExpressionSyntax GetLeftSideOfDot(SimpleNameSyntax simpleName) { return simpleName.GetLeftSideOfDot(); } protected override bool IsInCatchDeclaration(ExpressionSyntax expression) { return expression.IsParentKind(SyntaxKind.CatchDeclaration); } protected override bool IsArrayElementType(ExpressionSyntax expression) { return expression.IsParentKind(SyntaxKind.ArrayType) && expression.Parent.IsParentKind(SyntaxKind.ArrayCreationExpression); } protected override bool IsInValueTypeConstraintContext( SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken) { if (expression is TypeSyntax && expression.IsParentKind(SyntaxKind.TypeArgumentList)) { var typeArgumentList = (TypeArgumentListSyntax)expression.Parent; var symbolInfo = semanticModel.GetSymbolInfo(typeArgumentList.Parent, cancellationToken); var symbol = symbolInfo.GetAnySymbol(); if (symbol.IsConstructor()) { symbol = symbol.ContainingType; } var parameterIndex = typeArgumentList.Arguments.IndexOf((TypeSyntax)expression); var type = symbol as INamedTypeSymbol; if (type != null) { type = type.OriginalDefinition; var typeParameter = parameterIndex < type.TypeParameters.Length ? type.TypeParameters[parameterIndex] : null; return typeParameter != null && typeParameter.HasValueTypeConstraint; } var method = symbol as IMethodSymbol; if (method != null) { method = method.OriginalDefinition; var typeParameter = parameterIndex < method.TypeParameters.Length ? method.TypeParameters[parameterIndex] : null; return typeParameter != null && typeParameter.HasValueTypeConstraint; } } return false; } protected override bool IsInInterfaceList(ExpressionSyntax expression) { if (expression is TypeSyntax && expression.Parent is BaseTypeSyntax && expression.Parent.IsParentKind(SyntaxKind.BaseList) && ((BaseTypeSyntax)expression.Parent).Type == expression) { var baseList = (BaseListSyntax)expression.Parent.Parent; // If it's after the first item, then it's definitely an interface. if (baseList.Types[0] != expression.Parent) { return true; } // If it's in the base list of an interface or struct, then it's definitely an // interface. return baseList.IsParentKind(SyntaxKind.InterfaceDeclaration) || baseList.IsParentKind(SyntaxKind.StructDeclaration); } if (expression is TypeSyntax && expression.IsParentKind(SyntaxKind.TypeConstraint) && expression.Parent.IsParentKind(SyntaxKind.TypeParameterConstraintClause)) { var typeConstraint = (TypeConstraintSyntax)expression.Parent; var constraintClause = (TypeParameterConstraintClauseSyntax)typeConstraint.Parent; var index = constraintClause.Constraints.IndexOf(typeConstraint); // If it's after the first item, then it's definitely an interface. return index > 0; } return false; } protected override bool TryGetNameParts(ExpressionSyntax expression, out IList<string> nameParts) { nameParts = new List<string>(); return expression.TryGetNameParts(out nameParts); } protected override bool TryInitializeState( SemanticDocument document, SimpleNameSyntax simpleName, CancellationToken cancellationToken, out GenerateTypeServiceStateOptions generateTypeServiceStateOptions) { generateTypeServiceStateOptions = new GenerateTypeServiceStateOptions(); if (simpleName.IsVar) { return false; } if (SyntaxFacts.IsAliasQualifier(simpleName)) { return false; } // Never offer if we're in a using directive, unless its a static using. The feeling here is that it's highly // unlikely that this would be a location where a user would be wanting to generate // something. They're really just trying to reference something that exists but // isn't available for some reason (i.e. a missing reference). var usingDirectiveSyntax = simpleName.GetAncestorOrThis<UsingDirectiveSyntax>(); if (usingDirectiveSyntax != null && usingDirectiveSyntax.StaticKeyword.Kind() != SyntaxKind.StaticKeyword) { return false; } ExpressionSyntax nameOrMemberAccessExpression = null; if (simpleName.IsRightSideOfDot()) { // This simplename comes from the cref if (simpleName.IsParentKind(SyntaxKind.NameMemberCref)) { return false; } nameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression = (ExpressionSyntax)simpleName.Parent; // If we're on the right side of a dot, then the left side better be a name (and // not an arbitrary expression). var leftSideExpression = simpleName.GetLeftSideOfDot(); if (!leftSideExpression.IsKind( SyntaxKind.QualifiedName, SyntaxKind.IdentifierName, SyntaxKind.AliasQualifiedName, SyntaxKind.GenericName, SyntaxKind.SimpleMemberAccessExpression)) { return false; } } else { nameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression = simpleName; } // BUG(5712): Don't offer generate type in an enum's base list. if (nameOrMemberAccessExpression.Parent is BaseTypeSyntax && nameOrMemberAccessExpression.Parent.IsParentKind(SyntaxKind.BaseList) && ((BaseTypeSyntax)nameOrMemberAccessExpression.Parent).Type == nameOrMemberAccessExpression && nameOrMemberAccessExpression.Parent.Parent.IsParentKind(SyntaxKind.EnumDeclaration)) { return false; } // If we can guarantee it's a type only context, great. Otherwise, we may not want to // provide this here. var semanticModel = document.SemanticModel; if (!SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression)) { // Don't offer Generate Type in an expression context *unless* we're on the left // side of a dot. In that case the user might be making a type that they're // accessing a static off of. var syntaxTree = semanticModel.SyntaxTree; var start = nameOrMemberAccessExpression.SpanStart; var tokenOnLeftOfStart = syntaxTree.FindTokenOnLeftOfPosition(start, cancellationToken); var isExpressionContext = syntaxTree.IsExpressionContext(start, tokenOnLeftOfStart, attributes: true, cancellationToken: cancellationToken, semanticModelOpt: semanticModel); var isStatementContext = syntaxTree.IsStatementContext(start, tokenOnLeftOfStart, cancellationToken); var isExpressionOrStatementContext = isExpressionContext || isStatementContext; // Delegate Type Creation is not allowed in Non Type Namespace Context generateTypeServiceStateOptions.IsDelegateAllowed = false; if (!isExpressionOrStatementContext) { return false; } if (!simpleName.IsLeftSideOfDot() && !simpleName.IsInsideNameOf()) { if (nameOrMemberAccessExpression == null || !nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || !simpleName.IsRightSideOfDot()) { return false; } var leftSymbol = semanticModel.GetSymbolInfo(((MemberAccessExpressionSyntax)nameOrMemberAccessExpression).Expression, cancellationToken).Symbol; var token = simpleName.GetLastToken().GetNextToken(); // We let only the Namespace to be left of the Dot if (leftSymbol == null || !leftSymbol.IsKind(SymbolKind.Namespace) || !token.IsKind(SyntaxKind.DotToken)) { return false; } else { generateTypeServiceStateOptions.IsMembersWithModule = true; generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = true; } } // Global Namespace if (!generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess && !SyntaxFacts.IsInNamespaceOrTypeContext(simpleName)) { var token = simpleName.GetLastToken().GetNextToken(); if (token.IsKind(SyntaxKind.DotToken) && simpleName.Parent == token.Parent) { generateTypeServiceStateOptions.IsMembersWithModule = true; generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = true; } } } var fieldDeclaration = simpleName.GetAncestor<FieldDeclarationSyntax>(); if (fieldDeclaration != null && fieldDeclaration.Parent is CompilationUnitSyntax && document.Document.SourceCodeKind == SourceCodeKind.Regular) { return false; } // Check to see if Module could be an option in the Type Generation in Cross Language Generation var nextToken = simpleName.GetLastToken().GetNextToken(); if (simpleName.IsLeftSideOfDot() || nextToken.IsKind(SyntaxKind.DotToken)) { if (simpleName.IsRightSideOfDot()) { var parent = simpleName.Parent as QualifiedNameSyntax; if (parent != null) { var leftSymbol = semanticModel.GetSymbolInfo(parent.Left, cancellationToken).Symbol; if (leftSymbol != null && leftSymbol.IsKind(SymbolKind.Namespace)) { generateTypeServiceStateOptions.IsMembersWithModule = true; } } } } if (SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression)) { if (nextToken.IsKind(SyntaxKind.DotToken)) { // In Namespace or Type Context we cannot have Interface, Enum, Delegate as part of the Left Expression of a QualifiedName generateTypeServiceStateOptions.IsDelegateAllowed = false; generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = true; generateTypeServiceStateOptions.IsMembersWithModule = true; } // case: class Foo<T> where T: MyType if (nameOrMemberAccessExpression.GetAncestors<TypeConstraintSyntax>().Any()) { generateTypeServiceStateOptions.IsClassInterfaceTypes = true; return true; } // Events if (nameOrMemberAccessExpression.GetAncestors<EventFieldDeclarationSyntax>().Any() || nameOrMemberAccessExpression.GetAncestors<EventDeclarationSyntax>().Any()) { // Case : event foo name11 // Only Delegate if (simpleName.Parent != null && !(simpleName.Parent is QualifiedNameSyntax)) { generateTypeServiceStateOptions.IsDelegateOnly = true; return true; } // Case : event SomeSymbol.foo name11 if (nameOrMemberAccessExpression is QualifiedNameSyntax) { // Only Namespace, Class, Struct and Module are allowed to contain Delegate // Case : event Something.Mytype.<Delegate> Identifier if (nextToken.IsKind(SyntaxKind.DotToken)) { if (nameOrMemberAccessExpression.Parent != null && nameOrMemberAccessExpression.Parent is QualifiedNameSyntax) { return true; } else { Contract.Fail("Cannot reach this point"); } } else { // Case : event Something.<Delegate> Identifier generateTypeServiceStateOptions.IsDelegateOnly = true; return true; } } } } else { // MemberAccessExpression if ((nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || (nameOrMemberAccessExpression.Parent != null && nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression))) && nameOrMemberAccessExpression.IsLeftSideOfDot()) { // Check to see if the expression is part of Invocation Expression ExpressionSyntax outerMostMemberAccessExpression = null; if (nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { outerMostMemberAccessExpression = nameOrMemberAccessExpression; } else { Debug.Assert(nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)); outerMostMemberAccessExpression = (ExpressionSyntax)nameOrMemberAccessExpression.Parent; } outerMostMemberAccessExpression = outerMostMemberAccessExpression.GetAncestorsOrThis<ExpressionSyntax>().SkipWhile((n) => n != null && n.IsKind(SyntaxKind.SimpleMemberAccessExpression)).FirstOrDefault(); if (outerMostMemberAccessExpression != null && outerMostMemberAccessExpression is InvocationExpressionSyntax) { generateTypeServiceStateOptions.IsEnumNotAllowed = true; } } } // Cases: // // 1 - Function Address // var s2 = new MyD2(foo); // // 2 - Delegate // MyD1 d = null; // var s1 = new MyD2(d); // // 3 - Action // Action action1 = null; // var s3 = new MyD2(action1); // // 4 - Func // Func<int> lambda = () => { return 0; }; // var s4 = new MyD3(lambda); if (nameOrMemberAccessExpression.Parent is ObjectCreationExpressionSyntax) { var objectCreationExpressionOpt = generateTypeServiceStateOptions.ObjectCreationExpressionOpt = (ObjectCreationExpressionSyntax)nameOrMemberAccessExpression.Parent; // Enum and Interface not Allowed in Object Creation Expression generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = true; if (objectCreationExpressionOpt.ArgumentList != null) { if (objectCreationExpressionOpt.ArgumentList.CloseParenToken.IsMissing) { return false; } // Get the Method symbol for the Delegate to be created if (generateTypeServiceStateOptions.IsDelegateAllowed && objectCreationExpressionOpt.ArgumentList.Arguments.Count == 1) { generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, objectCreationExpressionOpt.ArgumentList.Arguments[0].Expression, cancellationToken); } else { generateTypeServiceStateOptions.IsDelegateAllowed = false; } } if (objectCreationExpressionOpt.Initializer != null) { foreach (var expression in objectCreationExpressionOpt.Initializer.Expressions) { var simpleAssignmentExpression = expression as AssignmentExpressionSyntax; if (simpleAssignmentExpression == null) { continue; } var name = simpleAssignmentExpression.Left as SimpleNameSyntax; if (name == null) { continue; } generateTypeServiceStateOptions.PropertiesToGenerate.Add(name); } } } if (generateTypeServiceStateOptions.IsDelegateAllowed) { // MyD1 z1 = foo; if (nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.VariableDeclaration)) { var variableDeclaration = (VariableDeclarationSyntax)nameOrMemberAccessExpression.Parent; if (variableDeclaration.Variables.Count != 0) { var firstVarDeclWithInitializer = variableDeclaration.Variables.FirstOrDefault(var => var.Initializer != null && var.Initializer.Value != null); if (firstVarDeclWithInitializer != null && firstVarDeclWithInitializer.Initializer != null && firstVarDeclWithInitializer.Initializer.Value != null) { generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, firstVarDeclWithInitializer.Initializer.Value, cancellationToken); } } } // var w1 = (MyD1)foo; if (nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.CastExpression)) { var castExpression = (CastExpressionSyntax)nameOrMemberAccessExpression.Parent; if (castExpression.Expression != null) { generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, castExpression.Expression, cancellationToken); } } } return true; } private IMethodSymbol GetMethodSymbolIfPresent(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken) { if (expression == null) { return null; } var memberGroup = semanticModel.GetMemberGroup(expression, cancellationToken); if (memberGroup.Length != 0) { return memberGroup.ElementAt(0).IsKind(SymbolKind.Method) ? (IMethodSymbol)memberGroup.ElementAt(0) : null; } var expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type; if (expressionType.IsDelegateType()) { return ((INamedTypeSymbol)expressionType).DelegateInvokeMethod; } var expressionSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).Symbol; if (expressionSymbol.IsKind(SymbolKind.Method)) { return (IMethodSymbol)expressionSymbol; } return null; } private Accessibility DetermineAccessibilityConstraint( State state, SemanticModel semanticModel, CancellationToken cancellationToken) { return semanticModel.DetermineAccessibilityConstraint( state.NameOrMemberAccessExpression as TypeSyntax, cancellationToken); } protected override IList<ITypeParameterSymbol> GetTypeParameters( State state, SemanticModel semanticModel, CancellationToken cancellationToken) { if (state.SimpleName is GenericNameSyntax) { var genericName = (GenericNameSyntax)state.SimpleName; var typeArguments = state.SimpleName.Arity == genericName.TypeArgumentList.Arguments.Count ? genericName.TypeArgumentList.Arguments.OfType<SyntaxNode>().ToList() : Enumerable.Repeat<SyntaxNode>(null, state.SimpleName.Arity); return this.GetTypeParameters(state, semanticModel, typeArguments, cancellationToken); } return SpecializedCollections.EmptyList<ITypeParameterSymbol>(); } protected override bool TryGetArgumentList(ObjectCreationExpressionSyntax objectCreationExpression, out IList<ArgumentSyntax> argumentList) { if (objectCreationExpression != null && objectCreationExpression.ArgumentList != null) { argumentList = objectCreationExpression.ArgumentList.Arguments.ToList(); return true; } argumentList = null; return false; } protected override IList<string> GenerateParameterNames( SemanticModel semanticModel, IList<ArgumentSyntax> arguments) { return semanticModel.GenerateParameterNames(arguments); } public override string GetRootNamespace(CompilationOptions options) { return string.Empty; } protected override bool IsInVariableTypeContext(ExpressionSyntax expression) { return false; } protected override INamedTypeSymbol DetermineTypeToGenerateIn(SemanticModel semanticModel, SimpleNameSyntax simpleName, CancellationToken cancellationToken) { return semanticModel.GetEnclosingNamedType(simpleName.SpanStart, cancellationToken); } protected override Accessibility GetAccessibility(State state, SemanticModel semanticModel, bool intoNamespace, CancellationToken cancellationToken) { var accessibility = DetermineDefaultAccessibility(state, semanticModel, intoNamespace, cancellationToken); if (!state.IsTypeGeneratedIntoNamespaceFromMemberAccess) { var accessibilityConstraint = DetermineAccessibilityConstraint(state, semanticModel, cancellationToken); if (accessibilityConstraint == Accessibility.Public || accessibilityConstraint == Accessibility.Internal) { accessibility = accessibilityConstraint; } } return accessibility; } protected override ITypeSymbol DetermineArgumentType(SemanticModel semanticModel, ArgumentSyntax argument, CancellationToken cancellationToken) { return argument.DetermineParameterType(semanticModel, cancellationToken); } protected override bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType) { return compilation.ClassifyConversion(sourceType, targetType).IsImplicit; } public override async Task<Tuple<INamespaceSymbol, INamespaceOrTypeSymbol, Location>> GetOrGenerateEnclosingNamespaceSymbol(INamedTypeSymbol namedTypeSymbol, string[] containers, Document selectedDocument, SyntaxNode selectedDocumentRoot, CancellationToken cancellationToken) { var compilationUnit = (CompilationUnitSyntax)selectedDocumentRoot; var semanticModel = await selectedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); if (containers.Length != 0) { // Search the NS declaration in the root var containerList = new List<string>(containers); var enclosingNamespace = GetDeclaringNamespace(containerList, 0, compilationUnit); if (enclosingNamespace != null) { var enclosingNamespaceSymbol = semanticModel.GetSymbolInfo(enclosingNamespace.Name, cancellationToken); if (enclosingNamespaceSymbol.Symbol != null) { return Tuple.Create((INamespaceSymbol)enclosingNamespaceSymbol.Symbol, (INamespaceOrTypeSymbol)namedTypeSymbol, enclosingNamespace.CloseBraceToken.GetLocation()); } } } var globalNamespace = semanticModel.GetEnclosingNamespace(0, cancellationToken); var rootNamespaceOrType = namedTypeSymbol.GenerateRootNamespaceOrType(containers); var lastMember = compilationUnit.Members.LastOrDefault(); Location afterThisLocation = null; if (lastMember != null) { afterThisLocation = semanticModel.SyntaxTree.GetLocation(new TextSpan(lastMember.Span.End, 0)); } else { afterThisLocation = semanticModel.SyntaxTree.GetLocation(new TextSpan()); } return Tuple.Create(globalNamespace, rootNamespaceOrType, afterThisLocation); } private NamespaceDeclarationSyntax GetDeclaringNamespace(List<string> containers, int indexDone, CompilationUnitSyntax compilationUnit) { foreach (var member in compilationUnit.Members) { var namespaceDeclaration = GetDeclaringNamespace(containers, 0, member); if (namespaceDeclaration != null) { return namespaceDeclaration; } } return null; } private NamespaceDeclarationSyntax GetDeclaringNamespace(List<string> containers, int indexDone, SyntaxNode localRoot) { var namespaceDecl = localRoot as NamespaceDeclarationSyntax; if (namespaceDecl == null || namespaceDecl.Name is AliasQualifiedNameSyntax) { return null; } List<string> namespaceContainers = new List<string>(); GetNamespaceContainers(namespaceDecl.Name, namespaceContainers); if (namespaceContainers.Count + indexDone > containers.Count || !IdentifierMatches(indexDone, namespaceContainers, containers)) { return null; } indexDone = indexDone + namespaceContainers.Count; if (indexDone == containers.Count) { return namespaceDecl; } foreach (var member in namespaceDecl.Members) { var resultant = GetDeclaringNamespace(containers, indexDone, member); if (resultant != null) { return resultant; } } return null; } private bool IdentifierMatches(int indexDone, List<string> namespaceContainers, List<string> containers) { for (int i = 0; i < namespaceContainers.Count; ++i) { if (namespaceContainers[i] != containers[indexDone + i]) { return false; } } return true; } private void GetNamespaceContainers(NameSyntax name, List<string> namespaceContainers) { if (name is QualifiedNameSyntax) { GetNamespaceContainers(((QualifiedNameSyntax)name).Left, namespaceContainers); namespaceContainers.Add(((QualifiedNameSyntax)name).Right.Identifier.ValueText); } else { Debug.Assert(name is SimpleNameSyntax); namespaceContainers.Add(((SimpleNameSyntax)name).Identifier.ValueText); } } internal override bool TryGetBaseList(ExpressionSyntax expression, out TypeKindOptions typeKindValue) { typeKindValue = TypeKindOptions.AllOptions; if (expression == null) { return false; } var node = expression as SyntaxNode; while (node != null) { if (node is BaseListSyntax) { if (node.Parent != null && (node.Parent is InterfaceDeclarationSyntax || node.Parent is StructDeclarationSyntax)) { typeKindValue = TypeKindOptions.Interface; return true; } typeKindValue = TypeKindOptions.BaseList; return true; } node = node.Parent; } return false; } internal override bool IsPublicOnlyAccessibility(ExpressionSyntax expression, Project project) { if (expression == null) { return false; } if (GeneratedTypesMustBePublic(project)) { return true; } var node = expression as SyntaxNode; SyntaxNode previousNode = null; while (node != null) { // Types in BaseList, Type Constraint or Member Types cannot be of restricter accessibility than the declaring type if ((node is BaseListSyntax || node is TypeParameterConstraintClauseSyntax) && node.Parent != null && node.Parent is TypeDeclarationSyntax) { var typeDecl = node.Parent as TypeDeclarationSyntax; if (typeDecl != null) { if (typeDecl.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword)) { return IsAllContainingTypeDeclsPublic(typeDecl); } else { // The Type Decl which contains the BaseList does not contain Public return false; } } Contract.Fail("Cannot reach this point"); } if ((node is EventDeclarationSyntax || node is EventFieldDeclarationSyntax) && node.Parent != null && node.Parent is TypeDeclarationSyntax) { // Make sure the GFU is not inside the Accessors if (previousNode != null && previousNode is AccessorListSyntax) { return false; } // Make sure that Event Declaration themselves are Public in the first place if (!node.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword)) { return false; } return IsAllContainingTypeDeclsPublic(node); } previousNode = node; node = node.Parent; } return false; } private bool IsAllContainingTypeDeclsPublic(SyntaxNode node) { // Make sure that all the containing Type Declarations are also Public var containingTypeDeclarations = node.GetAncestors<TypeDeclarationSyntax>(); if (containingTypeDeclarations.Count() == 0) { return true; } else { return containingTypeDeclarations.All(typedecl => typedecl.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword)); } } internal override bool IsGenericName(SimpleNameSyntax simpleName) { if (simpleName == null) { return false; } var genericName = simpleName as GenericNameSyntax; return genericName != null; } internal override bool IsSimpleName(ExpressionSyntax expression) { return expression is SimpleNameSyntax; } internal override Solution TryAddUsingsOrImportToDocument(Solution updatedSolution, SyntaxNode modifiedRoot, Document document, SimpleNameSyntax simpleName, string includeUsingsOrImports, CancellationToken cancellationToken) { // Nothing to include if (string.IsNullOrWhiteSpace(includeUsingsOrImports)) { return updatedSolution; } var placeSystemNamespaceFirst = document.Project.Solution.Workspace.Options.GetOption(OrganizerOptions.PlaceSystemNamespaceFirst, document.Project.Language); SyntaxNode root = null; if (modifiedRoot == null) { root = document.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken); } else { root = modifiedRoot; } if (root is CompilationUnitSyntax) { var compilationRoot = (CompilationUnitSyntax)root; var usingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(includeUsingsOrImports)); // Check if the usings is already present if (compilationRoot.Usings.Where(n => n != null && n.Alias == null) .Select(n => n.Name.ToString()) .Any(n => n.Equals(includeUsingsOrImports))) { return updatedSolution; } // Check if the GFU is triggered from the namespace same as the usings namespace if (IsWithinTheImportingNamespace(document, simpleName.SpanStart, includeUsingsOrImports, cancellationToken)) { return updatedSolution; } var addedCompilationRoot = compilationRoot.AddUsingDirectives(new[] { usingDirective }, placeSystemNamespaceFirst, Formatter.Annotation); updatedSolution = updatedSolution.WithDocumentSyntaxRoot(document.Id, addedCompilationRoot, PreservationMode.PreserveIdentity); } return updatedSolution; } private ITypeSymbol GetPropertyType( SimpleNameSyntax property, SemanticModel semanticModel, ITypeInferenceService typeInference, CancellationToken cancellationToken) { var parent = property.Parent as AssignmentExpressionSyntax; if (parent != null) { return typeInference.InferType(semanticModel, parent.Left, true, cancellationToken); } return null; } private IPropertySymbol CreatePropertySymbol(SimpleNameSyntax propertyName, ITypeSymbol propertyType) { return CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: SpecializedCollections.EmptyList<AttributeData>(), accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(), explicitInterfaceSymbol: null, name: propertyName.ToString(), type: propertyType, parameters: null, getMethod: s_accessor, setMethod: s_accessor, isIndexer: false); } private static readonly IMethodSymbol s_accessor = CodeGenerationSymbolFactory.CreateAccessorSymbol( attributes: null, accessibility: Accessibility.Public, statements: null); internal override bool TryGenerateProperty( SimpleNameSyntax propertyName, SemanticModel semanticModel, ITypeInferenceService typeInference, CancellationToken cancellationToken, out IPropertySymbol property) { property = null; var propertyType = GetPropertyType(propertyName, semanticModel, typeInference, cancellationToken); if (propertyType == null || propertyType is IErrorTypeSymbol) { property = CreatePropertySymbol(propertyName, semanticModel.Compilation.ObjectType); return true; } property = CreatePropertySymbol(propertyName, propertyType); return true; } internal override IMethodSymbol GetDelegatingConstructor( SemanticDocument document, ObjectCreationExpressionSyntax objectCreation, INamedTypeSymbol namedType, ISet<IMethodSymbol> candidates, CancellationToken cancellationToken) { var model = document.SemanticModel; var oldNode = objectCreation .AncestorsAndSelf(ascendOutOfTrivia: false) .Where(node => SpeculationAnalyzer.CanSpeculateOnNode(node)) .LastOrDefault(); var typeNameToReplace = objectCreation.Type; var newTypeName = namedType.GenerateTypeSyntax(); var newObjectCreation = objectCreation.WithType(newTypeName).WithAdditionalAnnotations(s_annotation); var newNode = oldNode.ReplaceNode(objectCreation, newObjectCreation); var speculativeModel = SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(oldNode, newNode, model); if (speculativeModel != null) { newObjectCreation = (ObjectCreationExpressionSyntax)newNode.GetAnnotatedNodes(s_annotation).Single(); var symbolInfo = speculativeModel.GetSymbolInfo(newObjectCreation, cancellationToken); var parameterTypes = newObjectCreation.ArgumentList.Arguments.Select( a => speculativeModel.GetTypeInfo(a.Expression, cancellationToken).ConvertedType).ToList(); return GenerateConstructorHelpers.GetDelegatingConstructor( document, symbolInfo, candidates, namedType, parameterTypes); } return null; } } }
namespace TypeVisualiser.ILAnalyser { using System; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Reflection.Emit; using TypeVisualiser.Properties; internal class MethodBodyReader : IMethodBodyReader { static MethodBodyReader() { GlobalIntermediateLanguageConstants.LoadOpCodes(); } private readonly Collection<ILInstruction> instructions = new Collection<ILInstruction>(); private byte[] il; private MethodBase mi; /// <summary> /// Gets the collection of IL instructions. /// </summary> /// <value>The instructions.</value> public IQueryable<ILInstruction> Instructions { get { return this.instructions.AsQueryable(); } } public void Read(MethodBase method) { if (method == null) { throw new ArgumentNullResourceException("method", Resources.General_Given_Parameter_Cannot_Be_Null); } this.mi = method; MethodBody body = this.mi.GetMethodBody(); if (body != null) { this.il = body.GetILAsByteArray(); ConstructInstructions(this.mi.Module); } } ///// <summary> ///// Gets the IL code of the method ///// </summary> ///// <returns></returns> // public string GetBodyCode() // { // string result = ""; // if (this.Instructions != null) // { // for (int i = 0; i < this.Instructions.Count; i++) // { // result += this.Instructions[i].GetCode() + "\n"; // } // } // return result; // } // public object GetRefferencedOperand(Module module, int metadataToken) // { // AssemblyName[] assemblyNames = module.Assembly.GetReferencedAssemblies(); // for (int i = 0; i < assemblyNames.Length; i++) // { // Module[] modules = Assembly.Load(assemblyNames[i]).GetModules(); // for (int j = 0; j < modules.Length; j++) // { // try // { // Type t = modules[j].ResolveType(metadataToken); // return t; // } catch // { // } // } // } // return null; // //System.Reflection.Assembly.Load(module.Assembly.GetReferencedAssemblies()[3]).GetModules()[0].ResolveType(metadataToken) // } /// <summary> /// Constructs the array of ILInstructions according to the IL byte code. /// </summary> /// <param name="module"> /// </param> [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Third party code needs to be as compatible as possible to allow upgrading")] [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "For simple analysis purposes, this is not an app critical function")] private void ConstructInstructions(Module module) { byte[] localIlbytes = this.il; int position = 0; while (position < localIlbytes.Length) { var instruction = new ILInstruction(); // get the operation code of the current instruction OpCode code; ushort value = localIlbytes[position++]; if (GlobalIntermediateLanguageConstants.SingleByteOpCodes.Count == 0) { throw new InvalidOperationException( "Attempt to use Method Body Reader before Global Intermediate Language Constants has been initialised. Global Intermediate Language Constants. Load Op Codes must be called once."); } if (value != 0xfe) { code = GlobalIntermediateLanguageConstants.SingleByteOpCodes[value]; } else { value = localIlbytes[position++]; code = GlobalIntermediateLanguageConstants.MultiByteOpCodes[value]; } instruction.Code = code; instruction.Offset = position - 1; int metadataToken; // get the operand of the current operation switch (code.OperandType) { case OperandType.InlineBrTarget: metadataToken = ReadInt32(ref position); metadataToken += position; instruction.Operand = metadataToken; break; case OperandType.InlineField: // TODO All these try catch blocks need to go try { metadataToken = ReadInt32(ref position); instruction.Operand = module.ResolveField(metadataToken); } catch { instruction.Operand = new object(); } break; case OperandType.InlineMethod: metadataToken = ReadInt32(ref position); try { instruction.Operand = module.ResolveMethod(metadataToken); } catch { instruction.Operand = new object(); } break; case OperandType.InlineSig: metadataToken = ReadInt32(ref position); instruction.Operand = module.ResolveSignature(metadataToken); break; case OperandType.InlineTok: metadataToken = ReadInt32(ref position); try { instruction.Operand = module.ResolveType(metadataToken); } catch { } // TODO : see what to do here break; case OperandType.InlineType: metadataToken = ReadInt32(ref position); // now we call the ResolveType always using the generic attributes type in order // to support decompilation of generic methods and classes // thanks to the guys from code project who commented on this missing feature Type[] declaringTypeGenericArgs = this.mi.DeclaringType.GetGenericArguments(); Type[] genericArgs = null; if (this.mi.IsGenericMethod) { genericArgs = this.mi.GetGenericArguments(); } instruction.Operand = module.ResolveType(metadataToken, declaringTypeGenericArgs, genericArgs); break; case OperandType.InlineI: { instruction.Operand = ReadInt32(ref position); break; } case OperandType.InlineI8: { instruction.Operand = ReadInt64(ref position); break; } case OperandType.InlineNone: { instruction.Operand = null; break; } case OperandType.InlineR: { instruction.Operand = ReadDouble(ref position); break; } case OperandType.InlineString: { metadataToken = ReadInt32(ref position); instruction.Operand = module.ResolveString(metadataToken); break; } case OperandType.InlineSwitch: { int count = ReadInt32(ref position); var casesAddresses = new int[count]; for (int i = 0; i < count; i++) { casesAddresses[i] = ReadInt32(ref position); } var cases = new int[count]; for (int i = 0; i < count; i++) { cases[i] = position + casesAddresses[i]; } break; } case OperandType.InlineVar: { instruction.Operand = ReadUInt16(ref position); break; } case OperandType.ShortInlineBrTarget: { instruction.Operand = ReadSByte(ref position) + position; break; } case OperandType.ShortInlineI: { instruction.Operand = ReadSByte(ref position); break; } case OperandType.ShortInlineR: { instruction.Operand = ReadSingle(ref position); break; } case OperandType.ShortInlineVar: { instruction.Operand = ReadByte(ref position); break; } default: { throw new NotSupportedException("Unknown operand type."); } } this.instructions.Add(instruction); } } private byte ReadByte(ref int position) { return this.il[position++]; } private double ReadDouble(ref int position) { return ((this.il[position++] | (this.il[position++] << 8)) | (this.il[position++] << 0x10)) | (this.il[position++] << 0x18) | (this.il[position++] << 0x20) | (this.il[position++] << 0x28) | (this.il[position++] << 0x30) | (this.il[position++] << 0x38); } //// private int ReadInt16(byte[] _il, ref int position) //// { //// return ((this.il[position++] | (this.il[position++] << 8))); //// } private int ReadInt32(ref int position) { return ((this.il[position++] | (this.il[position++] << 8)) | (this.il[position++] << 0x10)) | (this.il[position++] << 0x18); } private ulong ReadInt64(ref int position) { return (ulong) (((this.il[position++] | (this.il[position++] << 8)) | (this.il[position++] << 0x10)) | (this.il[position++] << 0x18) | (this.il[position++] << 0x20) | (this.il[position++] << 0x28) | (this.il[position++] << 0x30) | (this.il[position++] << 0x38)); } private sbyte ReadSByte(ref int position) { return (sbyte)this.il[position++]; } private float ReadSingle(ref int position) { return ((this.il[position++] | (this.il[position++] << 8)) | (this.il[position++] << 0x10)) | (this.il[position++] << 0x18); } private ushort ReadUInt16(ref int position) { return (ushort)(this.il[position++] | (this.il[position++] << 8)); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.Globalization; using System.IO; using System.Threading; using System.Windows.Forms; using System.Xml.Serialization; using CslaGenerator.Controls; using CslaGenerator.Data; using CslaGenerator.Metadata; using CslaGenerator.Util; using CslaGenerator.Util.PropertyBags; using DBSchemaInfo.Base; namespace CslaGenerator { public class GeneratorController : IDisposable { #region Main (application entry point) /// <summary> /// The main entry point for the application. /// </summary> /// <param name="args"> /// Command line arguments. First arg can be a filename to load. /// </param> [STAThread] private static void Main(string[] args) { Thread.CurrentThread.CurrentUICulture = new CultureInfo("en"); var controller = new GeneratorController(); controller.MainForm.Closing += controller.GeneratorFormClosing; controller.CommandLineArgs = args; // process the command line args here so we have a UI, also, we can not process in Init without // modifying more code to take args[] controller.ProcessCommandLineArgs(); Application.Run(); } #endregion #region Private Fields private string[] _commandlineArgs; private CslaGeneratorUnit _currentUnit; private AssociativeEntity _currentAssociativeEntitiy; private GlobalParameters _globalParameters = new GlobalParameters(); private string _currentFilePath = string.Empty; private MainForm _mainForm; private static ICatalog _catalog; private static GeneratorController _current; private readonly PropertyContext _propertyContext = new PropertyContext(); private bool _confirmReplacementRememberAnswer; private bool _confirmReplacementDialogResult; private bool _reportReplacementCounterRememberAnswer; internal bool IsDBConnected; internal bool IsLoading; internal bool HasErrors = false; internal bool HasWarnings = false; internal Stopwatch LoadingTimer = new Stopwatch(); internal int Tables; internal int Views; internal int Sprocs; #endregion #region Constructors/Dispose internal GeneratorController() { _current = this; Init(); GetConfig(); } private void Init() { _mainForm = new MainForm(this); _mainForm.ProjectPanel.SelectedItemsChanged += CslaObjectList_SelectedItemsChanged; _mainForm.ProjectPanel.LastItemRemoved += delegate { CurrentCslaObject = null; }; _mainForm.ObjectRelationsBuilderPanel.SelectedItemsChanged += AssociativeEntitiesList_SelectedItemsChanged; _mainForm.Show(); _mainForm.formSizePosition.RestoreFormSizePosition(); } protected virtual void Dispose(bool disposing) { if (disposing) { // dispose managed resources if (_mainForm != null) { _mainForm.Dispose(); _mainForm = null; } } // free native resources } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Processes command line args passed to CSLA Gen. Called after the generator is created. /// </summary> private void ProcessCommandLineArgs() { if (CommandLineArgs.Length > 0) { string filename = CommandLineArgs[0]; if (File.Exists(filename)) { // request that the UI load the project, since it keeps track // of *additional* state (isNew) that this class is unaware of. _mainForm.OpenProjectFile(filename); } } } #endregion #region internal Properties internal CslaGeneratorUnit CurrentUnit { get { return _currentUnit; } private set { _mainForm.WebBrowserDockPanel.Show(); _mainForm.GlobalSettingsPanel.LoadInfo(); _mainForm.ActivateShowGlobalSettings(); _mainForm.ObjectRelationsBuilderPanel.Show(_mainForm.DockPanel); _currentUnit = value; if (_mainForm.ProjectPropertiesPanel == null) _mainForm.ProjectPropertiesPanel = new ProjectProperties(); _mainForm.ProjectPropertiesPanel.LoadInfo(); _mainForm.ActivateShowProjectProperties(); } } internal CslaObjectInfo CurrentCslaObject { get; set; } internal GlobalParameters GlobalParameters { get { return _globalParameters; } set { if (value != null) _globalParameters = value; } } internal CslaGeneratorUnitLayout CurrentUnitLayout { get; set; } internal string TemplatesDirectory { get; set; } internal string ProjectsDirectory { get; set; } internal string ObjectsDirectory { get; set; } internal string RulesDirectory { get; set; } internal List<string> MruItems { get; set; } internal string[] CommandLineArgs { get { return _commandlineArgs; } set { _commandlineArgs = value; } } internal ProjectProperties CurrentProjectProperties { get { return _mainForm.ProjectPropertiesPanel; } } internal MainForm MainForm { get { return _mainForm; } set { _mainForm = value; } } internal string CurrentFilePath { get { return _currentFilePath; } set { _currentFilePath = value; } } internal static ICatalog Catalog { get { return _catalog; } set { _catalog = value; } } internal static GeneratorController Current { get { return _current; } } #endregion #region internal Methods internal void Connect() { DialogResult result; using (var frmConn = new ConnectionForm()) { result = frmConn.ShowDialog(); } if (result == DialogResult.OK) { Cursor.Current = Cursors.WaitCursor; BuildSchemaTree(ConnectionFactory.ConnectionString); Cursor.Current = Cursors.Default; IsDBConnected = true; } } internal void Load(string filePath) { bool forceSave = false; IsLoading = true; LoadingTimer.Restart(); FileStream fs = null; try { Cursor.Current = Cursors.WaitCursor; var deserialized = false; var converted = false; while (!deserialized) { try { fs = File.Open(filePath, FileMode.Open); var xml = new XmlSerializer(typeof(CslaGeneratorUnit)); CurrentUnit = (CslaGeneratorUnit) xml.Deserialize(fs); if (VersionHelper.CurrentFileVersion != CurrentUnit.FileVersion) { if (fs != null) { fs.Close(); fs.Dispose(); } forceSave = VersionHelper.SolveVersionNumberIssues(filePath, null); converted = true; NewCslaUnit(); } else { deserialized = true; } } catch (InvalidOperationException exception) { if (fs != null) { fs.Close(); fs.Dispose(); } if (exception.InnerException == null || converted) throw; forceSave = VersionHelper.SolveVersionNumberIssues(filePath, exception); if (FixXmlSchemaErrors(filePath, exception)) { converted = true; NewCslaUnit(); } else { throw; } } } if (fs != null) { fs.Close(); fs.Dispose(); } if (forceSave) Save(filePath); CurrentUnit.FileVersion = VersionHelper.CurrentFileVersion; _currentUnit.ResetParent(); CurrentCslaObject = null; _currentAssociativeEntitiy = null; _currentFilePath = GetFilePath(filePath); ConnectionFactory.ConnectionString = _currentUnit.ConnectionString; // check if this is a valid connection, else let the user enter new connection info SqlConnection cn = null; try { cn = ConnectionFactory.NewConnection; cn.Open(); BuildSchemaTree(_currentUnit.ConnectionString); IsDBConnected = true; } catch //(SqlException e) { // call connect function which will allow user to enter new info Connect(); } finally { if (cn != null && cn.State == ConnectionState.Open) { cn.Close(); } if (cn != null) { cn.Dispose(); } } BindControls(); _currentUnit.CslaObjects.ListChanged += CslaObjects_ListChanged; if (_currentUnit.CslaObjects.Count > 0) { if (_mainForm.ProjectPanel.ListObjects.Items.Count > 0) { CurrentCslaObject = (CslaObjectInfo) _mainForm.ProjectPanel.ListObjects.Items[0]; } else { CurrentCslaObject = null; } if (_mainForm.DbSchemaPanel != null) _mainForm.DbSchemaPanel.CurrentCslaObject = CurrentCslaObject; } else { CurrentCslaObject = null; if (_mainForm.DbSchemaPanel != null) _mainForm.DbSchemaPanel.CurrentCslaObject = null; } _mainForm.ProjectPanel.ApplyFiltersPresenter(); _currentUnit.AssociativeEntities.ListChanged += AssociativeEntities_ListChanged; /*if (_currentUnit.AssociativeEntities.Count > 0) { _currentAssociativeEntitiy = _currentUnit.AssociativeEntities[0]; } else { _currentAssociativeEntitiy = null; _frmGenerator.ObjectRelationsBuilder.PropertyGrid1.SelectedObject = null; _frmGenerator.ObjectRelationsBuilder.PropertyGrid2.SelectedObject = null; _frmGenerator.ObjectRelationsBuilder.PropertyGrid3.SelectedObject = null; }*/ } catch (Exception e) { var message = filePath + Environment.NewLine + Environment.NewLine + e.Message; if (e.InnerException != null) message += Environment.NewLine + e.InnerException.Message; MessageBox.Show(_mainForm, message, "Loading File Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { Cursor.Current = Cursors.Default; if (fs != null) { fs.Close(); fs.Dispose(); } } LoadProjectLayout(filePath); CurrentCslaObject = (CslaObjectInfo) GetSelectedItem(); IsLoading = false; LoadingTimer.Stop(); } private bool FixXmlSchemaErrors(string filePath, Exception ex) { //ex.Message //"There is an error in XML document (114, 8)." //ex.InnerException.Message //"Instance validation error: 'Separator' is not a valid value for CslaObjectType." var point = ex.Message .Split(new[] {'(', ')'}, StringSplitOptions.RemoveEmptyEntries)[1] .Split(','); var line = Convert.ToInt32(point[0]); var position = Convert.ToInt32(point[1]); var originalItem = ex.InnerException.Message .Split(new[] {'\''}, StringSplitOptions.RemoveEmptyEntries)[1]; var ofendedType = ex.InnerException.Message. Split(new[] {@"for"}, StringSplitOptions.RemoveEmptyEntries)[1] .Trim() .Trim('.'); if (VersionHelper.FindEnum(filePath, originalItem) == 0) return true; using (var fixXmlSchema = new FixXmlSchema()) { fixXmlSchema.FilePath = filePath; fixXmlSchema.OfendingLine = line; fixXmlSchema.OfendingPosition = position; fixXmlSchema.OfendedType = ofendedType; fixXmlSchema.OriginalItem = originalItem; var dialogResult = fixXmlSchema.ShowDialog(); if (dialogResult == DialogResult.OK) { var replacementItem = fixXmlSchema.ReplacementItem; if (ConfirmReplacement(ofendedType, originalItem, replacementItem)) { var counter = VersionHelper.ReplaceEnum(filePath, originalItem, replacementItem); ReportReplacement(ofendedType, originalItem, replacementItem, counter); return true; } } } return false; } private bool ConfirmReplacement(string ofendedType, string originalItem, string replacementItem) { if (!_confirmReplacementRememberAnswer) { var msg = string.Format(@"Do you want to replace all occurences of '{0}' by '{1}' of '{2}' type?", originalItem, replacementItem, ofendedType); using (var messageBox = new MessageBoxEx(msg, @"Fixing project file", MessageBoxIcon.Question)) { messageBox.SetButtons(new[] {DialogResult.No, DialogResult.Yes}, 2); messageBox.SetCheckbox(@"Do not ask again if ""Yes""."); messageBox.ShowDialog(); _confirmReplacementDialogResult = messageBox.DialogResult == DialogResult.Yes; _confirmReplacementRememberAnswer = messageBox.CheckboxChecked && _confirmReplacementDialogResult; } } return _confirmReplacementDialogResult; } private void ReportReplacement(string ofendedType, string originalItem, string replacementItem, int counter) { if (!_reportReplacementCounterRememberAnswer) { var msg = string.Format(@"Replaced {0} occurences of '{1}' by '{2}' of '{3}' type.", counter, originalItem, replacementItem, ofendedType); using (var messageBox = new MessageBoxEx(msg, @"Fixing project file", MessageBoxIcon.Information)) { messageBox.SetButtons(new[] {DialogResult.OK}); messageBox.SetCheckbox("Do not show again."); messageBox.ShowDialog(); _reportReplacementCounterRememberAnswer = messageBox.CheckboxChecked; } } } internal void LoadProjectLayout(string filePath) { filePath = ExtractPathWithoutExtension(filePath) + ".Layout"; if (File.Exists(filePath)) { using (var fs = File.Open(filePath, FileMode.Open)) { var xml = new XmlSerializer(typeof(CslaGeneratorUnitLayout)); CurrentUnitLayout = (CslaGeneratorUnitLayout) xml.Deserialize(fs); } MainForm.SetProjectState(); } } private void CslaObjects_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemChanged) { if (e.PropertyDescriptor.Name == "ObjectType" && _mainForm.ProjectPanel.FilterTypeIsActive) ReloadPropertyGrid(); } } private void AssociativeEntities_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemChanged) { if (e.PropertyDescriptor.Name == "ObjectName" || e.PropertyDescriptor.Name == "RelationType") ReloadBuilderPropertyGrid(); } } internal void NewCslaUnit() { IsLoading = true; CurrentUnit = new CslaGeneratorUnit(); CurrentUnitLayout = new CslaGeneratorUnitLayout(); _currentFilePath = Path.GetTempPath() + @"\" + Guid.NewGuid(); CurrentCslaObject = null; _currentUnit.ConnectionString = ConnectionFactory.ConnectionString; BindControls(); _mainForm.ObjectInfoGrid.SelectedObject = null; IsLoading = false; } internal void Save(string filePath) { if (!_mainForm.ApplyProjectProperties()) return; CurrentUnit.FileVersion = VersionHelper.CurrentFileVersion; _mainForm.GlobalSettingsPanel.ForceSaveGlobalSettings(); FileStream fs = null; var tempFile = Path.GetTempPath() + Guid.NewGuid() + ".cslagenerator"; var success = false; try { Cursor.Current = Cursors.WaitCursor; fs = File.Open(tempFile, FileMode.Create); var s = new XmlSerializer(typeof(CslaGeneratorUnit)); s.Serialize(fs, _currentUnit); success = true; } catch (Exception e) { MessageBox.Show(_mainForm, @"An error occurred while trying to save: " + Environment.NewLine + e.Message, "Save Error"); } finally { Cursor.Current = Cursors.Default; if (fs != null) { fs.Close(); fs.Dispose(); } } if (success) { File.Delete(filePath); File.Move(tempFile, filePath); _currentFilePath = GetFilePath(filePath); } SaveProjectLayout(filePath); } internal void SaveProjectLayout(string filePath) { _mainForm.GetProjectState(); filePath = ExtractPathWithoutExtension(filePath) + ".Layout"; FileStream fs = null; var tempFile = Path.GetTempPath() + Guid.NewGuid().ToString() + ".cslagenerator"; var success = false; try { Cursor.Current = Cursors.WaitCursor; fs = File.Open(tempFile, FileMode.Create); var s = new XmlSerializer(typeof(CslaGeneratorUnitLayout)); s.Serialize(fs, CurrentUnitLayout); success = true; } catch (Exception e) { MessageBox.Show(_mainForm, @"An error occurred while trying to save: " + Environment.NewLine + e.Message, "Save Error"); } finally { Cursor.Current = Cursors.Default; if (fs != null) { fs.Close(); fs.Dispose(); } } if (success) { File.Delete(filePath); File.Move(tempFile, filePath); File.SetAttributes(filePath, FileAttributes.Hidden); } } internal static string ExtractFilename(string filePath) { var slash = filePath.LastIndexOf('\\'); if (slash > 0) return filePath.Substring(slash + 1); return filePath; } internal static string ExtractPathWithoutExtension(string filePath) { var dot = filePath.LastIndexOf('.'); if (dot > 0) return filePath.Substring(0, dot); return filePath; } #endregion #region private Methods private string GetFilePath(string fileName) { var fi = new FileInfo(fileName); return fi.Directory.FullName; } private void BindControls() { if (_currentUnit != null) { _mainForm.ProjectNameTextBox.Enabled = true; _mainForm.ProjectNameTextBox.DataBindings.Clear(); _mainForm.ProjectNameTextBox.DataBindings.Add("Text", _currentUnit, "ProjectName"); _mainForm.TargetDirectoryButton.Enabled = true; _mainForm.TargetDirectoryTextBox.Enabled = true; _mainForm.TargetDirectoryTextBox.DataBindings.Clear(); _mainForm.TargetDirectoryTextBox.DataBindings.Add("Text", _currentUnit, "TargetDirectory"); BindCslaList(); BindRelationsList(); } } private void BindCslaList() { if (_currentUnit != null) { _mainForm.ProjectPanel.Objects = _currentUnit.CslaObjects; _mainForm.ProjectPanel.ApplyFilters(true); _mainForm.ProjectPanel.ListObjects.ClearSelected(); if (_mainForm.ProjectPanel.ListObjects.Items.Count > 0) _mainForm.ProjectPanel.ListObjects.SelectedIndex = 0; // make sure the previous stored selection is cleared _mainForm.ProjectPanel.ClearSelectedItems(); } } private void BindRelationsList() { if (_currentUnit != null) { _mainForm.ObjectRelationsBuilderPanel.AssociativeEntities = _currentUnit.AssociativeEntities; _mainForm.ObjectRelationsBuilderPanel.FillViews(true); _mainForm.ObjectRelationsBuilderPanel.GetCurrentListBox().ClearSelected(); if (_mainForm.ObjectRelationsBuilderPanel.GetCurrentListBox().Items.Count > 0) _mainForm.ObjectRelationsBuilderPanel.GetCurrentListBox().SelectedIndex = 0; // make sure the previous stored selection is cleared _mainForm.ObjectRelationsBuilderPanel.ClearSelectedItems(); } } private void BuildSchemaTree(string connectionString) { try { if (_mainForm.DbSchemaPanel != null && _mainForm.DbSchemaPanel.Visible) _mainForm.DbSchemaPanel.Hide(); if (_mainForm.DbSchemaPanel != null) { _mainForm.DbSchemaPanel.Close(); _mainForm.DbSchemaPanel.Dispose(); } _mainForm.DbSchemaPanel = new DbSchemaPanel(_currentUnit, connectionString); _mainForm.DbSchemaPanel.BuildSchemaTree(); _mainForm.ActivateShowSchema(); _mainForm.DbSchemaPanel.SetDbColumnsPctHeight(73); _mainForm.DbSchemaPanel.SetDbTreeViewPctHeight(73); } catch (Exception e) { throw (e); } } /*private string GetFileNameWithoutExtension(string fileName) { var index = fileName.LastIndexOf("."); if (index >= 0) { return fileName.Substring(0, index); } return fileName; } private string GetFileExtension(string fileName) { var index = fileName.LastIndexOf("."); if (index >= 0) { return fileName.Substring(index + 1); } return ".cs"; } private string GetTemplateName(CslaObjectInfo info) { switch (info.ObjectType) { case CslaObjectType.EditableRoot: return ConfigurationManager.AppSettings["EditableRootTemplate"]; case CslaObjectType.EditableChild: return ConfigurationManager.AppSettings["EditableChildTemplate"]; case CslaObjectType.EditableRootCollection: return ConfigurationManager.AppSettings["EditableRootCollectionTemplate"]; case CslaObjectType.EditableChildCollection: return ConfigurationManager.AppSettings["EditableChildCollectionTemplate"]; case CslaObjectType.EditableSwitchable: return ConfigurationManager.AppSettings["EditableSwitchableTemplate"]; case CslaObjectType.DynamicEditableRoot: return ConfigurationManager.AppSettings["DynamicEditableRootTemplate"]; case CslaObjectType.DynamicEditableRootCollection: return ConfigurationManager.AppSettings["DynamicEditableRootCollectionTemplate"]; case CslaObjectType.ReadOnlyObject: return ConfigurationManager.AppSettings["ReadOnlyObjectTemplate"]; case CslaObjectType.ReadOnlyCollection: return ConfigurationManager.AppSettings["ReadOnlyCollectionTemplate"]; default: return String.Empty; } }*/ #endregion #region Event Handlers private void GeneratorFormClosing(object sender, CancelEventArgs e) { Application.Exit(); } private void CslaObjectList_SelectedItemsChanged(object sender, EventArgs e) { // fired on "ObjectName" changed for the following scenario: // Suppose we have a filter on the name, // and we change the object name in such way that // the object isn't visible any longer, // and it must not be shown on the PropertyGrid // THEN we need to reload the PropertyGrid ReloadPropertyGrid(); } private void AssociativeEntitiesList_SelectedItemsChanged(object sender, EventArgs e) { ReloadBuilderPropertyGrid(); } internal void ReloadPropertyGrid() { if (_mainForm.DbSchemaPanel != null) _mainForm.DbSchemaPanel.CurrentCslaObject = null; var selectedItems = new List<CslaObjectInfo>(); foreach (CslaObjectInfo obj in _mainForm.ProjectPanel.ListObjects.SelectedItems) { selectedItems.Add(obj); if (!IsLoading && _mainForm.DbSchemaPanel != null) { CurrentCslaObject = obj; _mainForm.DbSchemaPanel.CurrentCslaObject = obj; } } if (_mainForm.DbSchemaPanel != null && selectedItems.Count != 1) { CurrentCslaObject = null; _mainForm.DbSchemaPanel.CurrentCslaObject = null; } if (selectedItems.Count == 0) _mainForm.ObjectInfoGrid.SelectedObject = null; else _mainForm.ObjectInfoGrid.SelectedObject = new PropertyBag(selectedItems.ToArray(), _propertyContext); } void ReloadBuilderPropertyGrid() { var selectedItems = new List<AssociativeEntity>(); var listBoxSelectedItems = _mainForm.ObjectRelationsBuilderPanel.GetCurrentListBox().SelectedItems; foreach (AssociativeEntity obj in listBoxSelectedItems) { selectedItems.Add(obj); if (!IsLoading) { _currentAssociativeEntitiy = obj; } } if (selectedItems.Count == 0) { _currentAssociativeEntitiy = null; } else { if (_currentAssociativeEntitiy == null) _currentAssociativeEntitiy = selectedItems[0]; } _mainForm.ObjectRelationsBuilderPanel.SetAllPropertyGridSelectedObject(_currentAssociativeEntitiy); } #endregion private void GetConfig() { GetConfigTemplatesFolder(); GetConfigProjectsFolder(); GetConfigObjectsFolder(); GetConfigRulesFolder(); } private void GetConfigTemplatesFolder() { var tDir = ConfigTools.SharedAppConfigGet("TemplatesDirectory"); if (string.IsNullOrEmpty(tDir)) { tDir = ConfigTools.AppConfigGet("TemplatesDirectory"); while (tDir.LastIndexOf(@"\\") == tDir.Length - 2) { tDir = tDir.Substring(0, tDir.Length - 1); } } if (string.IsNullOrEmpty(tDir)) { TemplatesDirectory = Environment.SpecialFolder.Desktop.ToString(); } else { TemplatesDirectory = tDir; } } private void GetConfigProjectsFolder() { var tDir = ConfigTools.SharedAppConfigGet("ProjectsDirectory"); if (string.IsNullOrEmpty(tDir)) { tDir = ConfigTools.AppConfigGet("ProjectsDirectory"); while (tDir.LastIndexOf(@"\\") == tDir.Length - 2) { tDir = tDir.Substring(0, tDir.Length - 1); } } if (string.IsNullOrEmpty(tDir)) { ProjectsDirectory = Environment.SpecialFolder.Desktop.ToString(); } else { ProjectsDirectory = tDir; } } internal void GetConfigObjectsFolder() { var tDir = ConfigTools.SharedAppConfigGet("ObjectsDirectory"); if (string.IsNullOrEmpty(tDir)) { tDir = ConfigTools.AppConfigGet("ObjectsDirectory"); while (tDir.LastIndexOf(@"\\") == tDir.Length - 2) { tDir = tDir.Substring(0, tDir.Length - 1); } } if (string.IsNullOrEmpty(tDir)) { ObjectsDirectory = Environment.SpecialFolder.Desktop.ToString(); } else { ObjectsDirectory = tDir; } } private void GetConfigRulesFolder() { var tDir = ConfigTools.SharedAppConfigGet("RulesDirectory"); if (string.IsNullOrEmpty(tDir)) { tDir = ConfigTools.AppConfigGet("RulesDirectory"); while (tDir.LastIndexOf(@"\\") == tDir.Length - 2) { tDir = tDir.Substring(0, tDir.Length - 1); } } if (string.IsNullOrEmpty(tDir)) { RulesDirectory = Environment.SpecialFolder.Desktop.ToString(); } else { RulesDirectory = tDir; } } internal void ReSortMruItems() { var original = MruItems.ToArray(); MruItems.Clear(); foreach (var item in original) { if (!MruItems.Contains(item)) MruItems.Add(item); } ConfigTools.SharedAppConfigChangeMru(MruItems); } internal object GetSelectedItem() { object selectedItem; if (Current.MainForm.ProjectPanel.ListObjects.InvokeRequired) { selectedItem = Current.MainForm.ProjectPanel.ListObjects.Invoke((Action) delegate { GetSelectedItem(); }); return selectedItem; } selectedItem = Current.MainForm.ProjectPanel.ListObjects.SelectedItem; return selectedItem; } #region Nested CslaObjectInfoComparer private class CslaObjectInfoComparer : IComparer<CslaObjectInfo> { #region IComparer<CslaObjectInfo> Members public int Compare(CslaObjectInfo x, CslaObjectInfo y) { return x.ObjectName.CompareTo(y.ObjectName); } #endregion } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyComplex { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; public static partial class PolymorphismExtensions { /// <summary> /// Get complex types that are polymorphic /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Fish GetValid(this IPolymorphism operations) { return Task.Factory.StartNew(s => ((IPolymorphism)s).GetValidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get complex types that are polymorphic /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Fish> GetValidAsync( this IPolymorphism operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put complex types that are polymorphic /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put a salmon that looks like this: /// { /// 'fishtype':'Salmon', /// 'location':'alaska', /// 'iswild':true, /// 'species':'king', /// 'length':1.0, /// 'siblings':[ /// { /// 'fishtype':'Shark', /// 'age':6, /// 'birthday': '2012-01-05T01:00:00Z', /// 'length':20.0, /// 'species':'predator', /// }, /// { /// 'fishtype':'Sawshark', /// 'age':105, /// 'birthday': '1900-01-05T01:00:00Z', /// 'length':10.0, /// 'picture': new Buffer([255, 255, 255, 255, /// 254]).toString('base64'), /// 'species':'dangerous', /// }, /// { /// 'fishtype': 'goblin', /// 'age': 1, /// 'birthday': '2015-08-08T00:00:00Z', /// 'length': 30.0, /// 'species': 'scary', /// 'jawsize': 5 /// } /// ] /// }; /// </param> public static void PutValid(this IPolymorphism operations, Fish complexBody) { Task.Factory.StartNew(s => ((IPolymorphism)s).PutValidAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put complex types that are polymorphic /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put a salmon that looks like this: /// { /// 'fishtype':'Salmon', /// 'location':'alaska', /// 'iswild':true, /// 'species':'king', /// 'length':1.0, /// 'siblings':[ /// { /// 'fishtype':'Shark', /// 'age':6, /// 'birthday': '2012-01-05T01:00:00Z', /// 'length':20.0, /// 'species':'predator', /// }, /// { /// 'fishtype':'Sawshark', /// 'age':105, /// 'birthday': '1900-01-05T01:00:00Z', /// 'length':10.0, /// 'picture': new Buffer([255, 255, 255, 255, /// 254]).toString('base64'), /// 'species':'dangerous', /// }, /// { /// 'fishtype': 'goblin', /// 'age': 1, /// 'birthday': '2015-08-08T00:00:00Z', /// 'length': 30.0, /// 'species': 'scary', /// 'jawsize': 5 /// } /// ] /// }; /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutValidAsync( this IPolymorphism operations, Fish complexBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutValidWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Put complex types that are polymorphic, attempting to omit required /// 'birthday' field - the request should not be allowed from the client /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please attempt put a sawshark that looks like this, the client should not /// allow this data to be sent: /// { /// "fishtype": "sawshark", /// "species": "snaggle toothed", /// "length": 18.5, /// "age": 2, /// "birthday": "2013-06-01T01:00:00Z", /// "location": "alaska", /// "picture": base64(FF FF FF FF FE), /// "siblings": [ /// { /// "fishtype": "shark", /// "species": "predator", /// "birthday": "2012-01-05T01:00:00Z", /// "length": 20, /// "age": 6 /// }, /// { /// "fishtype": "sawshark", /// "species": "dangerous", /// "picture": base64(FF FF FF FF FE), /// "length": 10, /// "age": 105 /// } /// ] /// } /// </param> public static void PutValidMissingRequired(this IPolymorphism operations, Fish complexBody) { Task.Factory.StartNew(s => ((IPolymorphism)s).PutValidMissingRequiredAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put complex types that are polymorphic, attempting to omit required /// 'birthday' field - the request should not be allowed from the client /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please attempt put a sawshark that looks like this, the client should not /// allow this data to be sent: /// { /// "fishtype": "sawshark", /// "species": "snaggle toothed", /// "length": 18.5, /// "age": 2, /// "birthday": "2013-06-01T01:00:00Z", /// "location": "alaska", /// "picture": base64(FF FF FF FF FE), /// "siblings": [ /// { /// "fishtype": "shark", /// "species": "predator", /// "birthday": "2012-01-05T01:00:00Z", /// "length": 20, /// "age": 6 /// }, /// { /// "fishtype": "sawshark", /// "species": "dangerous", /// "picture": base64(FF FF FF FF FE), /// "length": 10, /// "age": 105 /// } /// ] /// } /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutValidMissingRequiredAsync( this IPolymorphism operations, Fish complexBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutValidMissingRequiredWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Reflection; using Microsoft.Extensions.Logging; using Orleans.Streams; namespace Orleans.Runtime.Host { /// <summary> /// Interface exposed by ServiceRuntimeWrapper for functionality provided /// by Microsoft.WindowsAzure.ServiceRuntime. /// </summary> public interface IServiceRuntimeWrapper { /// <summary> /// Deployment ID of the hosted service /// </summary> string DeploymentId { get; } /// <summary> /// Name of the role instance /// </summary> string InstanceName { get; } /// <summary> /// Name of the worker/web role /// </summary> string RoleName { get; } /// <summary> /// Update domain of the role instance /// </summary> int UpdateDomain { get; } /// <summary> /// Fault domain of the role instance /// </summary> int FaultDomain { get; } /// <summary> /// Number of instances in the worker/web role /// </summary> int RoleInstanceCount { get; } /// <summary> /// Returns IP endpoint by name /// </summary> /// <param name="endpointName">Name of the IP endpoint</param> /// <returns></returns> IPEndPoint GetIPEndpoint(string endpointName); /// <summary> /// Returns value of the given configuration setting /// </summary> /// <param name="configurationSettingName"></param> /// <returns></returns> string GetConfigurationSettingValue(string configurationSettingName); /// <summary> /// Subscribes given even handler for role instance Stopping event /// </summary> /// /// <param name="handlerObject">Object that handler is part of, or null for a static method</param> /// <param name="handler">Handler to subscribe</param> void SubscribeForStoppingNotification(object handlerObject, EventHandler<object> handler); /// <summary> /// Unsubscribes given even handler from role instance Stopping event /// </summary> /// /// <param name="handlerObject">Object that handler is part of, or null for a static method</param> /// <param name="handler">Handler to unsubscribe</param> void UnsubscribeFromStoppingNotification(object handlerObject, EventHandler<object> handler); } /// <summary> /// The purpose of this class is to wrap the functionality provided /// by Microsoft.WindowsAzure.ServiceRuntime.dll, so that we can access it via Reflection, /// and not have a compile-time dependency on it. /// Microsoft.WindowsAzure.ServiceRuntime.dll doesn't have an official NuGet package. /// By loading it via Reflection we solve this problem, and do not need an assembly /// binding redirect for it, as we can call any compatible version. /// Microsoft.WindowsAzure.ServiceRuntime.dll hasn't changed in years, so the chance of a breaking change /// is relatively low. /// </summary> internal class ServiceRuntimeWrapper : IServiceRuntimeWrapper, IDeploymentConfiguration { private readonly ILogger logger; private Assembly assembly; private Type roleEnvironmentType; private EventInfo stoppingEvent; private MethodInfo stoppingEventAdd; private MethodInfo stoppingEventRemove; private Type roleInstanceType; private dynamic currentRoleInstance; private dynamic instanceEndpoints; private dynamic role; public ServiceRuntimeWrapper(ILoggerFactory loggerFactory) { logger = loggerFactory.CreateLogger<ServiceRuntimeWrapper>(); Initialize(); } public string DeploymentId { get; private set; } public string InstanceId { get; private set; } public string RoleName { get; private set; } public int UpdateDomain { get; private set; } public int FaultDomain { get; private set; } public string InstanceName { get { return ExtractInstanceName(InstanceId, DeploymentId); } } public int RoleInstanceCount { get { dynamic instances = role.Instances; return instances.Count; } } public IList<string> GetAllSiloNames() { dynamic instances = role.Instances; var list = new List<string>(); foreach(dynamic instance in instances) list.Add(ExtractInstanceName(instance.Id,DeploymentId)); return list; } public IPEndPoint GetIPEndpoint(string endpointName) { try { dynamic ep = instanceEndpoints.GetType() .GetProperty("Item") .GetMethod.Invoke(instanceEndpoints, new object[] {endpointName}); return ep.IPEndpoint; } catch (Exception exc) { string errorMsg = string.Format("Unable to obtain endpoint info for role {0} from role config parameter {1} -- Endpoints defined = [{2}]", RoleName, endpointName, string.Join(", ", instanceEndpoints)); logger.Error(ErrorCode.SiloEndpointConfigError, errorMsg, exc); throw new OrleansException(errorMsg, exc); } } public string GetConfigurationSettingValue(string configurationSettingName) { return (string) roleEnvironmentType.GetMethod("GetConfigurationSettingValue").Invoke(null, new object[] {configurationSettingName}); } public void SubscribeForStoppingNotification(object handlerObject, EventHandler<object> handler) { var handlerDelegate = handler.GetMethodInfo().CreateDelegate(stoppingEvent.EventHandlerType, handlerObject); stoppingEventAdd.Invoke(null, new object[] { handlerDelegate }); } public void UnsubscribeFromStoppingNotification(object handlerObject, EventHandler<object> handler) { var handlerDelegate = handler.GetMethodInfo().CreateDelegate(stoppingEvent.EventHandlerType, handlerObject); stoppingEventRemove.Invoke(null, new[] { handlerDelegate }); } private void Initialize() { assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault( a => a.FullName.StartsWith("Microsoft.WindowsAzure.ServiceRuntime")); // If we are runing within a worker role Microsoft.WindowsAzure.ServiceRuntime should already be loaded if (assembly == null) { const string msg1 = "Microsoft.WindowsAzure.ServiceRuntime is not loaded. Trying to load it with Assembly.LoadWithPartialName()."; logger.Warn(ErrorCode.AzureServiceRuntime_NotLoaded, msg1); // Microsoft.WindowsAzure.ServiceRuntime isn't loaded. We may be running within a web role or not in Azure. #pragma warning disable 618 assembly = Assembly.Load(new AssemblyName("Microsoft.WindowsAzure.ServiceRuntime, Version = 2.7.0.0, Culture = neutral, PublicKeyToken = 31bf3856ad364e35")); #pragma warning restore 618 if (assembly == null) { const string msg2 = "Failed to find or load Microsoft.WindowsAzure.ServiceRuntime."; logger.Error(ErrorCode.AzureServiceRuntime_FailedToLoad, msg2); throw new OrleansException(msg2); } } roleEnvironmentType = assembly.GetType("Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment"); stoppingEvent = roleEnvironmentType.GetEvent("Stopping"); stoppingEventAdd = stoppingEvent.GetAddMethod(); stoppingEventRemove = stoppingEvent.GetRemoveMethod(); roleInstanceType = assembly.GetType("Microsoft.WindowsAzure.ServiceRuntime.RoleInstance"); DeploymentId = (string) roleEnvironmentType.GetProperty("DeploymentId").GetValue(null); if (string.IsNullOrWhiteSpace(DeploymentId)) throw new OrleansException("DeploymentId is null or whitespace."); currentRoleInstance = roleEnvironmentType.GetProperty("CurrentRoleInstance").GetValue(null); if (currentRoleInstance == null) throw new OrleansException("CurrentRoleInstance is null."); InstanceId = currentRoleInstance.Id; UpdateDomain = currentRoleInstance.UpdateDomain; FaultDomain = currentRoleInstance.FaultDomain; instanceEndpoints = currentRoleInstance.InstanceEndpoints; role = currentRoleInstance.Role; RoleName = role.Name; } private static string ExtractInstanceName(string instanceId, string deploymentId) { return instanceId.Length > deploymentId.Length && instanceId.StartsWith(deploymentId) ? instanceId.Substring(deploymentId.Length + 1) : instanceId; } } }
/** * 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 System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; namespace Thrift.Transport { /// <summary> /// SSL Socket Wrapper class /// </summary> public class TTLSSocket : TStreamTransport { /// <summary> /// Internal TCP Client /// </summary> private TcpClient client = null; /// <summary> /// The host /// </summary> private string host = null; /// <summary> /// The port /// </summary> private int port = 0; /// <summary> /// The timeout for the connection /// </summary> private int timeout = 0; /// <summary> /// Internal SSL Stream for IO /// </summary> private SslStream secureStream = null; /// <summary> /// Defines wheter or not this socket is a server socket<br/> /// This is used for the TLS-authentication /// </summary> private bool isServer = false; /// <summary> /// The certificate /// </summary> private X509Certificate certificate = null; /// <summary> /// User defined certificate validator. /// </summary> private RemoteCertificateValidationCallback certValidator = null; /// <summary> /// Initializes a new instance of the <see cref="TTLSSocket"/> class. /// </summary> /// <param name="client">An already created TCP-client</param> /// <param name="certificate">The certificate.</param> /// <param name="isServer">if set to <c>true</c> [is server].</param> public TTLSSocket(TcpClient client, X509Certificate certificate, bool isServer = false) { this.client = client; this.certificate = certificate; this.isServer = isServer; if (IsOpen) { base.inputStream = client.GetStream(); base.outputStream = client.GetStream(); } } /// <summary> /// Initializes a new instance of the <see cref="TTLSSocket"/> class. /// </summary> /// <param name="host">The host, where the socket should connect to.</param> /// <param name="port">The port.</param> /// <param name="certificatePath">The certificate path.</param> /// <param name="certValidator">User defined cert validator.</param> public TTLSSocket(string host, int port, string certificatePath, RemoteCertificateValidationCallback certValidator = null) : this(host, port, 0, X509Certificate.CreateFromCertFile(certificatePath), certValidator) { } /// <summary> /// Initializes a new instance of the <see cref="TTLSSocket"/> class. /// </summary> /// <param name="host">The host, where the socket should connect to.</param> /// <param name="port">The port.</param> /// <param name="certificate">The certificate.</param> /// <param name="certValidator">User defined cert validator.</param> public TTLSSocket(string host, int port, X509Certificate certificate, RemoteCertificateValidationCallback certValidator = null) : this(host, port, 0, certificate, certValidator) { } /// <summary> /// Initializes a new instance of the <see cref="TTLSSocket"/> class. /// </summary> /// <param name="host">The host, where the socket should connect to.</param> /// <param name="port">The port.</param> /// <param name="timeout">The timeout.</param> /// <param name="certificate">The certificate.</param> /// <param name="certValidator">User defined cert validator.</param> public TTLSSocket(string host, int port, int timeout, X509Certificate certificate, RemoteCertificateValidationCallback certValidator = null) { this.host = host; this.port = port; this.timeout = timeout; this.certificate = certificate; this.certValidator = certValidator; InitSocket(); } /// <summary> /// Creates the TcpClient and sets the timeouts /// </summary> private void InitSocket() { this.client = new TcpClient(); client.ReceiveTimeout = client.SendTimeout = timeout; client.Client.NoDelay = true; } /// <summary> /// Sets Send / Recv Timeout for IO /// </summary> public int Timeout { set { this.client.ReceiveTimeout = this.client.SendTimeout = this.timeout = value; } } /// <summary> /// Gets the TCP client. /// </summary> public TcpClient TcpClient { get { return client; } } /// <summary> /// Gets the host. /// </summary> public string Host { get { return host; } } /// <summary> /// Gets the port. /// </summary> public int Port { get { return port; } } /// <summary> /// Gets a value indicating whether TCP Client is Cpen /// </summary> public override bool IsOpen { get { if (this.client == null) { return false; } return this.client.Connected; } } /// <summary> /// Validates the certificates!<br/> /// </summary> /// <param name="sender">The sender-object.</param> /// <param name="certificate">The used certificate.</param> /// <param name="chain">The certificate chain.</param> /// <param name="sslPolicyErrors">An enum, which lists all the errors from the .NET certificate check.</param> /// <returns></returns> private bool CertificateValidator(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslValidationErrors) { return (sslValidationErrors == SslPolicyErrors.None); } /// <summary> /// Connects to the host and starts the routine, which sets up the TLS /// </summary> public override void Open() { if (IsOpen) { throw new TTransportException(TTransportException.ExceptionType.AlreadyOpen, "Socket already connected"); } if (String.IsNullOrEmpty(host)) { throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open null host"); } if (port <= 0) { throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open without port"); } if (client == null) { InitSocket(); } client.Connect(host, port); setupTLS(); } /// <summary> /// Creates a TLS-stream and lays it over the existing socket /// </summary> public void setupTLS() { if (isServer) { // Server authentication this.secureStream = new SslStream(this.client.GetStream(), false); this.secureStream.AuthenticateAsServer(this.certificate, false, SslProtocols.Tls, true); } else { // Client authentication X509CertificateCollection validCerts = new X509CertificateCollection(); validCerts.Add(certificate); if (this.certValidator != null) { this.secureStream = new SslStream(this.client.GetStream(), false, new RemoteCertificateValidationCallback(this.certValidator)); } else { this.secureStream = new SslStream(this.client.GetStream(), false, new RemoteCertificateValidationCallback(CertificateValidator)); } this.secureStream.AuthenticateAsClient(host, validCerts, SslProtocols.Tls, true); } inputStream = this.secureStream; outputStream = this.secureStream; } /// <summary> /// Closes the SSL Socket /// </summary> public override void Close() { base.Close(); if (this.client != null) { this.client.Close(); this.client = null; } if (this.secureStream != null) { this.secureStream.Close(); this.secureStream = null; } } } }
// Copyright 2016 Applied Geographics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.Data.OleDb; using System.Linq; using System.Web; using System.Web.Caching; using System.Web.UI.HtmlControls; using AppGeo.Clients; using AppGeo.Clients.Ags; using AppGeo.Clients.ArcIms; public static class AppContext { public const string ServerImageCacheKey = "ServerImageCache"; public const string BrowserImageCacheKey = "BrowserImageCache"; public static string ConfigurationKey = DateTime.Now.ToString("yyyyMMddhhmmss"); private static object ConfigurationLock = new object(); public static AppSettings AppSettings { get { return GetConfiguration().AppSettings; } } public static TimedCache<MapImageData> BrowserImageCache { get { TimedCache<MapImageData> imageCache; if (HttpContext.Current.Cache[BrowserImageCacheKey] == null) { imageCache = new TimedCache<MapImageData>(AppSettings.BrowserImageCacheTimeout, true); CacheInsert(BrowserImageCacheKey, imageCache); } else { imageCache = (TimedCache<MapImageData>)HttpContext.Current.Cache[BrowserImageCacheKey]; } return imageCache; } } public static TimedCache<MapImageData> ServerImageCache { get { TimedCache<MapImageData> imageCache; if (HttpContext.Current.Cache[ServerImageCacheKey] == null) { imageCache = new TimedCache<MapImageData>(AppSettings.ServerImageCacheTimeout); CacheInsert(ServerImageCacheKey, imageCache); } else { imageCache = (TimedCache<MapImageData>)HttpContext.Current.Cache[ServerImageCacheKey]; } return imageCache; } } public static void CacheConfiguration(Configuration config) { string key = "Configuration"; foreach (DictionaryEntry entry in HttpContext.Current.Cache) { string entryKey = (string)entry.Key; if (entryKey != BrowserImageCacheKey && entryKey != ServerImageCacheKey) { HttpContext.Current.Cache.Remove(entryKey); } } CacheInsert(key, config); ConfigurationKey = DateTime.Now.ToString("yyyyMMddhhmmss"); } private static void CacheInsert(string key, object obj) { HttpContext.Current.Cache.Insert(key, obj, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null); } private static Dictionary<String, CommonDataFrame> GetCachedDataFrames() { Cache cache = HttpContext.Current.Cache; string cacheKey = "DataFrames"; Dictionary<String, CommonDataFrame> dataFrames = null; if (cache[cacheKey] != null) { dataFrames = (Dictionary<String, CommonDataFrame>)cache[cacheKey]; } else { dataFrames = new Dictionary<String, CommonDataFrame>(); CacheInsert(cacheKey, dataFrames); } return dataFrames; } private static Dictionary<String, CommonMapService> GetCachedServices() { Cache cache = HttpContext.Current.Cache; string cacheKey = "Services"; Dictionary<String, CommonMapService> services = null; if (cache[cacheKey] != null) { services = (Dictionary<String, CommonMapService>)cache[cacheKey]; } else { services = new Dictionary<String, CommonMapService>(); CacheInsert(cacheKey, services); } return services; } public static Configuration GetConfiguration() { return GetConfiguration(false); } public static Configuration GetConfiguration(bool forceReload) { Cache cache = HttpContext.Current.Cache; string key = "Configuration"; Configuration config; lock (ConfigurationLock) { if (!forceReload && cache[key] != null) { config = (Configuration)cache[key]; } else { config = Configuration.GetCurrent(); config.CascadeDeactivated(); config.RemoveDeactivated(); config.ValidateConfiguration(); config.RemoveValidationErrors(); CacheConfiguration(config); } } return config; } public static OleDbConnection GetDatabaseConnection() { OleDbConnection connection; try { connection = new OleDbConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString); connection.Open(); } catch (Exception ex) { throw new AppException("Could not connect to database.", ex); } return connection; } public static CommonDataFrame GetDataFrame(string mapTabId) { Configuration config = GetConfiguration(); Configuration.MapTabRow mapTab = config.MapTab.FindByMapTabID(mapTabId); return GetDataFrame(mapTab); } public static CommonDataFrame GetDataFrame(Configuration.MapTabRow mapTab) { Dictionary<String, CommonDataFrame> dataFrames = GetCachedDataFrames(); string dataFrameKey = mapTab.GetDataFrameKey(); CommonDataFrame dataFrame = null; if (dataFrames.ContainsKey(dataFrameKey)) { dataFrame = dataFrames[dataFrameKey]; } else { Dictionary<String, CommonMapService> services = GetCachedServices(); CommonMapService service = null; string serviceKey = mapTab.GetServiceKey("AGS"); if (services.ContainsKey(serviceKey)) { service = services[serviceKey]; } else { serviceKey = mapTab.GetServiceKey("ArcIMS"); if (services.ContainsKey(serviceKey)) { service = services[serviceKey]; } } if (service == null) { service = GetService(mapTab, "AGS"); if (service == null) { service = GetService(mapTab, "ArcIMS"); } } if (service != null) { dataFrame = mapTab.IsDataFrameNull() ? service.DefaultDataFrame : service.DataFrames.FirstOrDefault(df => String.Compare(df.Name, mapTab.DataFrame, true) == 0); if (dataFrame != null) { dataFrames.Add(dataFrameKey, dataFrame); } } } return dataFrame; } private static CommonHost GetHost(Configuration.MapTabRow mapTab, string type) { string userName = mapTab.IsUserNameNull() ? "" : mapTab.UserName; string password = mapTab.IsPasswordNull() ? "" : mapTab.Password; CommonHost host = null; try { switch (type) { case "AGS": if (String.IsNullOrEmpty(userName) && String.IsNullOrEmpty(password)) { host = new AgsHost(mapTab.MapHost); } else { try { host = new AgsHost(mapTab.MapHost, userName, password, true); } catch { } if (host == null) { host = new AgsHost(mapTab.MapHost, userName, password, false); } } break; case "ArcIMS": host = new ArcImsHost(mapTab.MapHost, userName, password); break; } } catch { } return host; } private static CommonMapService GetService(Configuration.MapTabRow mapTab, string type) { Dictionary<String, CommonMapService> services = GetCachedServices(); string serviceKey = mapTab.GetServiceKey(type); CommonMapService service = null; if (services.ContainsKey(serviceKey)) { service = services[serviceKey]; } else { CommonHost host = GetHost(mapTab, type); if (host != null) { try { service = host.GetMapService(mapTab.MapService); ArcImsService arcImsService = service as ArcImsService; if (arcImsService != null && !arcImsService.IsArcMap) { arcImsService.LoadToc(true); } services.Add(serviceKey, service); } catch { } } } return service; } }
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 ShopyShop.Areas.HelpPage.ModelDescriptions; using ShopyShop.Areas.HelpPage.Models; namespace ShopyShop.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Xml; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.DataSnapshot.Interfaces; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.DataSnapshot.Providers { public class ObjectSnapshot : IDataSnapshotProvider { private Scene m_scene = null; // private DataSnapshotManager m_parent = null; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private bool m_stale = true; private static UUID m_DefaultImage = new UUID("89556747-24cb-43ed-920b-47caed15465f"); private static UUID m_BlankImage = new UUID("5748decc-f629-461c-9a36-a35a221fe21f"); public void Initialize(Scene scene, DataSnapshotManager parent) { m_scene = scene; // m_parent = parent; //To check for staleness, we must catch all incoming client packets. m_scene.EventManager.OnNewClient += OnNewClient; m_scene.EventManager.OnParcelPrimCountAdd += delegate(SceneObjectGroup obj) { this.Stale = true; }; } public void OnNewClient(IClientAPI client) { //Detect object data changes by hooking into the IClientAPI. //Very dirty, and breaks whenever someone changes the client API. client.OnAddPrim += delegate (UUID ownerID, UUID groupID, Vector3 RayEnd, Quaternion rot, PrimitiveBaseShape shape, byte bypassRaycast, Vector3 RayStart, UUID RayTargetID, byte RayEndIsIntersection) { this.Stale = true; }; client.OnLinkObjects += delegate (IClientAPI remoteClient, uint parent, List<uint> children) { this.Stale = true; }; client.OnDelinkObjects += delegate(List<uint> primIds, IClientAPI clientApi) { this.Stale = true; }; client.OnGrabUpdate += delegate(UUID objectID, Vector3 offset, Vector3 grapPos, IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs) { this.Stale = true; }; client.OnObjectAttach += delegate(IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, Quaternion rot, bool silent) { this.Stale = true; }; client.OnObjectDuplicate += delegate(uint localID, Vector3 offset, uint dupeFlags, UUID AgentID, UUID GroupID) { this.Stale = true; }; client.OnObjectDuplicateOnRay += delegate(uint localID, uint dupeFlags, UUID AgentID, UUID GroupID, UUID RayTargetObj, Vector3 RayEnd, Vector3 RayStart, bool BypassRaycast, bool RayEndIsIntersection, bool CopyCenters, bool CopyRotates) { this.Stale = true; }; client.OnObjectIncludeInSearch += delegate(IClientAPI remoteClient, bool IncludeInSearch, uint localID) { this.Stale = true; }; client.OnObjectPermissions += delegate(IClientAPI controller, UUID agentID, UUID sessionID, byte field, uint localId, uint mask, byte set) { this.Stale = true; }; client.OnRezObject += delegate(IClientAPI remoteClient, UUID itemID, Vector3 RayEnd, Vector3 RayStart, UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection, bool RezSelected, bool RemoveItem, UUID fromTaskID) { this.Stale = true; }; } public Scene GetParentScene { get { return m_scene; } } public XmlNode RequestSnapshotData(XmlDocument nodeFactory) { m_log.Debug("[DATASNAPSHOT]: Generating object data for scene " + m_scene.RegionInfo.RegionName); XmlNode parent = nodeFactory.CreateNode(XmlNodeType.Element, "objectdata", ""); XmlNode node; foreach (EntityBase entity in m_scene.Entities) { // only objects, not avatars if (entity is SceneObjectGroup) { SceneObjectGroup obj = (SceneObjectGroup)entity; // m_log.Debug("[DATASNAPSHOT]: Found object " + obj.Name + " in scene"); // libomv will complain about PrimFlags.JointWheel // being obsolete, so we... #pragma warning disable 0612 if ((obj.RootPart.Flags & PrimFlags.JointWheel) == PrimFlags.JointWheel) { SceneObjectPart m_rootPart = obj.RootPart; if (m_rootPart != null) { ILandObject land = m_scene.LandChannel.GetLandObject(m_rootPart.AbsolutePosition.X, m_rootPart.AbsolutePosition.Y); XmlNode xmlobject = nodeFactory.CreateNode(XmlNodeType.Element, "object", ""); node = nodeFactory.CreateNode(XmlNodeType.Element, "uuid", ""); node.InnerText = obj.UUID.ToString(); xmlobject.AppendChild(node); node = nodeFactory.CreateNode(XmlNodeType.Element, "title", ""); node.InnerText = m_rootPart.Name; xmlobject.AppendChild(node); node = nodeFactory.CreateNode(XmlNodeType.Element, "description", ""); node.InnerText = m_rootPart.Description; xmlobject.AppendChild(node); node = nodeFactory.CreateNode(XmlNodeType.Element, "flags", ""); node.InnerText = String.Format("{0:x}", m_rootPart.ObjectFlags); xmlobject.AppendChild(node); node = nodeFactory.CreateNode(XmlNodeType.Element, "regionuuid", ""); node.InnerText = m_scene.RegionInfo.RegionSettings.RegionUUID.ToString(); xmlobject.AppendChild(node); node = nodeFactory.CreateNode(XmlNodeType.Element, "parceluuid", ""); node.InnerText = land.LandData.GlobalID.ToString(); xmlobject.AppendChild(node); node = nodeFactory.CreateNode(XmlNodeType.Element, "location", ""); Vector3 loc = obj.AbsolutePosition; node.InnerText = loc.X.ToString() + "/" + loc.Y.ToString() + "/" + loc.Z.ToString(); xmlobject.AppendChild(node); string bestImage = GuessImage(obj); if (bestImage != string.Empty) { node = nodeFactory.CreateNode(XmlNodeType.Element, "image", ""); node.InnerText = bestImage; xmlobject.AppendChild(node); } parent.AppendChild(xmlobject); } } #pragma warning disable 0612 } } this.Stale = false; return parent; } public String Name { get { return "ObjectSnapshot"; } } public bool Stale { get { return m_stale; } set { m_stale = value; if (m_stale) OnStale(this); } } public event ProviderStale OnStale; /// <summary> /// Guesses the best image, based on a simple heuristic. It guesses only for boxes. /// We're optimizing for boxes, because those are the most common objects /// marked "Show in search" -- boxes with content inside.For other shapes, /// it's really hard to tell which texture should be grabbed. /// </summary> /// <param name="sog"></param> /// <returns></returns> private string GuessImage(SceneObjectGroup sog) { string bestguess = string.Empty; Dictionary<UUID, int> counts = new Dictionary<UUID, int>(); PrimitiveBaseShape shape = sog.RootPart.Shape; if (shape != null && shape.ProfileShape == ProfileShape.Square) { Primitive.TextureEntry textures = shape.Textures; if (textures != null) { if (textures.DefaultTexture != null && textures.DefaultTexture.TextureID != UUID.Zero && textures.DefaultTexture.TextureID != m_DefaultImage && textures.DefaultTexture.TextureID != m_BlankImage && textures.DefaultTexture.RGBA.A < 50f) { counts[textures.DefaultTexture.TextureID] = 8; } if (textures.FaceTextures != null) { foreach (Primitive.TextureEntryFace tentry in textures.FaceTextures) { if (tentry != null) { if (tentry.TextureID != UUID.Zero && tentry.TextureID != m_DefaultImage && tentry.TextureID != m_BlankImage && tentry.RGBA.A < 50) { int c = 0; counts.TryGetValue(tentry.TextureID, out c); counts[tentry.TextureID] = c + 1; // decrease the default texture count if (counts.ContainsKey(textures.DefaultTexture.TextureID)) counts[textures.DefaultTexture.TextureID] = counts[textures.DefaultTexture.TextureID] - 1; } } } } // Let's pick the most unique texture int min = 9999; foreach (KeyValuePair<UUID, int> kv in counts) { if (kv.Value < min && kv.Value >= 1) { bestguess = kv.Key.ToString(); min = kv.Value; } } } } return bestguess; } } }
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 YesNoWebApp.Areas.HelpPage.ModelDescriptions; using YesNoWebApp.Areas.HelpPage.Models; namespace YesNoWebApp.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace LitJson { public class JsonWriter { private static NumberFormatInfo number_format; private WriterContext context; private Stack<WriterContext> ctx_stack; private bool has_reached_end; private char[] hex_seq; private int indentation; private int indent_value; private StringBuilder inst_string_builder; private bool pretty_print; private bool validate; private TextWriter writer; public int IndentValue { get { return this.indent_value; } set { this.indentation = this.indentation / this.indent_value * value; this.indent_value = value; } } public bool PrettyPrint { get { return this.pretty_print; } set { this.pretty_print = value; } } public TextWriter TextWriter { get { return this.writer; } } public bool Validate { get { return this.validate; } set { this.validate = value; } } public JsonWriter() { this.inst_string_builder = new StringBuilder(); this.writer = new StringWriter(this.inst_string_builder); this.Init(); } public JsonWriter(StringBuilder sb) : this(new StringWriter(sb)) { } public JsonWriter(TextWriter writer) { if (writer == null) { throw new ArgumentNullException("writer"); } this.writer = writer; this.Init(); } static JsonWriter() { JsonWriter.number_format = NumberFormatInfo.InvariantInfo; } private void DoValidation(Condition cond) { if (!this.context.ExpectingValue) { this.context.Count++; } if (!this.validate) { return; } if (this.has_reached_end) { throw new JsonException("A complete JSON symbol has already been written"); } switch (cond) { case Condition.InArray: if (!this.context.InArray) { throw new JsonException("Can't close an array here"); } break; case Condition.InObject: if (!this.context.InObject || this.context.ExpectingValue) { throw new JsonException("Can't close an object here"); } break; case Condition.NotAProperty: if (this.context.InObject && !this.context.ExpectingValue) { throw new JsonException("Expected a property"); } break; case Condition.Property: if (!this.context.InObject || this.context.ExpectingValue) { throw new JsonException("Can't add a property here"); } break; case Condition.Value: if (!this.context.InArray && (!this.context.InObject || !this.context.ExpectingValue)) { throw new JsonException("Can't add a value here"); } break; } } private void Init() { this.has_reached_end = false; this.hex_seq = new char[4]; this.indentation = 0; this.indent_value = 4; this.pretty_print = false; this.validate = true; this.ctx_stack = new Stack<WriterContext>(); this.context = new WriterContext(); this.ctx_stack.Push(this.context); } private static void IntToHex(int n, char[] hex) { for (int i = 0; i < 4; i++) { int num = n % 16; if (num < 10) { hex[3 - i] = (char)(48 + num); } else { hex[3 - i] = (char)(65 + (num - 10)); } n >>= 4; } } private void Indent() { if (this.pretty_print) { this.indentation += this.indent_value; } } private void Put(string str) { if (this.pretty_print && !this.context.ExpectingValue) { for (int i = 0; i < this.indentation; i++) { this.writer.Write(' '); } } this.writer.Write(str); } private void PutNewline() { this.PutNewline(true); } private void PutNewline(bool add_comma) { if (add_comma && !this.context.ExpectingValue && this.context.Count > 1) { this.writer.Write(','); } if (this.pretty_print && !this.context.ExpectingValue) { this.writer.Write('\n'); } } private void PutString(string str) { this.Put(string.Empty); this.writer.Write('"'); int length = str.Length; for (int i = 0; i < length; i++) { char c = str[i]; switch (c) { case '\b': this.writer.Write("\\b"); goto IL_156; case '\t': this.writer.Write("\\t"); goto IL_156; case '\n': this.writer.Write("\\n"); goto IL_156; case '\v': IL_4E: if (c == '"' || c == '\\') { this.writer.Write('\\'); this.writer.Write(str[i]); goto IL_156; } if (str[i] >= ' ' && str[i] <= '~') { this.writer.Write(str[i]); goto IL_156; } JsonWriter.IntToHex((int)str[i], this.hex_seq); this.writer.Write("\\u"); this.writer.Write(this.hex_seq); goto IL_156; case '\f': this.writer.Write("\\f"); goto IL_156; case '\r': this.writer.Write("\\r"); goto IL_156; } goto IL_4E; IL_156:; } this.writer.Write('"'); } private void Unindent() { if (this.pretty_print) { this.indentation -= this.indent_value; } } public override string ToString() { if (this.inst_string_builder == null) { return string.Empty; } return this.inst_string_builder.ToString(); } public void Reset() { this.has_reached_end = false; this.ctx_stack.Clear(); this.context = new WriterContext(); this.ctx_stack.Push(this.context); if (this.inst_string_builder != null) { this.inst_string_builder.Remove(0, this.inst_string_builder.Length); } } public void Write(bool boolean) { this.DoValidation(Condition.Value); this.PutNewline(); this.Put((!boolean) ? "false" : "true"); this.context.ExpectingValue = false; } public void Write(decimal number) { this.DoValidation(Condition.Value); this.PutNewline(); this.Put(Convert.ToString(number, JsonWriter.number_format)); this.context.ExpectingValue = false; } public void Write(double number) { this.DoValidation(Condition.Value); this.PutNewline(); string text = Convert.ToString(number, JsonWriter.number_format); this.Put(text); if (text.IndexOf('.') == -1 && text.IndexOf('E') == -1) { this.writer.Write(".0"); } this.context.ExpectingValue = false; } public void Write(int number) { this.DoValidation(Condition.Value); this.PutNewline(); this.Put(Convert.ToString(number, JsonWriter.number_format)); this.context.ExpectingValue = false; } public void Write(long number) { this.DoValidation(Condition.Value); this.PutNewline(); this.Put(Convert.ToString(number, JsonWriter.number_format)); this.context.ExpectingValue = false; } public void Write(string str) { this.DoValidation(Condition.Value); this.PutNewline(); if (str == null) { this.Put("null"); } else { this.PutString(str); } this.context.ExpectingValue = false; } public void Write(ulong number) { this.DoValidation(Condition.Value); this.PutNewline(); this.Put(Convert.ToString(number, JsonWriter.number_format)); this.context.ExpectingValue = false; } public void WriteArrayEnd() { this.DoValidation(Condition.InArray); this.PutNewline(false); this.ctx_stack.Pop(); if (this.ctx_stack.Count == 1) { this.has_reached_end = true; } else { this.context = this.ctx_stack.Peek(); this.context.ExpectingValue = false; } this.Unindent(); this.Put("]"); } public void WriteArrayStart() { this.DoValidation(Condition.NotAProperty); this.PutNewline(); this.Put("["); this.context = new WriterContext(); this.context.InArray = true; this.ctx_stack.Push(this.context); this.Indent(); } public void WriteObjectEnd() { this.DoValidation(Condition.InObject); this.PutNewline(false); this.ctx_stack.Pop(); if (this.ctx_stack.Count == 1) { this.has_reached_end = true; } else { this.context = this.ctx_stack.Peek(); this.context.ExpectingValue = false; } this.Unindent(); this.Put("}"); } public void WriteObjectStart() { this.DoValidation(Condition.NotAProperty); this.PutNewline(); this.Put("{"); this.context = new WriterContext(); this.context.InObject = true; this.ctx_stack.Push(this.context); this.Indent(); } public void WritePropertyName(string property_name) { this.DoValidation(Condition.Property); this.PutNewline(); this.PutString(property_name); if (this.pretty_print) { if (property_name.Length > this.context.Padding) { this.context.Padding = property_name.Length; } for (int i = this.context.Padding - property_name.Length; i >= 0; i--) { this.writer.Write(' '); } this.writer.Write(": "); } else { this.writer.Write(':'); } this.context.ExpectingValue = true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ExcelDna.Integration; using Qwack.Options; using Qwack.Excel.Services; using Microsoft.Extensions.Logging; using Microsoft.Extensions.DependencyInjection; using Qwack.Options.VolSurfaces; using Qwack.Excel.Utils; using Qwack.Core.Basic; using Qwack.Math; using Qwack.Math.Interpolation; using Qwack.Core.Curves; using Qwack.Dates; using Qwack.Core.Models; using Qwack.Excel.Curves; using Qwack.Core.Cubes; using Qwack.Transport.BasicTypes; namespace Qwack.Excel.Options { public class VolSurfaceFunctions { private const bool Parallel = false; private static readonly ILogger _logger = ContainerStores.GlobalContainer.GetService<ILoggerFactory>()?.CreateLogger<AmericanFunctions>(); [ExcelFunction(Description = "Creates a constant vol surface object", Category = CategoryNames.Volatility, Name = CategoryNames.Volatility + "_" + nameof(CreateConstantVolSurface), IsThreadSafe = Parallel)] public static object CreateConstantVolSurface( [ExcelArgument(Description = "Object name")] string ObjectName, [ExcelArgument(Description = "Asset Id")] string AssetId, [ExcelArgument(Description = "Origin date")] DateTime OriginDate, [ExcelArgument(Description = "Volatility")] double Volatility, [ExcelArgument(Description = "Currency - default USD")] object Currency) { return ExcelHelper.Execute(_logger, () => { var ccyStr = Currency.OptionalExcel("USD"); ContainerStores.SessionContainer.GetService<ICalendarProvider>().Collection.TryGetCalendar(ccyStr, out var ccyCal); var surface = new ConstantVolSurface(OriginDate, Volatility) { Currency = ContainerStores.CurrencyProvider[ccyStr], Name = AssetId ?? ObjectName, AssetId = AssetId ?? ObjectName, }; return ExcelHelper.PushToCache<IVolSurface>(surface, ObjectName); }); } [ExcelFunction(Description = "Creates a grid vol surface object", Category = CategoryNames.Volatility, Name = CategoryNames.Volatility + "_" + nameof(CreateGridVolSurface), IsThreadSafe = Parallel)] public static object CreateGridVolSurface( [ExcelArgument(Description = "Object name")] string ObjectName, [ExcelArgument(Description = "Asset Id")] string AssetId, [ExcelArgument(Description = "Origin date")] DateTime OriginDate, [ExcelArgument(Description = "Strikes")] double[] Strikes, [ExcelArgument(Description = "Expiries")] double[] Expiries, [ExcelArgument(Description = "Volatilities")] double[,] Volatilities, [ExcelArgument(Description = "Stike Type - default Absolute")] object StrikeType, [ExcelArgument(Description = "Stike Interpolation - default Linear")] object StrikeInterpolation, [ExcelArgument(Description = "Time Interpolation - default Linear")] object TimeInterpolation, [ExcelArgument(Description = "Time basis - default ACT365F")] object TimeBasis, [ExcelArgument(Description = "Pillar labels (optional)")] object PillarLabels, [ExcelArgument(Description = "Currency - default USD")] object Currency, [ExcelArgument(Description = "Override spot lag - default none")] object SpotLag) { return ExcelHelper.Execute(_logger, () => { var labels = (PillarLabels is ExcelMissing) ? null : ((object[,])PillarLabels).ObjectRangeToVector<string>(); var ccyStr = Currency.OptionalExcel("USD"); ContainerStores.SessionContainer.GetService<ICalendarProvider>().Collection.TryGetCalendar(ccyStr, out var ccyCal); var stikeType = StrikeType.OptionalExcel<string>("Absolute"); var strikeInterpType = StrikeInterpolation.OptionalExcel<string>("Linear"); var timeInterpType = TimeInterpolation.OptionalExcel<string>("LinearInVariance"); var timeBasis = TimeBasis.OptionalExcel<string>("ACT365F"); var expiries = ExcelHelper.ToDateTimeArray(Expiries); if (!Enum.TryParse(stikeType, out StrikeType sType)) return $"Could not parse strike type - {stikeType}"; if (!Enum.TryParse(strikeInterpType, out Interpolator1DType siType)) return $"Could not parse strike interpolator type - {strikeInterpType}"; if (!Enum.TryParse(timeInterpType, out Interpolator1DType tiType)) return $"Could not parse time interpolator type - {timeInterpType}"; if (!Enum.TryParse(timeBasis, out DayCountBasis basis)) return $"Could not parse time basis type - {timeBasis}"; var surface = new GridVolSurface(OriginDate, Strikes, expiries, Volatilities.SquareToJagged(), sType, siType, tiType, basis, labels) { Currency = ContainerStores.CurrencyProvider[ccyStr], Name = AssetId ?? ObjectName, AssetId = AssetId ?? ObjectName, }; if (SpotLag != null && !(SpotLag is ExcelMissing)) { surface.OverrideSpotLag = new Frequency((string)SpotLag); } return ExcelHelper.PushToCache<IVolSurface>(surface, ObjectName); }); } [ExcelFunction(Description = "Creates a grid vol surface object from RR/BF qoutes", Category = CategoryNames.Volatility, Name = CategoryNames.Volatility + "_" + nameof(CreateRiskyFlyVolSurface), IsThreadSafe = Parallel)] public static object CreateRiskyFlyVolSurface( [ExcelArgument(Description = "Object name")] string ObjectName, [ExcelArgument(Description = "Asset Id")] string AssetId, [ExcelArgument(Description = "Origin date")] DateTime OriginDate, [ExcelArgument(Description = "Wing deltas")] double[] WingDeltas, [ExcelArgument(Description = "Expiries")] double[] Expiries, [ExcelArgument(Description = "ATM Volatilities")] double[] ATMVols, [ExcelArgument(Description = "Risk Reversal quotes")] double[,] Riskies, [ExcelArgument(Description = "Butterfly quotes")] double[,] Flies, [ExcelArgument(Description = "Forwards or price curve object")] object FwdsOrCurve, [ExcelArgument(Description = "ATM vol type - default zero-delta straddle")] object ATMType, [ExcelArgument(Description = "Wing quote type - Simple or Market")] object WingType, [ExcelArgument(Description = "Stike Interpolation - default CubicSpline")] object StrikeInterpolation, [ExcelArgument(Description = "Time Interpolation - default LinearInVariance")] object TimeInterpolation, [ExcelArgument(Description = "Pillar labels (optional)")] object PillarLabels, [ExcelArgument(Description = "Currency - default USD")] object Currency, [ExcelArgument(Description = "Override spot lag - default none")] object SpotLag) { return ExcelHelper.Execute(_logger, () => { var labels = (PillarLabels is ExcelMissing) ? null : ((object[,])PillarLabels).ObjectRangeToVector<string>(); var ccyStr = Currency.OptionalExcel("USD"); ContainerStores.SessionContainer.GetService<ICalendarProvider>().Collection.TryGetCalendar(ccyStr, out var ccyCal); var atmType = ATMType.OptionalExcel("ZeroDeltaStraddle"); var wingType = WingType.OptionalExcel("Simple"); var strikeInterpType = StrikeInterpolation.OptionalExcel("CubicSpline"); var timeInterpType = TimeInterpolation.OptionalExcel("LinearInVariance"); var expiries = ExcelHelper.ToDateTimeArray(Expiries); var rr = Riskies.SquareToJagged<double>(); var bf = Flies.SquareToJagged<double>(); if (!Enum.TryParse(wingType, out WingQuoteType wType)) return $"Could not parse wing quote type - {wingType}"; if (!Enum.TryParse(atmType, out AtmVolType aType)) return $"Could not parse atm quote type - {atmType}"; if (!Enum.TryParse(strikeInterpType, out Interpolator1DType siType)) return $"Could not parse strike interpolator type - {strikeInterpType}"; if (!Enum.TryParse(timeInterpType, out Interpolator1DType tiType)) return $"Could not parse time interpolator type - {timeInterpType}"; double[] fwds = null; if(FwdsOrCurve is ExcelMissing) { fwds = expiries.Select(x => 100.0).ToArray(); } else if (FwdsOrCurve is double) { fwds = new double[] { (double)FwdsOrCurve }; } else if (FwdsOrCurve is string) { if (!ContainerStores.GetObjectCache<IPriceCurve>().TryGetObject(FwdsOrCurve as string, out var curve)) { return $"Could not find fwd curve with name - {FwdsOrCurve as string}"; } fwds = expiries.Select(e => curve.Value.GetPriceForDate(e)).ToArray(); } else { fwds = ((object[,])FwdsOrCurve).ObjectRangeToVector<double>(); } var surface = new RiskyFlySurface(OriginDate, ATMVols, expiries, WingDeltas, rr, bf, fwds, wType, aType, siType, tiType, labels) { Currency = ContainerStores.CurrencyProvider[ccyStr], Name = AssetId ?? ObjectName, AssetId = AssetId ?? ObjectName, }; if(SpotLag!=null && !(SpotLag is ExcelMissing)) { surface.OverrideSpotLag = new Frequency((string)SpotLag); } return ExcelHelper.PushToCache<IVolSurface>(surface, ObjectName); }); } [ExcelFunction(Description = "Creates a SABR vol surface object from RR/BF qoutes", Category = CategoryNames.Volatility, Name = CategoryNames.Volatility + "_" + nameof(CreateSABRVolSurfaceFromRiskyFly), IsThreadSafe = Parallel)] public static object CreateSABRVolSurfaceFromRiskyFly( [ExcelArgument(Description = "Object name")] string ObjectName, [ExcelArgument(Description = "Asset Id")] string AssetId, [ExcelArgument(Description = "Origin date")] DateTime OriginDate, [ExcelArgument(Description = "Wing deltas")] double[] WingDeltas, [ExcelArgument(Description = "Expiries")] double[] Expiries, [ExcelArgument(Description = "ATM Volatilities")] double[] ATMVols, [ExcelArgument(Description = "Risk Reversal quotes")] double[,] Riskies, [ExcelArgument(Description = "Butterfly quotes")] double[,] Flies, [ExcelArgument(Description = "Forwards or price curve object")] object FwdsOrCurve, [ExcelArgument(Description = "ATM vol type - default zero-delta straddle")] object ATMType, [ExcelArgument(Description = "Wing quote type - Simple or Market")] object WingType, [ExcelArgument(Description = "Time Interpolation - default LinearInVariance")] object TimeInterpolation, [ExcelArgument(Description = "Pillar labels (optional)")] object PillarLabels, [ExcelArgument(Description = "Currency - default USD")] object Currency) { return ExcelHelper.Execute(_logger, () => { var labels = (PillarLabels is ExcelMissing) ? null : ((object[,])PillarLabels).ObjectRangeToVector<string>(); var ccyStr = Currency.OptionalExcel("USD"); ContainerStores.SessionContainer.GetService<ICalendarProvider>().Collection.TryGetCalendar(ccyStr, out var ccyCal); var atmType = ATMType.OptionalExcel("ZeroDeltaStraddle"); var wingType = WingType.OptionalExcel("Simple"); var timeInterpType = TimeInterpolation.OptionalExcel("LinearInVariance"); var expiries = ExcelHelper.ToDateTimeArray(Expiries); var rr = Riskies.SquareToJagged<double>(); var bf = Flies.SquareToJagged<double>(); if (!Enum.TryParse(wingType, out WingQuoteType wType)) return $"Could not parse wing quote type - {wingType}"; if (!Enum.TryParse(atmType, out AtmVolType aType)) return $"Could not parse atm quote type - {atmType}"; if (!Enum.TryParse(timeInterpType, out Interpolator1DType tiType)) return $"Could not parse time interpolator type - {timeInterpType}"; double[] fwds = null; if (FwdsOrCurve is double) { fwds = new double[] { (double)FwdsOrCurve }; } else if (FwdsOrCurve is string) { if (!ContainerStores.GetObjectCache<IPriceCurve>().TryGetObject(FwdsOrCurve as string, out var curve)) { return $"Could not find fwd curve with name - {FwdsOrCurve as string}"; } fwds = expiries.Select(e => curve.Value.GetPriceForDate(e)).ToArray(); } else { fwds = ((object[,])FwdsOrCurve).ObjectRangeToVector<double>(); } var surface = new SabrVolSurface(OriginDate, ATMVols, expiries, WingDeltas, rr, bf, fwds, wType, aType, tiType, labels) { Currency = ContainerStores.CurrencyProvider[ccyStr], Name = AssetId ?? ObjectName, AssetId = AssetId ?? ObjectName, }; return ExcelHelper.PushToCache<IVolSurface>(surface, ObjectName); }); } [ExcelFunction(Description = "Creates an inverse pair fx vol surface", Category = CategoryNames.Volatility, Name = CategoryNames.Volatility + "_" + nameof(CreateInvertedFxSurface), IsThreadSafe = Parallel)] public static object CreateInvertedFxSurface( [ExcelArgument(Description = "Object name")] string ObjectName, [ExcelArgument(Description = "Input surface name")] string InputSurface) { return ExcelHelper.Execute(_logger, () => { if (ContainerStores.GetObjectCache<IVolSurface>().TryGetObject(InputSurface, out var volSurface) && volSurface.Value is IATMVolSurface atmSurface) { return ExcelHelper.PushToCache<IVolSurface>(new InverseFxSurface(ObjectName, atmSurface, ContainerStores.CurrencyProvider), ObjectName); } return $"Vol surface {InputSurface} not found in cache or could not be case to ATM Surface"; }); } [ExcelFunction(Description = "Gets a volatility for a delta strike from a vol surface object", Category = CategoryNames.Volatility, Name = CategoryNames.Volatility + "_" + nameof(GetVolForDeltaStrike), IsThreadSafe = Parallel)] public static object GetVolForDeltaStrike( [ExcelArgument(Description = "Object name")] string ObjectName, [ExcelArgument(Description = "Delta Strike")] double DeltaStrike, [ExcelArgument(Description = "Expiry")] DateTime Expiry, [ExcelArgument(Description = "Forward")] double Forward ) { return ExcelHelper.Execute(_logger, () => { if (ContainerStores.GetObjectCache<IVolSurface>().TryGetObject(ObjectName, out var volSurface)) { return volSurface.Value.GetVolForDeltaStrike(DeltaStrike, Expiry, Forward); } return $"Vol surface {ObjectName} not found in cache"; }); } [ExcelFunction(Description = "Gets a volatility for an absolute strike from a vol surface object", Category = CategoryNames.Volatility, Name = CategoryNames.Volatility + "_" + nameof(GetVolForAbsoluteStrike), IsThreadSafe = Parallel)] public static object GetVolForAbsoluteStrike( [ExcelArgument(Description = "Object name")] string ObjectName, [ExcelArgument(Description = "Absolute Strike")] double Strike, [ExcelArgument(Description = "Expiry")] DateTime Expiry, [ExcelArgument(Description = "Forward")] double Forward ) { return ExcelHelper.Execute(_logger, () => { if (ContainerStores.GetObjectCache<IVolSurface>().TryGetObject(ObjectName, out var volSurface)) { return volSurface.Value.GetVolForAbsoluteStrike(Strike, Expiry, Forward); } return $"Vol surface {ObjectName} not found in cache"; }); } [ExcelFunction(Description = "Creates a CDF from a vol surface", Category = CategoryNames.Volatility, Name = CategoryNames.Volatility + "_" + nameof(GenerateCDF), IsThreadSafe = Parallel)] public static object GenerateCDF( [ExcelArgument(Description = "Output interpolator name")] string ObjectName, [ExcelArgument(Description = "Volsurface name")] string VolSurface, [ExcelArgument(Description = "Expiry date")] DateTime ExpiryDate, [ExcelArgument(Description = "Forward")] double Forward, [ExcelArgument(Description = "Number of samples")] int NumberOfSamples) { return ExcelHelper.Execute(_logger, () => { if (ContainerStores.GetObjectCache<IVolSurface>().TryGetObject(VolSurface, out var volSurface)) { var interpolator = volSurface.Value.GenerateCDF(NumberOfSamples, ExpiryDate, Forward); return ExcelHelper.PushToCache(interpolator, ObjectName); } return $"Vol surface {VolSurface} not found in cache"; }); } [ExcelFunction(Description = "Creates a PDF from a vol surface", Category = CategoryNames.Volatility, Name = CategoryNames.Volatility + "_" + nameof(GeneratePDF), IsThreadSafe = Parallel)] public static object GeneratePDF( [ExcelArgument(Description = "Output interpolator name")] string ObjectName, [ExcelArgument(Description = "Volsurface name")] string VolSurface, [ExcelArgument(Description = "Expiry date")] DateTime ExpiryDate, [ExcelArgument(Description = "Forward")] double Forward, [ExcelArgument(Description = "Number of samples")] int NumberOfSamples) { return ExcelHelper.Execute(_logger, () => { if (ContainerStores.GetObjectCache<IVolSurface>().TryGetObject(VolSurface, out var volSurface)) { var interpolator = volSurface.Value.GeneratePDF(NumberOfSamples, ExpiryDate, Forward); return ExcelHelper.PushToCache(interpolator, ObjectName); } return $"Vol surface {VolSurface} not found in cache"; }); } [ExcelFunction(Description = "Creates a PDF from a smile interpolator", Category = CategoryNames.Volatility, Name = CategoryNames.Volatility + "_" + nameof(GeneratePDFFromInterpolator), IsThreadSafe = Parallel)] public static object GeneratePDFFromInterpolator( [ExcelArgument(Description = "Output interpolator name")] string ObjectName, [ExcelArgument(Description = "Input interpolator name")] string VolInterpolator, [ExcelArgument(Description = "Expiry as year fraction")] double ExpiryYearFraction, [ExcelArgument(Description = "Forward")] double Forward, [ExcelArgument(Description = "Number of samples")] int NumberOfSamples) { return ExcelHelper.Execute(_logger, () => { if (ContainerStores.GetObjectCache<IInterpolator1D>().TryGetObject(VolInterpolator, out var smile)) { var interpolator = smile.Value.GeneratePDF(NumberOfSamples, ExpiryYearFraction, Forward); return ExcelHelper.PushToCache(interpolator, ObjectName); } return $"Interpolator {VolInterpolator} not found in cache"; }); } [ExcelFunction(Description = "Creates a CDF from a smile interpolator", Category = CategoryNames.Volatility, Name = CategoryNames.Volatility + "_" + nameof(GenerateCDFFromInterpolator), IsThreadSafe = Parallel)] public static object GenerateCDFFromInterpolator( [ExcelArgument(Description = "Output interpolator name")] string ObjectName, [ExcelArgument(Description = "Input interpolator name")] string VolInterpolator, [ExcelArgument(Description = "Expiry as year fraction")] double ExpiryYearFraction, [ExcelArgument(Description = "Forward")] double Forward, [ExcelArgument(Description = "Number of samples")] int NumberOfSamples) { return ExcelHelper.Execute(_logger, () => { if (ContainerStores.GetObjectCache<IInterpolator1D>().TryGetObject(VolInterpolator, out var smile)) { var interpolator = smile.Value.GenerateCDF(NumberOfSamples, ExpiryYearFraction, Forward); return ExcelHelper.PushToCache(interpolator, ObjectName); } return $"Interpolator {VolInterpolator} not found in cache"; }); } [ExcelFunction(Description = "Creates a composite smile from a vol surface and an fx vol surface", Category = CategoryNames.Volatility, Name = CategoryNames.Volatility + "_" + nameof(GenerateCompoSmile), IsThreadSafe = Parallel)] public static object GenerateCompoSmile( [ExcelArgument(Description = "Output interpolator name")] string ObjectName, [ExcelArgument(Description = "Volsurface name")] string VolSurface, [ExcelArgument(Description = "Fx Volsurface name")] string FxVolSurface, [ExcelArgument(Description = "Expiry date")] DateTime ExpiryDate, [ExcelArgument(Description = "Forward")] double Forward, [ExcelArgument(Description = "Fx Forward")] double FxForward, [ExcelArgument(Description = "Correlation")] double Correlation, [ExcelArgument(Description = "Number of samples")] int NumberOfSamples) { return ExcelHelper.Execute(_logger, () => { if (ContainerStores.GetObjectCache<IVolSurface>().TryGetObject(VolSurface, out var volSurface)) { if (ContainerStores.GetObjectCache<IVolSurface>().TryGetObject(FxVolSurface, out var volSurfaceFx)) { var interpolator = volSurface.Value.GenerateCompositeSmile(volSurfaceFx.Value, NumberOfSamples, ExpiryDate, Forward, FxForward, Correlation); return ExcelHelper.PushToCache(interpolator, ObjectName); } else return $"Fx vol surface {FxVolSurface} not found in cache"; } else return $"Vol surface {VolSurface} not found in cache"; }); } [ExcelFunction(Description = "Creates a composite surface from a vol surface and an fx vol surface", Category = CategoryNames.Volatility, Name = CategoryNames.Volatility + "_" + nameof(GenerateCompoSurface), IsThreadSafe = Parallel)] public static object GenerateCompoSurface( [ExcelArgument(Description = "Output surface name")] string ObjectName, [ExcelArgument(Description = "Asset-fx model name")] string AssetFxModel, [ExcelArgument(Description = "AssetId")] string AssetId, [ExcelArgument(Description = "FxPair")] string FxPair, [ExcelArgument(Description = "Correlation")] double Correlation, [ExcelArgument(Description = "Number of samples")] int NumberOfSamples) { return ExcelHelper.Execute(_logger, () => { if (ContainerStores.GetObjectCache<IAssetFxModel>().TryGetObject(AssetFxModel, out var model)) { if (!model.Value.FundingModel.VolSurfaces.ContainsKey(FxPair)) throw new Exception($"No vol surface found in model for fx pair {FxPair}"); model.Value.GetVolSurface(AssetId); var surface = model.Value.GenerateCompositeSurface(AssetId, FxPair, NumberOfSamples, Correlation, true); return ExcelHelper.PushToCache<IVolSurface>(surface, ObjectName); } else return $"Model {AssetFxModel} not found in cache"; }); } [ExcelFunction(Description = "Turns a risky/fly surface into a cube of quotes", Category = CategoryNames.Volatility, Name = CategoryNames.Volatility + "_" + nameof(SurfaceToCube), IsThreadSafe = Parallel)] public static object SurfaceToCube( [ExcelArgument(Description = "Surface name")] string SurfaceName, [ExcelArgument(Description = "Output cube name")] string CubeName) { return ExcelHelper.Execute(_logger, () => { var surface = ContainerStores.GetObjectCache<IVolSurface>().GetObjectOrThrow(SurfaceName, $"Vol surface {SurfaceName} not found"); var rrbf = (RiskyFlySurface)surface.Value; var cube = rrbf.ToCube(); return RiskFunctions.PushCubeToCache(cube, CubeName); }); } [ExcelFunction(Description = "Reconstructs a risky/fly surface from a cube of quotes", Category = CategoryNames.Volatility, Name = CategoryNames.Volatility + "_" + nameof(SurfaceFromCube), IsThreadSafe = Parallel)] public static object SurfaceFromCube( [ExcelArgument(Description = "Output Surface name")] string SurfaceName, [ExcelArgument(Description = "Cube name")] string CubeName, [ExcelArgument(Description = "Build date")] DateTime BuildDate, [ExcelArgument(Description = "Currency")] string Currency, [ExcelArgument(Description = "Asset Id")] string AssetId, [ExcelArgument(Description = "Stike Interpolation - default GaussianKernel")] object StrikeInterpolation, [ExcelArgument(Description = "Time Interpolation - default LinearInVariance")] object TimeInterpolation) { return ExcelHelper.Execute(_logger, () => { var cube = ContainerStores.GetObjectCache<ICube>().GetObjectOrThrow(CubeName, $"Cube {CubeName} not found"); var strikeInterpType = StrikeInterpolation.OptionalExcel("GaussianKernel"); var timeInterpType = TimeInterpolation.OptionalExcel("LinearInVariance"); if (!Enum.TryParse(strikeInterpType, out Interpolator1DType siType)) return $"Could not parse strike interpolator type - {strikeInterpType}"; if (!Enum.TryParse(timeInterpType, out Interpolator1DType tiType)) return $"Could not parse time interpolator type - {timeInterpType}"; var rrbf = RiskyFlySurface.FromCube(cube.Value, BuildDate, siType, tiType); rrbf.AssetId = AssetId; rrbf.Name = AssetId; if (!string.IsNullOrWhiteSpace(Currency)) rrbf.Currency = ContainerStores.CurrencyProvider.GetCurrency(Currency); return ExcelHelper.PushToCache<IVolSurface>(rrbf, SurfaceName); }); } [ExcelFunction(Description = "Extracts quotes from a risky/fly surface", Category = CategoryNames.Volatility, Name = CategoryNames.Volatility + "_" + nameof(SurfaceToQuotes), IsThreadSafe = Parallel)] public static object SurfaceToQuotes( [ExcelArgument(Description = "Surface name")] string SurfaceName) { return ExcelHelper.Execute(_logger, () => { var surface = ContainerStores.GetObjectCache<IVolSurface>().GetObjectOrThrow(SurfaceName, $"Vol surface {SurfaceName} not found"); var rrbf = (RiskyFlySurface)surface.Value; return rrbf.DisplayQuotes(); }); } } }
// 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.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Roslyn.Utilities; using Microsoft.CodeAnalysis.GeneratedCodeRecognition; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal abstract partial class AbstractCodeModelService : ICodeModelService { private readonly ConditionalWeakTable<SyntaxTree, IBidirectionalMap<SyntaxNodeKey, SyntaxNode>> _treeToNodeKeyMaps = new ConditionalWeakTable<SyntaxTree, IBidirectionalMap<SyntaxNodeKey, SyntaxNode>>(); protected readonly ISyntaxFactsService SyntaxFactsService; private readonly IEditorOptionsFactoryService _editorOptionsFactoryService; private readonly AbstractNodeNameGenerator _nodeNameGenerator; private readonly AbstractNodeLocator _nodeLocator; private readonly AbstractCodeModelEventCollector _eventCollector; private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices; private readonly IFormattingRule _lineAdjustmentFormattingRule; private readonly IFormattingRule _endRegionFormattingRule; protected AbstractCodeModelService( HostLanguageServices languageServiceProvider, IEditorOptionsFactoryService editorOptionsFactoryService, IEnumerable<IRefactorNotifyService> refactorNotifyServices, IFormattingRule lineAdjustmentFormattingRule, IFormattingRule endRegionFormattingRule) { Debug.Assert(languageServiceProvider != null); Debug.Assert(editorOptionsFactoryService != null); this.SyntaxFactsService = languageServiceProvider.GetService<ISyntaxFactsService>(); _editorOptionsFactoryService = editorOptionsFactoryService; _lineAdjustmentFormattingRule = lineAdjustmentFormattingRule; _endRegionFormattingRule = endRegionFormattingRule; _refactorNotifyServices = refactorNotifyServices; _nodeNameGenerator = CreateNodeNameGenerator(); _nodeLocator = CreateNodeLocator(); _eventCollector = CreateCodeModelEventCollector(); } protected string GetNewLineCharacter(SourceText text) { return _editorOptionsFactoryService.GetEditorOptions(text).GetNewLineCharacter(); } protected int GetTabSize(SourceText text) { var snapshot = text.FindCorrespondingEditorTextSnapshot(); return GetTabSize(snapshot); } protected int GetTabSize(ITextSnapshot snapshot) { if (snapshot == null) { throw new ArgumentNullException(nameof(snapshot)); } var textBuffer = snapshot.TextBuffer; return _editorOptionsFactoryService.GetOptions(textBuffer).GetTabSize(); } protected SyntaxToken GetTokenWithoutAnnotation(SyntaxToken current, Func<SyntaxToken, SyntaxToken> nextTokenGetter) { while (current.ContainsAnnotations) { current = nextTokenGetter(current); } return current; } protected TextSpan GetEncompassingSpan(SyntaxNode root, SyntaxToken startToken, SyntaxToken endToken) { var startPosition = startToken.SpanStart; var endPosition = endToken.RawKind == 0 ? root.Span.End : endToken.Span.End; return TextSpan.FromBounds(startPosition, endPosition); } private IBidirectionalMap<SyntaxNodeKey, SyntaxNode> BuildNodeKeyMap(SyntaxTree syntaxTree) { var nameOrdinalMap = new Dictionary<string, int>(); var nodeKeyMap = BidirectionalMap<SyntaxNodeKey, SyntaxNode>.Empty; foreach (var node in GetFlattenedMemberNodes(syntaxTree)) { var name = _nodeNameGenerator.GenerateName(node); if (!nameOrdinalMap.TryGetValue(name, out var ordinal)) { ordinal = 0; } nameOrdinalMap[name] = ++ordinal; var key = new SyntaxNodeKey(name, ordinal); nodeKeyMap = nodeKeyMap.Add(key, node); } return nodeKeyMap; } private IBidirectionalMap<SyntaxNodeKey, SyntaxNode> GetNodeKeyMap(SyntaxTree syntaxTree) { return _treeToNodeKeyMaps.GetValue(syntaxTree, BuildNodeKeyMap); } public SyntaxNodeKey GetNodeKey(SyntaxNode node) { var nodeKey = TryGetNodeKey(node); if (nodeKey.IsEmpty) { throw new ArgumentException(); } return nodeKey; } public SyntaxNodeKey TryGetNodeKey(SyntaxNode node) { var nodeKeyMap = GetNodeKeyMap(node.SyntaxTree); if (!nodeKeyMap.TryGetKey(node, out var nodeKey)) { return SyntaxNodeKey.Empty; } return nodeKey; } public SyntaxNode LookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree) { var nodeKeyMap = GetNodeKeyMap(syntaxTree); if (!nodeKeyMap.TryGetValue(nodeKey, out var node)) { throw new ArgumentException(); } return node; } public bool TryLookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree, out SyntaxNode node) { var nodeKeyMap = GetNodeKeyMap(syntaxTree); return nodeKeyMap.TryGetValue(nodeKey, out node); } public abstract bool MatchesScope(SyntaxNode node, EnvDTE.vsCMElement scope); public abstract IEnumerable<SyntaxNode> GetOptionNodes(SyntaxNode parent); public abstract IEnumerable<SyntaxNode> GetImportNodes(SyntaxNode parent); public abstract IEnumerable<SyntaxNode> GetAttributeNodes(SyntaxNode parent); public abstract IEnumerable<SyntaxNode> GetAttributeArgumentNodes(SyntaxNode parent); public abstract IEnumerable<SyntaxNode> GetInheritsNodes(SyntaxNode parent); public abstract IEnumerable<SyntaxNode> GetImplementsNodes(SyntaxNode parent); public abstract IEnumerable<SyntaxNode> GetParameterNodes(SyntaxNode parent); protected IEnumerable<SyntaxNode> GetFlattenedMemberNodes(SyntaxTree syntaxTree) { return GetMemberNodes(syntaxTree.GetRoot(), includeSelf: true, recursive: true, logicalFields: true, onlySupportedNodes: true); } protected IEnumerable<SyntaxNode> GetLogicalMemberNodes(SyntaxNode container) { return GetMemberNodes(container, includeSelf: false, recursive: false, logicalFields: true, onlySupportedNodes: false); } public IEnumerable<SyntaxNode> GetLogicalSupportedMemberNodes(SyntaxNode container) { return GetMemberNodes(container, includeSelf: false, recursive: false, logicalFields: true, onlySupportedNodes: true); } /// <summary> /// Retrieves the members of a specified <paramref name="container"/> node. The members that are /// returned can be controlled by passing various parameters. /// </summary> /// <param name="container">The <see cref="SyntaxNode"/> from which to retrieve members.</param> /// <param name="includeSelf">If true, the container is returned as well.</param> /// <param name="recursive">If true, members are recursed to return descendant members as well /// as immediate children. For example, a namespace would return the namespaces and types within. /// However, if <paramref name="recursive"/> is true, members with the namespaces and types would /// also be returned.</param> /// <param name="logicalFields">If true, field declarations are broken into their respective declarators. /// For example, the field "int x, y" would return two declarators, one for x and one for y in place /// of the field.</param> /// <param name="onlySupportedNodes">If true, only members supported by Code Model are returned.</param> public abstract IEnumerable<SyntaxNode> GetMemberNodes(SyntaxNode container, bool includeSelf, bool recursive, bool logicalFields, bool onlySupportedNodes); public abstract string Language { get; } public abstract string AssemblyAttributeString { get; } public EnvDTE.CodeElement CreateExternalCodeElement(CodeModelState state, ProjectId projectId, ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Event: return (EnvDTE.CodeElement)ExternalCodeEvent.Create(state, projectId, (IEventSymbol)symbol); case SymbolKind.Field: return (EnvDTE.CodeElement)ExternalCodeVariable.Create(state, projectId, (IFieldSymbol)symbol); case SymbolKind.Method: return (EnvDTE.CodeElement)ExternalCodeFunction.Create(state, projectId, (IMethodSymbol)symbol); case SymbolKind.Namespace: return (EnvDTE.CodeElement)ExternalCodeNamespace.Create(state, projectId, (INamespaceSymbol)symbol); case SymbolKind.NamedType: var namedType = (INamedTypeSymbol)symbol; switch (namedType.TypeKind) { case TypeKind.Class: case TypeKind.Module: return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, namedType); case TypeKind.Delegate: return (EnvDTE.CodeElement)ExternalCodeDelegate.Create(state, projectId, namedType); case TypeKind.Enum: return (EnvDTE.CodeElement)ExternalCodeEnum.Create(state, projectId, namedType); case TypeKind.Interface: return (EnvDTE.CodeElement)ExternalCodeInterface.Create(state, projectId, namedType); case TypeKind.Struct: return (EnvDTE.CodeElement)ExternalCodeStruct.Create(state, projectId, namedType); default: throw Exceptions.ThrowEFail(); } case SymbolKind.Property: var propertySymbol = (IPropertySymbol)symbol; return propertySymbol.IsWithEvents ? (EnvDTE.CodeElement)ExternalCodeVariable.Create(state, projectId, propertySymbol) : (EnvDTE.CodeElement)ExternalCodeProperty.Create(state, projectId, (IPropertySymbol)symbol); default: throw Exceptions.ThrowEFail(); } } /// <summary> /// Do not use this method directly! Instead, go through <see cref="FileCodeModel.GetOrCreateCodeElement{T}(SyntaxNode)"/> /// </summary> public abstract EnvDTE.CodeElement CreateInternalCodeElement( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node); public EnvDTE.CodeElement CreateCodeType(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol) { if (typeSymbol.TypeKind == TypeKind.Pointer || typeSymbol.TypeKind == TypeKind.TypeParameter || typeSymbol.TypeKind == TypeKind.Submission) { throw Exceptions.ThrowEFail(); } if (typeSymbol.TypeKind == TypeKind.Error || typeSymbol.TypeKind == TypeKind.Unknown) { return ExternalCodeUnknown.Create(state, projectId, typeSymbol); } var project = state.Workspace.CurrentSolution.GetProject(projectId); if (project == null) { throw Exceptions.ThrowEFail(); } if (typeSymbol.TypeKind == TypeKind.Dynamic) { var obj = project.GetCompilationAsync().Result.GetSpecialType(SpecialType.System_Object); return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, obj); } if (TryGetElementFromSource(state, project, typeSymbol, out var element)) { return element; } EnvDTE.vsCMElement elementKind = GetElementKind(typeSymbol); switch (elementKind) { case EnvDTE.vsCMElement.vsCMElementClass: case EnvDTE.vsCMElement.vsCMElementModule: return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, typeSymbol); case EnvDTE.vsCMElement.vsCMElementInterface: return (EnvDTE.CodeElement)ExternalCodeInterface.Create(state, projectId, typeSymbol); case EnvDTE.vsCMElement.vsCMElementDelegate: return (EnvDTE.CodeElement)ExternalCodeDelegate.Create(state, projectId, typeSymbol); case EnvDTE.vsCMElement.vsCMElementEnum: return (EnvDTE.CodeElement)ExternalCodeEnum.Create(state, projectId, typeSymbol); case EnvDTE.vsCMElement.vsCMElementStruct: return (EnvDTE.CodeElement)ExternalCodeStruct.Create(state, projectId, typeSymbol); default: Debug.Fail("Unsupported element kind: " + elementKind); throw Exceptions.ThrowEInvalidArg(); } } public abstract EnvDTE.CodeTypeRef CreateCodeTypeRef(CodeModelState state, ProjectId projectId, object type); public abstract EnvDTE.vsCMTypeRef GetTypeKindForCodeTypeRef(ITypeSymbol typeSymbol); public abstract string GetAsFullNameForCodeTypeRef(ITypeSymbol typeSymbol); public abstract string GetAsStringForCodeTypeRef(ITypeSymbol typeSymbol); public abstract bool IsParameterNode(SyntaxNode node); public abstract bool IsAttributeNode(SyntaxNode node); public abstract bool IsAttributeArgumentNode(SyntaxNode node); public abstract bool IsOptionNode(SyntaxNode node); public abstract bool IsImportNode(SyntaxNode node); public ISymbol ResolveSymbol(Workspace workspace, ProjectId projectId, SymbolKey symbolId) { var project = workspace.CurrentSolution.GetProject(projectId); if (project == null) { throw Exceptions.ThrowEFail(); } return symbolId.Resolve(project.GetCompilationAsync().Result).Symbol; } protected EnvDTE.CodeFunction CreateInternalCodeAccessorFunction(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node) { SyntaxNode parentNode = node .Ancestors() .FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty); if (parentNode == null) { throw new InvalidOperationException(); } var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode); var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent); var accessorKind = GetAccessorKind(node); return CodeAccessorFunction.Create(state, parentObj, accessorKind); } protected EnvDTE.CodeAttribute CreateInternalCodeAttribute(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node) { var parentNode = GetEffectiveParentForAttribute(node); AbstractCodeElement parentObject; if (IsParameterNode(parentNode)) { var parentElement = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode); parentObject = ComAggregate.GetManagedObject<AbstractCodeElement>(parentElement); } else { var nodeKey = parentNode.AncestorsAndSelf() .Select(n => TryGetNodeKey(n)) .FirstOrDefault(nk => nk != SyntaxNodeKey.Empty); if (nodeKey == SyntaxNodeKey.Empty) { // This is an assembly-level attribute. parentNode = fileCodeModel.GetSyntaxRoot(); parentObject = null; } else { parentNode = fileCodeModel.LookupNode(nodeKey); var parentElement = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode); parentObject = ComAggregate.GetManagedObject<AbstractCodeElement>(parentElement); } } GetAttributeNameAndOrdinal(parentNode, node, out var name, out var ordinal); return CodeAttribute.Create(state, fileCodeModel, parentObject, name, ordinal); } protected EnvDTE80.CodeImport CreateInternalCodeImport(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node) { GetImportParentAndName(node, out var parentNode, out var name); AbstractCodeElement parentObj = null; if (parentNode != null) { var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode); parentObj = ComAggregate.GetManagedObject<AbstractCodeElement>(parent); } return CodeImport.Create(state, fileCodeModel, parentObj, name); } protected EnvDTE.CodeParameter CreateInternalCodeParameter(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node) { SyntaxNode parentNode = node .Ancestors() .FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty); if (parentNode == null) { throw new InvalidOperationException(); } string name = GetParameterName(node); var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode); var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent); return CodeParameter.Create(state, parentObj, name); } protected EnvDTE80.CodeElement2 CreateInternalCodeOptionStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node) { GetOptionNameAndOrdinal(node.Parent, node, out var name, out var ordinal); return CodeOptionsStatement.Create(state, fileCodeModel, name, ordinal); } protected EnvDTE80.CodeElement2 CreateInternalCodeInheritsStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node) { SyntaxNode parentNode = node .Ancestors() .FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty); if (parentNode == null) { throw new InvalidOperationException(); } GetInheritsNamespaceAndOrdinal(parentNode, node, out var namespaceName, out var ordinal); var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode); var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent); return CodeInheritsStatement.Create(state, parentObj, namespaceName, ordinal); } protected EnvDTE80.CodeElement2 CreateInternalCodeImplementsStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node) { SyntaxNode parentNode = node .Ancestors() .FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty); if (parentNode == null) { throw new InvalidOperationException(); } GetImplementsNamespaceAndOrdinal(parentNode, node, out var namespaceName, out var ordinal); var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode); var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent); return CodeImplementsStatement.Create(state, parentObj, namespaceName, ordinal); } protected EnvDTE80.CodeAttributeArgument CreateInternalCodeAttributeArgument(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node) { GetAttributeArgumentParentAndIndex(node, out var attributeNode, out var index); var codeAttribute = CreateInternalCodeAttribute(state, fileCodeModel, attributeNode); var codeAttributeObj = ComAggregate.GetManagedObject<CodeAttribute>(codeAttribute); return CodeAttributeArgument.Create(state, codeAttributeObj, index); } public abstract EnvDTE.CodeElement CreateUnknownCodeElement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node); public abstract EnvDTE.CodeElement CreateUnknownRootNamespaceCodeElement(CodeModelState state, FileCodeModel fileCodeModel); public abstract string GetUnescapedName(string name); public abstract string GetName(SyntaxNode node); public abstract SyntaxNode GetNodeWithName(SyntaxNode node); public abstract SyntaxNode SetName(SyntaxNode node, string name); public abstract string GetFullName(SyntaxNode node, SemanticModel semanticModel); public abstract string GetFullyQualifiedName(string name, int position, SemanticModel semanticModel); public void Rename(ISymbol symbol, string newName, Solution solution) { // TODO: (tomescht) make this testable through unit tests. // Right now we have to go through the project system to find all // the outstanding CodeElements which might be affected by the // rename. This is silly. This functionality should be moved down // into the service layer. var workspace = solution.Workspace as VisualStudioWorkspaceImpl; if (workspace == null) { throw Exceptions.ThrowEFail(); } // Save the node keys. var nodeKeyValidation = new NodeKeyValidation(); foreach (var project in workspace.DeferredState.ProjectTracker.ImmutableProjects) { nodeKeyValidation.AddProject(project); } // Rename symbol. var newSolution = Renamer.RenameSymbolAsync(solution, symbol, newName, solution.Options).WaitAndGetResult_CodeModel(CancellationToken.None); var changedDocuments = newSolution.GetChangedDocuments(solution); // Notify third parties of the coming rename operation and let exceptions propagate out _refactorNotifyServices.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true); // Update the workspace. if (!workspace.TryApplyChanges(newSolution)) { throw Exceptions.ThrowEFail(); } // Notify third parties of the completed rename operation and let exceptions propagate out _refactorNotifyServices.TryOnAfterGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true); RenameTrackingDismisser.DismissRenameTracking(workspace, changedDocuments); // Update the node keys. nodeKeyValidation.RestoreKeys(); } public abstract bool IsValidExternalSymbol(ISymbol symbol); public abstract string GetExternalSymbolName(ISymbol symbol); public abstract string GetExternalSymbolFullName(ISymbol symbol); public VirtualTreePoint? GetStartPoint(SyntaxNode node, EnvDTE.vsCMPart? part) { return _nodeLocator.GetStartPoint(node, part); } public VirtualTreePoint? GetEndPoint(SyntaxNode node, EnvDTE.vsCMPart? part) { return _nodeLocator.GetEndPoint(node, part); } public abstract EnvDTE.vsCMAccess GetAccess(ISymbol symbol); public abstract EnvDTE.vsCMAccess GetAccess(SyntaxNode node); public abstract SyntaxNode GetNodeWithModifiers(SyntaxNode node); public abstract SyntaxNode GetNodeWithType(SyntaxNode node); public abstract SyntaxNode GetNodeWithInitializer(SyntaxNode node); public abstract SyntaxNode SetAccess(SyntaxNode node, EnvDTE.vsCMAccess access); public abstract EnvDTE.vsCMElement GetElementKind(SyntaxNode node); protected EnvDTE.vsCMElement GetElementKind(ITypeSymbol typeSymbol) { switch (typeSymbol.TypeKind) { case TypeKind.Array: case TypeKind.Class: return EnvDTE.vsCMElement.vsCMElementClass; case TypeKind.Interface: return EnvDTE.vsCMElement.vsCMElementInterface; case TypeKind.Struct: return EnvDTE.vsCMElement.vsCMElementStruct; case TypeKind.Enum: return EnvDTE.vsCMElement.vsCMElementEnum; case TypeKind.Delegate: return EnvDTE.vsCMElement.vsCMElementDelegate; case TypeKind.Module: return EnvDTE.vsCMElement.vsCMElementModule; default: Debug.Fail("Unexpected TypeKind: " + typeSymbol.TypeKind); throw Exceptions.ThrowEInvalidArg(); } } protected bool TryGetElementFromSource( CodeModelState state, Project project, ITypeSymbol typeSymbol, out EnvDTE.CodeElement element) { element = null; if (!typeSymbol.IsDefinition) { return false; } // Here's the strategy for determine what source file we'd try to return an element from. // 1. Prefer source files that we don't heuristically flag as generated code. // 2. If all of the source files are generated code, pick the first one. Compilation compilation = null; Tuple<DocumentId, Location> generatedCode = null; DocumentId chosenDocumentId = null; Location chosenLocation = null; foreach (var location in typeSymbol.Locations) { if (location.IsInSource) { compilation = compilation ?? project.GetCompilationAsync(CancellationToken.None).WaitAndGetResult_CodeModel(CancellationToken.None); if (compilation.ContainsSyntaxTree(location.SourceTree)) { var document = project.GetDocument(location.SourceTree); if (!document.IsGeneratedCode(CancellationToken.None)) { chosenLocation = location; chosenDocumentId = document.Id; break; } else { generatedCode = generatedCode ?? Tuple.Create(document.Id, location); } } } } if (chosenDocumentId == null && generatedCode != null) { chosenDocumentId = generatedCode.Item1; chosenLocation = generatedCode.Item2; } if (chosenDocumentId != null) { var fileCodeModel = state.Workspace.GetFileCodeModel(chosenDocumentId); if (fileCodeModel != null) { var underlyingFileCodeModel = ComAggregate.GetManagedObject<FileCodeModel>(fileCodeModel); element = underlyingFileCodeModel.CodeElementFromPosition(chosenLocation.SourceSpan.Start, GetElementKind(typeSymbol)); return element != null; } } return false; } public abstract bool IsExpressionBodiedProperty(SyntaxNode node); public abstract bool IsAccessorNode(SyntaxNode node); public abstract MethodKind GetAccessorKind(SyntaxNode node); public abstract bool TryGetAccessorNode(SyntaxNode parentNode, MethodKind kind, out SyntaxNode accessorNode); public abstract bool TryGetAutoPropertyExpressionBody(SyntaxNode parentNode, out SyntaxNode accessorNode); public abstract bool TryGetParameterNode(SyntaxNode parentNode, string name, out SyntaxNode parameterNode); public abstract bool TryGetImportNode(SyntaxNode parentNode, string dottedName, out SyntaxNode importNode); public abstract bool TryGetOptionNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode optionNode); public abstract bool TryGetInheritsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode inheritsNode); public abstract bool TryGetImplementsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode implementsNode); public abstract bool TryGetAttributeNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode attributeNode); public abstract bool TryGetAttributeArgumentNode(SyntaxNode attributeNode, int index, out SyntaxNode attributeArgumentNode); public abstract void GetOptionNameAndOrdinal(SyntaxNode parentNode, SyntaxNode optionNode, out string name, out int ordinal); public abstract void GetInheritsNamespaceAndOrdinal(SyntaxNode inheritsNode, SyntaxNode optionNode, out string namespaceName, out int ordinal); public abstract void GetImplementsNamespaceAndOrdinal(SyntaxNode implementsNode, SyntaxNode optionNode, out string namespaceName, out int ordinal); public abstract void GetAttributeNameAndOrdinal(SyntaxNode parentNode, SyntaxNode attributeNode, out string name, out int ordinal); public abstract SyntaxNode GetAttributeTargetNode(SyntaxNode attributeNode); public abstract string GetAttributeTarget(SyntaxNode attributeNode); public abstract string GetAttributeValue(SyntaxNode attributeNode); public abstract SyntaxNode SetAttributeTarget(SyntaxNode attributeNode, string value); public abstract SyntaxNode SetAttributeValue(SyntaxNode attributeNode, string value); public abstract SyntaxNode GetNodeWithAttributes(SyntaxNode node); public abstract SyntaxNode GetEffectiveParentForAttribute(SyntaxNode node); public abstract SyntaxNode CreateAttributeNode(string name, string value, string target = null); public abstract void GetAttributeArgumentParentAndIndex(SyntaxNode attributeArgumentNode, out SyntaxNode attributeNode, out int index); public abstract SyntaxNode CreateAttributeArgumentNode(string name, string value); public abstract string GetAttributeArgumentValue(SyntaxNode attributeArgumentNode); public abstract string GetImportAlias(SyntaxNode node); public abstract string GetImportNamespaceOrType(SyntaxNode node); public abstract void GetImportParentAndName(SyntaxNode importNode, out SyntaxNode namespaceNode, out string name); public abstract SyntaxNode CreateImportNode(string name, string alias = null); public abstract string GetParameterName(SyntaxNode node); public virtual string GetParameterFullName(SyntaxNode node) { return GetParameterName(node); } public abstract EnvDTE80.vsCMParameterKind GetParameterKind(SyntaxNode node); public abstract SyntaxNode SetParameterKind(SyntaxNode node, EnvDTE80.vsCMParameterKind kind); public abstract EnvDTE80.vsCMParameterKind UpdateParameterKind(EnvDTE80.vsCMParameterKind parameterKind, PARAMETER_PASSING_MODE passingMode); public abstract SyntaxNode CreateParameterNode(string name, string type); public abstract EnvDTE.vsCMFunction ValidateFunctionKind(SyntaxNode containerNode, EnvDTE.vsCMFunction kind, string name); public abstract bool SupportsEventThrower { get; } public abstract bool GetCanOverride(SyntaxNode memberNode); public abstract SyntaxNode SetCanOverride(SyntaxNode memberNode, bool value); public abstract EnvDTE80.vsCMClassKind GetClassKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol); public abstract SyntaxNode SetClassKind(SyntaxNode typeNode, EnvDTE80.vsCMClassKind kind); public abstract string GetComment(SyntaxNode node); public abstract SyntaxNode SetComment(SyntaxNode node, string value); public abstract EnvDTE80.vsCMConstKind GetConstKind(SyntaxNode variableNode); public abstract SyntaxNode SetConstKind(SyntaxNode variableNode, EnvDTE80.vsCMConstKind kind); public abstract EnvDTE80.vsCMDataTypeKind GetDataTypeKind(SyntaxNode typeNode, INamedTypeSymbol symbol); public abstract SyntaxNode SetDataTypeKind(SyntaxNode typeNode, EnvDTE80.vsCMDataTypeKind kind); public abstract string GetDocComment(SyntaxNode node); public abstract SyntaxNode SetDocComment(SyntaxNode node, string value); public abstract EnvDTE.vsCMFunction GetFunctionKind(IMethodSymbol symbol); public abstract EnvDTE80.vsCMInheritanceKind GetInheritanceKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol); public abstract SyntaxNode SetInheritanceKind(SyntaxNode typeNode, EnvDTE80.vsCMInheritanceKind kind); public abstract bool GetIsAbstract(SyntaxNode memberNode, ISymbol symbol); public abstract SyntaxNode SetIsAbstract(SyntaxNode memberNode, bool value); public abstract bool GetIsConstant(SyntaxNode variableNode); public abstract SyntaxNode SetIsConstant(SyntaxNode variableNode, bool value); public abstract bool GetIsDefault(SyntaxNode propertyNode); public abstract SyntaxNode SetIsDefault(SyntaxNode propertyNode, bool value); public abstract bool GetIsGeneric(SyntaxNode memberNode); public abstract bool GetIsPropertyStyleEvent(SyntaxNode eventNode); public abstract bool GetIsShared(SyntaxNode memberNode, ISymbol symbol); public abstract SyntaxNode SetIsShared(SyntaxNode memberNode, bool value); public abstract bool GetMustImplement(SyntaxNode memberNode); public abstract SyntaxNode SetMustImplement(SyntaxNode memberNode, bool value); public abstract EnvDTE80.vsCMOverrideKind GetOverrideKind(SyntaxNode memberNode); public abstract SyntaxNode SetOverrideKind(SyntaxNode memberNode, EnvDTE80.vsCMOverrideKind kind); public abstract EnvDTE80.vsCMPropertyKind GetReadWrite(SyntaxNode memberNode); public abstract SyntaxNode SetType(SyntaxNode node, ITypeSymbol typeSymbol); public abstract Document Delete(Document document, SyntaxNode node); public abstract string GetMethodXml(SyntaxNode node, SemanticModel semanticModel); public abstract string GetInitExpression(SyntaxNode node); public abstract SyntaxNode AddInitExpression(SyntaxNode node, string value); public abstract CodeGenerationDestination GetDestination(SyntaxNode containerNode); protected abstract Accessibility GetDefaultAccessibility(SymbolKind targetSymbolKind, CodeGenerationDestination destination); public Accessibility GetAccessibility(EnvDTE.vsCMAccess access, SymbolKind targetSymbolKind, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified) { // Note: Some EnvDTE.vsCMAccess members aren't "bitwise-mutually-exclusive" // Specifically, vsCMAccessProjectOrProtected (12) is a combination of vsCMAccessProject (4) and vsCMAccessProtected (8) // We therefore check for this first. if ((access & EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) == EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) { return Accessibility.ProtectedOrInternal; } else if ((access & EnvDTE.vsCMAccess.vsCMAccessPrivate) != 0) { return Accessibility.Private; } else if ((access & EnvDTE.vsCMAccess.vsCMAccessProject) != 0) { return Accessibility.Internal; } else if ((access & EnvDTE.vsCMAccess.vsCMAccessProtected) != 0) { return Accessibility.Protected; } else if ((access & EnvDTE.vsCMAccess.vsCMAccessPublic) != 0) { return Accessibility.Public; } else if ((access & EnvDTE.vsCMAccess.vsCMAccessDefault) != 0) { return GetDefaultAccessibility(targetSymbolKind, destination); } else { throw new ArgumentException(ServicesVSResources.Invalid_access, nameof(access)); } } public bool GetWithEvents(EnvDTE.vsCMAccess access) { return (access & EnvDTE.vsCMAccess.vsCMAccessWithEvents) != 0; } protected SpecialType GetSpecialType(EnvDTE.vsCMTypeRef type) { // TODO(DustinCa): Verify this list against VB switch (type) { case EnvDTE.vsCMTypeRef.vsCMTypeRefBool: return SpecialType.System_Boolean; case EnvDTE.vsCMTypeRef.vsCMTypeRefByte: return SpecialType.System_Byte; case EnvDTE.vsCMTypeRef.vsCMTypeRefChar: return SpecialType.System_Char; case EnvDTE.vsCMTypeRef.vsCMTypeRefDecimal: return SpecialType.System_Decimal; case EnvDTE.vsCMTypeRef.vsCMTypeRefDouble: return SpecialType.System_Double; case EnvDTE.vsCMTypeRef.vsCMTypeRefFloat: return SpecialType.System_Single; case EnvDTE.vsCMTypeRef.vsCMTypeRefInt: return SpecialType.System_Int32; case EnvDTE.vsCMTypeRef.vsCMTypeRefLong: return SpecialType.System_Int64; case EnvDTE.vsCMTypeRef.vsCMTypeRefObject: return SpecialType.System_Object; case EnvDTE.vsCMTypeRef.vsCMTypeRefShort: return SpecialType.System_Int16; case EnvDTE.vsCMTypeRef.vsCMTypeRefString: return SpecialType.System_String; case EnvDTE.vsCMTypeRef.vsCMTypeRefVoid: return SpecialType.System_Void; default: // TODO: Support vsCMTypeRef2? It doesn't appear that Dev10 C# does... throw new ArgumentException(); } } private ITypeSymbol GetSpecialType(EnvDTE.vsCMTypeRef type, Compilation compilation) { return compilation.GetSpecialType(GetSpecialType(type)); } protected abstract ITypeSymbol GetTypeSymbolFromPartialName(string partialName, SemanticModel semanticModel, int position); public abstract ITypeSymbol GetTypeSymbolFromFullName(string fullName, Compilation compilation); public ITypeSymbol GetTypeSymbol(object type, SemanticModel semanticModel, int position) { if (type is EnvDTE.CodeTypeRef) { return GetTypeSymbolFromPartialName(((EnvDTE.CodeTypeRef)type).AsString, semanticModel, position); } else if (type is EnvDTE.CodeType) { return GetTypeSymbolFromFullName(((EnvDTE.CodeType)type).FullName, semanticModel.Compilation); } ITypeSymbol typeSymbol; if (type is EnvDTE.vsCMTypeRef || type is int) { typeSymbol = GetSpecialType((EnvDTE.vsCMTypeRef)type, semanticModel.Compilation); } else if (type is string s) { typeSymbol = GetTypeSymbolFromPartialName(s, semanticModel, position); } else { throw new InvalidOperationException(); } if (typeSymbol == null) { throw new ArgumentException(); } return typeSymbol; } public abstract SyntaxNode CreateReturnDefaultValueStatement(ITypeSymbol type); protected abstract int GetAttributeIndexInContainer( SyntaxNode containerNode, Func<SyntaxNode, bool> predicate); /// <summary> /// The position argument is a VARIANT which may be an EnvDTE.CodeElement, an int or a string /// representing the name of a member. This function translates the argument and returns the /// 1-based position of the specified attribute. /// </summary> public int PositionVariantToAttributeInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel) { return PositionVariantToInsertionIndex( position, containerNode, fileCodeModel, GetAttributeIndexInContainer, GetAttributeNodes); } protected abstract int GetAttributeArgumentIndexInContainer( SyntaxNode containerNode, Func<SyntaxNode, bool> predicate); public int PositionVariantToAttributeArgumentInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel) { return PositionVariantToInsertionIndex( position, containerNode, fileCodeModel, GetAttributeArgumentIndexInContainer, GetAttributeArgumentNodes); } protected abstract int GetImportIndexInContainer( SyntaxNode containerNode, Func<SyntaxNode, bool> predicate); public int PositionVariantToImportInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel) { return PositionVariantToInsertionIndex( position, containerNode, fileCodeModel, GetImportIndexInContainer, GetImportNodes); } protected abstract int GetParameterIndexInContainer( SyntaxNode containerNode, Func<SyntaxNode, bool> predicate); public int PositionVariantToParameterInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel) { return PositionVariantToInsertionIndex( position, containerNode, fileCodeModel, GetParameterIndexInContainer, GetParameterNodes); } /// <summary> /// Finds the index of the first child within the container for which <paramref name="predicate"/> returns true. /// Note that the result is a 1-based as that is what code model expects. Returns -1 if no match is found. /// </summary> protected abstract int GetMemberIndexInContainer( SyntaxNode containerNode, Func<SyntaxNode, bool> predicate); /// <summary> /// The position argument is a VARIANT which may be an EnvDTE.CodeElement, an int or a string /// representing the name of a member. This function translates the argument and returns the /// 1-based position of the specified member. /// </summary> public int PositionVariantToMemberInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel) { return PositionVariantToInsertionIndex( position, containerNode, fileCodeModel, GetMemberIndexInContainer, n => GetMemberNodes(n, includeSelf: false, recursive: false, logicalFields: false, onlySupportedNodes: false)); } private int PositionVariantToInsertionIndex( object position, SyntaxNode containerNode, FileCodeModel fileCodeModel, Func<SyntaxNode, Func<SyntaxNode, bool>, int> getIndexInContainer, Func<SyntaxNode, IEnumerable<SyntaxNode>> getChildNodes) { int result; if (position is int i) { result = i; } else if (position is EnvDTE.CodeElement) { var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(position); if (codeElement == null || codeElement.FileCodeModel != fileCodeModel) { throw Exceptions.ThrowEInvalidArg(); } var positionNode = codeElement.LookupNode(); if (positionNode == null) { throw Exceptions.ThrowEFail(); } result = getIndexInContainer(containerNode, child => child == positionNode); } else if (position is string name) { result = getIndexInContainer(containerNode, child => GetName(child) == name); } else if (position == null || position == Type.Missing) { result = 0; } else { // Nothing we can handle... throw Exceptions.ThrowEInvalidArg(); } // -1 means to insert at the end, so we'll return the last child. return result == -1 ? getChildNodes(containerNode).ToArray().Length : result; } protected abstract SyntaxNode GetFieldFromVariableNode(SyntaxNode variableNode); protected abstract SyntaxNode GetVariableFromFieldNode(SyntaxNode fieldNode); protected abstract SyntaxNode GetAttributeFromAttributeDeclarationNode(SyntaxNode attributeDeclarationNode); protected void GetNodesAroundInsertionIndex<TSyntaxNode>( TSyntaxNode containerNode, int childIndexToInsertAfter, out TSyntaxNode insertBeforeNode, out TSyntaxNode insertAfterNode) where TSyntaxNode : SyntaxNode { var childNodes = GetLogicalMemberNodes(containerNode).ToArray(); // Note: childIndexToInsertAfter is 1-based but can be 0, meaning insert before any other members. // If it isn't 0, it means to insert the member node *after* the node at the 1-based index. Debug.Assert(childIndexToInsertAfter >= 0 && childIndexToInsertAfter <= childNodes.Length); // Initialize the nodes that we'll insert the new member before and after. insertBeforeNode = null; insertAfterNode = null; if (childIndexToInsertAfter == 0) { if (childNodes.Length > 0) { insertBeforeNode = (TSyntaxNode)childNodes[0]; } } else { insertAfterNode = (TSyntaxNode)childNodes[childIndexToInsertAfter - 1]; if (childIndexToInsertAfter < childNodes.Length) { insertBeforeNode = (TSyntaxNode)childNodes[childIndexToInsertAfter]; } } if (insertBeforeNode != null) { insertBeforeNode = (TSyntaxNode)GetFieldFromVariableNode(insertBeforeNode); } if (insertAfterNode != null) { insertAfterNode = (TSyntaxNode)GetFieldFromVariableNode(insertAfterNode); } } private int GetMemberInsertionIndex(SyntaxNode container, int insertionIndex) { var childNodes = GetLogicalMemberNodes(container).ToArray(); // Note: childIndexToInsertAfter is 1-based but can be 0, meaning insert before any other members. // If it isn't 0, it means to insert the member node *after* the node at the 1-based index. Debug.Assert(insertionIndex >= 0 && insertionIndex <= childNodes.Length); if (insertionIndex == 0) { return 0; } else { var nodeAtIndex = GetFieldFromVariableNode(childNodes[insertionIndex - 1]); return GetMemberNodes(container, includeSelf: false, recursive: false, logicalFields: false, onlySupportedNodes: false).ToList().IndexOf(nodeAtIndex) + 1; } } private int GetAttributeArgumentInsertionIndex(SyntaxNode container, int insertionIndex) { return insertionIndex; } private int GetAttributeInsertionIndex(SyntaxNode container, int insertionIndex) { return insertionIndex; } private int GetImportInsertionIndex(SyntaxNode container, int insertionIndex) { return insertionIndex; } private int GetParameterInsertionIndex(SyntaxNode container, int insertionIndex) { return insertionIndex; } protected abstract bool IsCodeModelNode(SyntaxNode node); protected abstract TextSpan GetSpanToFormat(SyntaxNode root, TextSpan span); protected abstract SyntaxNode InsertMemberNodeIntoContainer(int index, SyntaxNode member, SyntaxNode container); protected abstract SyntaxNode InsertAttributeArgumentIntoContainer(int index, SyntaxNode attributeArgument, SyntaxNode container); protected abstract SyntaxNode InsertAttributeListIntoContainer(int index, SyntaxNode attribute, SyntaxNode container); protected abstract SyntaxNode InsertImportIntoContainer(int index, SyntaxNode import, SyntaxNode container); protected abstract SyntaxNode InsertParameterIntoContainer(int index, SyntaxNode parameter, SyntaxNode container); private Document FormatAnnotatedNode(Document document, SyntaxAnnotation annotation, IEnumerable<IFormattingRule> additionalRules, CancellationToken cancellationToken) { var root = document.GetSyntaxRootSynchronously(cancellationToken); var annotatedNode = root.GetAnnotatedNodesAndTokens(annotation).Single().AsNode(); var formattingSpan = GetSpanToFormat(root, annotatedNode.FullSpan); var formattingRules = Formatter.GetDefaultFormattingRules(document); if (additionalRules != null) { formattingRules = additionalRules.Concat(formattingRules); } return Formatter.FormatAsync( document, new TextSpan[] { formattingSpan }, options: null, rules: formattingRules, cancellationToken: cancellationToken).WaitAndGetResult_CodeModel(cancellationToken); } private SyntaxNode InsertNode( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode node, Func<int, SyntaxNode, SyntaxNode, SyntaxNode> insertNodeIntoContainer, CancellationToken cancellationToken, out Document newDocument) { var root = document.GetSyntaxRootSynchronously(cancellationToken); // Annotate the member we're inserting so we can get back to it. var annotation = new SyntaxAnnotation(); var gen = SyntaxGenerator.GetGenerator(document); node = node.WithAdditionalAnnotations(annotation); if (gen.GetDeclarationKind(node) != DeclarationKind.NamespaceImport) { // REVIEW: how simplifier ever worked for code model? nobody added simplifier.Annotation before? node = node.WithAdditionalAnnotations(Simplifier.Annotation); } var newContainerNode = insertNodeIntoContainer(insertionIndex, node, containerNode); var newRoot = root.ReplaceNode(containerNode, newContainerNode); document = document.WithSyntaxRoot(newRoot); if (!batchMode) { document = Simplifier.ReduceAsync(document, annotation, optionSet: null, cancellationToken: cancellationToken).WaitAndGetResult_CodeModel(cancellationToken); } document = FormatAnnotatedNode(document, annotation, new[] { _lineAdjustmentFormattingRule, _endRegionFormattingRule }, cancellationToken); // out param newDocument = document; // new node return document .GetSyntaxRootSynchronously(cancellationToken) .GetAnnotatedNodesAndTokens(annotation) .Single() .AsNode(); } /// <summary> /// Override to determine whether <param name="newNode"/> adds a method body to <param name="node"/>. /// This is used to determine whether a blank line should be added inside the body when formatting. /// </summary> protected abstract bool AddBlankLineToMethodBody(SyntaxNode node, SyntaxNode newNode); public Document UpdateNode( Document document, SyntaxNode node, SyntaxNode newNode, CancellationToken cancellationToken) { // Annotate the member we're inserting so we can get back to it. var annotation = new SyntaxAnnotation(); // REVIEW: how simplifier ever worked for code model? nobody added simplifier.Annotation before? var annotatedNode = newNode.WithAdditionalAnnotations(annotation, Simplifier.Annotation); var oldRoot = document.GetSyntaxRootSynchronously(cancellationToken); var newRoot = oldRoot.ReplaceNode(node, annotatedNode); document = document.WithSyntaxRoot(newRoot); var additionalRules = AddBlankLineToMethodBody(node, newNode) ? SpecializedCollections.SingletonEnumerable(_lineAdjustmentFormattingRule) : null; document = FormatAnnotatedNode(document, annotation, additionalRules, cancellationToken); return document; } public SyntaxNode InsertAttribute( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode attributeNode, CancellationToken cancellationToken, out Document newDocument) { var finalNode = InsertNode( document, batchMode, GetAttributeInsertionIndex(containerNode, insertionIndex), containerNode, attributeNode, InsertAttributeListIntoContainer, cancellationToken, out newDocument); return GetAttributeFromAttributeDeclarationNode(finalNode); } public SyntaxNode InsertAttributeArgument( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode attributeArgumentNode, CancellationToken cancellationToken, out Document newDocument) { var finalNode = InsertNode( document, batchMode, GetAttributeArgumentInsertionIndex(containerNode, insertionIndex), containerNode, attributeArgumentNode, InsertAttributeArgumentIntoContainer, cancellationToken, out newDocument); return finalNode; } public SyntaxNode InsertImport( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode importNode, CancellationToken cancellationToken, out Document newDocument) { var finalNode = InsertNode( document, batchMode, GetImportInsertionIndex(containerNode, insertionIndex), containerNode, importNode, InsertImportIntoContainer, cancellationToken, out newDocument); return finalNode; } public SyntaxNode InsertParameter( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode parameterNode, CancellationToken cancellationToken, out Document newDocument) { var finalNode = InsertNode( document, batchMode, GetParameterInsertionIndex(containerNode, insertionIndex), containerNode, parameterNode, InsertParameterIntoContainer, cancellationToken, out newDocument); return finalNode; } public SyntaxNode InsertMember( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode memberNode, CancellationToken cancellationToken, out Document newDocument) { var finalNode = InsertNode( document, batchMode, GetMemberInsertionIndex(containerNode, insertionIndex), containerNode, memberNode, InsertMemberNodeIntoContainer, cancellationToken, out newDocument); return GetVariableFromFieldNode(finalNode); } public Queue<CodeModelEvent> CollectCodeModelEvents(SyntaxTree oldTree, SyntaxTree newTree) { return _eventCollector.Collect(oldTree, newTree); } public abstract bool IsNamespace(SyntaxNode node); public abstract bool IsType(SyntaxNode node); public virtual IList<string> GetHandledEventNames(SyntaxNode method, SemanticModel semanticModel) { // descendants may override (particularly VB). return SpecializedCollections.EmptyList<string>(); } public virtual bool HandlesEvent(string eventName, SyntaxNode method, SemanticModel semanticModel) { // descendants may override (particularly VB). return false; } public virtual Document AddHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken) { // descendants may override (particularly VB). return document; } public virtual Document RemoveHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken) { // descendants may override (particularly VB). return document; } public abstract string[] GetFunctionExtenderNames(); public abstract object GetFunctionExtender(string name, SyntaxNode node, ISymbol symbol); public abstract string[] GetPropertyExtenderNames(); public abstract object GetPropertyExtender(string name, SyntaxNode node, ISymbol symbol); public abstract string[] GetExternalTypeExtenderNames(); public abstract object GetExternalTypeExtender(string name, string externalLocation); public abstract string[] GetTypeExtenderNames(); public abstract object GetTypeExtender(string name, AbstractCodeType codeType); public abstract bool IsValidBaseType(SyntaxNode node, ITypeSymbol typeSymbol); public abstract SyntaxNode AddBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position); public abstract SyntaxNode RemoveBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel); public abstract bool IsValidInterfaceType(SyntaxNode node, ITypeSymbol typeSymbol); public abstract SyntaxNode AddImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position); public abstract SyntaxNode RemoveImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel); public abstract string GetPrototype(SyntaxNode node, ISymbol symbol, PrototypeFlags flags); public virtual void AttachFormatTrackingToBuffer(ITextBuffer buffer) { // can be override by languages if needed } public virtual void DetachFormatTrackingToBuffer(ITextBuffer buffer) { // can be override by languages if needed } public virtual void EnsureBufferFormatted(ITextBuffer buffer) { // can be override by languages if needed } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Collections.Generic; namespace GC_Microbenchmarks { // the type of objects allocated // value refers to object size public enum ObjectType { Undefined = -1, Small = 8000, SmallFinal = 8500, // small finalizable object Large = 85000, ExtraLarge = 20*1024*1024 } // the condition to satisfy before ending the benchmark public enum AllocationCondition { Undefined, HeapSize, Segments, Objects } // the object that gets allocated public class Node { public Node(int dataSize) { data = new byte[dataSize]; } public byte[] data; } // the finalizable object that gets allocated public class FNode : Node { public FNode(int dataSize) : base(dataSize) { } // puts object on finalization list ~FNode() { } } public class GCMicroBench { // the minimum size of a segment // if reserved mem increases by more than MinSegmentSize, then we can assume we've allocated a new segment public const long MinSegmentSize = 4 * 1024 * 1024; public const string ObjTypeParam = "/objtype:"; public const string ConditionParam = "/condition:"; public const string AmountParam = "/amount:"; // test members private List<Node> m_list = new List<Node>(); // holds the allocated objects private ObjectType m_objType = ObjectType.Undefined; private AllocationCondition m_allocCondition = AllocationCondition.Undefined; private long m_amount = 0; // outputs the usage information for the app public static void Usage() { Console.WriteLine("USAGE: /objtype: /condition: /amount:"); Console.WriteLine("where"); Console.WriteLine("\tobjtype = [small|smallfinal|large|extralarge]"); Console.WriteLine("\tcondition = [heapsize|segments|objects]"); Console.WriteLine("\tamount = the number that satisfies the condition (ex: number of objects)"); } public static void Main(string[] args) { GCMicroBench test = new GCMicroBench(); if (!test.ParseArgs(args)) { Usage(); return; } test.RunTest(); } public bool ParseArgs(string[] args) { if (args.Length != 3) { return false; } for (int i = 0; i < args.Length; i++) { args[i] = args[i].ToLower(); if (args[i].StartsWith(ObjTypeParam)) { if (m_objType != ObjectType.Undefined) { return false; } switch (args[i].Substring(ObjTypeParam.Length)) { case "small": m_objType = ObjectType.Small; break; case "smallfinal": m_objType = ObjectType.SmallFinal; break; case "large": m_objType = ObjectType.Large; break; case "extralarge": m_objType = ObjectType.ExtraLarge; break; default: return false; } } else if (args[i].StartsWith(ConditionParam)) { if (m_allocCondition != AllocationCondition.Undefined) { return false; } switch (args[i].Substring(ConditionParam.Length)) { case "heapsize": m_allocCondition = AllocationCondition.HeapSize; break; case "segments": m_allocCondition = AllocationCondition.Segments; break; case "objects": m_allocCondition = AllocationCondition.Objects; break; default: return false; } } else if (args[i].StartsWith(AmountParam)) { if (m_amount != 0) { return false; } if ((!Int64.TryParse(args[i].Substring(AmountParam.Length), out m_amount)) || (m_amount <= 0)) { Console.WriteLine("amount must be greater than 0"); return false; } if ( (m_allocCondition == AllocationCondition.HeapSize) && ( m_amount <= GC.GetTotalMemory(false) ) ) { Console.WriteLine("amount must be greater than current heap size"); return false; } } else { return false; } } return true; } public void RunTest() { // allocate objType objects until heap size >= amount bytes if (m_allocCondition == AllocationCondition.HeapSize) { while (GC.GetTotalMemory(false) <= m_amount) { Allocate(); } } // allocate amount objType objects else if (m_allocCondition == AllocationCondition.Objects) { for (long i = 0; i < m_amount; i++) { Allocate(); } } // allocate objType objects until reserved VM increases by minimum segment size, amount times // (this is an indirect way of determining if a new segment has been allocated) else if (m_allocCondition == AllocationCondition.Segments) { long reservedMem; for (long i = 0; i < m_amount; i++) { reservedMem = Process.GetCurrentProcess().VirtualMemorySize64; do { Allocate(); } while (Math.Abs(Process.GetCurrentProcess().VirtualMemorySize64 - reservedMem) < MinSegmentSize); } } // allocations done Deallocate(); } public void Allocate() { Node n; // create new finalizable object if (m_objType == ObjectType.SmallFinal) { n = new FNode((int)m_objType); } else { n = new Node((int)m_objType); } m_list.Add(n); } public bool ClearList() { if (m_list != null) { m_list.Clear(); m_list = null; return ( (m_list.Count > 0) && (m_list[0] is FNode)); } return false; } // releases references to allocated objects // times GC.Collect() // if objects are finalizable, also times GC.WaitForPendingFinalizers() public void Deallocate() { bool finalizable = ClearList(); GC.Collect(); if (finalizable) { GC.WaitForPendingFinalizers(); GC.Collect(); } } } }
// Copyright (c) 1995-2009 held by the author(s). All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // nor the names of its contributors may be used to endorse or // promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1998 { /// <summary> /// Used in UA PDU /// </summary> [Serializable] [XmlRoot] public partial class ApaData { /// <summary> /// Index of APA parameter /// </summary> private ushort _parameterIndex; /// <summary> /// Index of APA parameter /// </summary> private short _parameterValue; /// <summary> /// Initializes a new instance of the <see cref="ApaData"/> class. /// </summary> public ApaData() { } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(ApaData left, ApaData right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(ApaData left, ApaData right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public virtual int GetMarshalledSize() { int marshalSize = 0; marshalSize += 2; // this._parameterIndex marshalSize += 2; // this._parameterValue return marshalSize; } /// <summary> /// Gets or sets the Index of APA parameter /// </summary> [XmlElement(Type = typeof(ushort), ElementName = "parameterIndex")] public ushort ParameterIndex { get { return this._parameterIndex; } set { this._parameterIndex = value; } } /// <summary> /// Gets or sets the Index of APA parameter /// </summary> [XmlElement(Type = typeof(short), ElementName = "parameterValue")] public short ParameterValue { get { return this._parameterValue; } set { this._parameterValue = value; } } /// <summary> /// Occurs when exception when processing PDU is caught. /// </summary> public event EventHandler<PduExceptionEventArgs> ExceptionOccured; /// <summary> /// Called when exception occurs (raises the <see cref="Exception"/> event). /// </summary> /// <param name="e">The exception.</param> protected void RaiseExceptionOccured(Exception e) { if (Pdu.FireExceptionEvents && this.ExceptionOccured != null) { this.ExceptionOccured(this, new PduExceptionEventArgs(e)); } } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Marshal(DataOutputStream dos) { if (dos != null) { try { dos.WriteUnsignedShort((ushort)this._parameterIndex); dos.WriteShort((short)this._parameterValue); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Unmarshal(DataInputStream dis) { if (dis != null) { try { this._parameterIndex = dis.ReadUnsignedShort(); this._parameterValue = dis.ReadShort(); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Reflection(StringBuilder sb) { sb.AppendLine("<ApaData>"); try { sb.AppendLine("<parameterIndex type=\"ushort\">" + this._parameterIndex.ToString(CultureInfo.InvariantCulture) + "</parameterIndex>"); sb.AppendLine("<parameterValue type=\"short\">" + this._parameterValue.ToString(CultureInfo.InvariantCulture) + "</parameterValue>"); sb.AppendLine("</ApaData>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return this == obj as ApaData; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(ApaData obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } if (this._parameterIndex != obj._parameterIndex) { ivarsEqual = false; } if (this._parameterValue != obj._parameterValue) { ivarsEqual = false; } return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; result = GenerateHash(result) ^ this._parameterIndex.GetHashCode(); result = GenerateHash(result) ^ this._parameterValue.GetHashCode(); return result; } } }
// // Pusher.cs // // Author: // Zachary Gramana <zack@xamarin.com> // // Copyright (c) 2013, 2014 Xamarin Inc (http://www.xamarin.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. // /** * Original iOS version by Jens Alfke * Ported to Android by Marty Schoch, Traun Leyden * * Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Text; using Couchbase.Lite; using Couchbase.Lite.Internal; using Couchbase.Lite.Replicator; using Couchbase.Lite.Support; using Couchbase.Lite.Util; using Sharpen; using System.Threading.Tasks; using System.Net.Http; using System.Web; using System.Net.Http.Headers; using Newtonsoft.Json.Linq; using System.Linq; namespace Couchbase.Lite.Replicator { internal class Pusher : Replication { readonly string Tag = "Pusher"; private bool observing; private FilterDelegate filter; /// <summary>Constructor</summary> public Pusher(Database db, Uri remote, bool continuous, TaskFactory workExecutor) : this(db, remote, continuous, null, workExecutor) { } /// <summary>Constructor</summary> public Pusher(Database db, Uri remote, bool continuous, IHttpClientFactory clientFactory , TaskFactory workExecutor) : base(db, remote, continuous, clientFactory , workExecutor) { CreateTarget = false; observing = false; } #region implemented abstract members of Replication public override IEnumerable<String> Channels { get; set; } public override IEnumerable<String> DocIds { get; set; } public override Dictionary<String, String> Headers { get; set; } public override Boolean CreateTarget { get; set; } public override bool IsPull { get { return false; } } #endregion protected internal override void MaybeCreateRemoteDB() { if (!CreateTarget) { return; } Log.V(Tag, this + ": Remote db might not exist; creating it..."); Log.D(Tag, this + "|" + Thread.CurrentThread() + ": maybeCreateRemoteDB() calling asyncTaskStarted()"); SendAsyncRequest(HttpMethod.Put, String.Empty, null, (result, e) => { try { if (e is HttpException && ((HttpException)e).ErrorCode != 412) { // this is fatal: no db to push to! Log.E(Tag, this + ": Failed to create remote db", e); LastError = e; Stop(); } else { Log.V (Tag, this + ": Created remote db"); CreateTarget = false; BeginReplicating (); } } finally { Log.D(Tag, this + "|" + Thread.CurrentThread() + ": maybeCreateRemoteDB.onComplete() calling asyncTaskFinished()"); AsyncTaskFinished(1); } }); } internal override void BeginReplicating() { // If we're still waiting to create the remote db, do nothing now. (This method will be // re-invoked after that request finishes; see maybeCreateRemoteDB() above.) Log.D(Database.Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": beginReplicating() called"); if (CreateTarget) { Log.D(Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": creatingTarget == true, doing nothing"); return; } else { Log.D(Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": creatingTarget != true, continuing"); } if (Filter != null) { filter = LocalDatabase.GetFilter(Filter); } if (Filter != null && filter == null) { Log.W(Tag, string.Format("{0}: No ReplicationFilter registered for filter '{1}'; ignoring" , this, Filter)); } // Process existing changes since the last push: long lastSequenceLong = 0; if (LastSequence != null) { lastSequenceLong = long.Parse(LastSequence); } var options = new ChangesOptions(); options.SetIncludeConflicts(true); var changes = LocalDatabase.ChangesSince(lastSequenceLong, options, filter); if (changes.Count > 0) { Batcher.QueueObjects(changes); Batcher.Flush(); } // Now listen for future changes (in continuous mode): if (continuous) { observing = true; LocalDatabase.Changed += OnChanged; Log.D(Tag, this + "|" + Thread.CurrentThread() + ": pusher.beginReplicating() calling asyncTaskStarted()"); AsyncTaskStarted(); } } // prevents stopped() from being called when other tasks finish public override void Stop() { StopObserving(); base.Stop(); } private void StopObserving() { if (observing) { try { observing = false; LocalDatabase.Changed -= OnChanged; } finally { AsyncTaskFinished(1); } } } internal void OnChanged(Object sender, Database.DatabaseChangeEventArgs args) { var changes = args.Changes; foreach (DocumentChange change in changes) { // Skip revisions that originally came from the database I'm syncing to: var source = change.SourceUrl; if (source != null && source.Equals(RemoteUrl)) { return; } var rev = change.AddedRevision; IDictionary<String, Object> paramsFixMe = null; // TODO: these should not be null if (LocalDatabase.RunFilter(filter, paramsFixMe, rev)) { AddToInbox(rev); } } } internal override void ProcessInbox(RevisionList inbox) { var lastInboxSequence = inbox[inbox.Count - 1].GetSequence(); // Generate a set of doc/rev IDs in the JSON format that _revs_diff wants: // <http://wiki.apache.org/couchdb/HttpPostRevsDiff> var diffs = new Dictionary<String, IList<String>>(); foreach (var rev in inbox) { var docID = rev.GetDocId(); var revs = diffs.Get(docID); if (revs == null) { revs = new AList<String>(); diffs[docID] = revs; } revs.AddItem(rev.GetRevId()); } // Call _revs_diff on the target db: Log.D(Tag, this + "|" + Thread.CurrentThread() + ": processInbox() calling asyncTaskStarted()"); Log.D(Tag, this + "|" + Thread.CurrentThread() + ": posting to /_revs_diff: " + diffs); AsyncTaskStarted(); SendAsyncRequest(HttpMethod.Post, "/_revs_diff", diffs, (response, e) => { try { Log.D(Tag, this + "|" + Thread.CurrentThread() + ": /_revs_diff response: " + response); var responseData = (JObject)response; var results = responseData.ToObject<IDictionary<string, object>>(); if (e != null) { LastError = e; RevisionFailed(); //Stop (); } else { if (results.Count != 0) { // Go through the list of local changes again, selecting the ones the destination server // said were missing and mapping them to a JSON dictionary in the form _bulk_docs wants: var docsToSend = new AList<object> (); foreach (var rev in inbox) { IDictionary<string, object> properties = null; var resultDocData = (JObject)results.Get (rev.GetDocId ()); var resultDoc = resultDocData.ToObject<IDictionary<String, Object>>(); if (resultDoc != null) { var revs = ((JArray)resultDoc.Get ("missing")).Values<String>().ToList(); if (revs != null && revs.Contains (rev.GetRevId ())) { //remote server needs this revision // Get the revision's properties if (rev.IsDeleted ()) { properties = new Dictionary<string, object> (); properties.Put ("_id", rev.GetDocId ()); properties.Put ("_rev", rev.GetRevId ()); properties.Put ("_deleted", true); } else { // OPT: Shouldn't include all attachment bodies, just ones that have changed var contentOptions = EnumSet.Of (TDContentOptions.TDIncludeAttachments, TDContentOptions.TDBigAttachmentsFollow); try { LocalDatabase.LoadRevisionBody (rev, contentOptions); } catch (CouchbaseLiteException e1) { Log.W(Tag, string.Format("%s Couldn't get local contents of %s", rev, this)); RevisionFailed(); continue; } properties = new Dictionary<String, Object> (rev.GetProperties ()); } if (properties.ContainsKey ("_attachments")) { if (UploadMultipartRevision (rev)) { continue; } } if (properties != null) { // Add the _revisions list: properties.Put ("_revisions", LocalDatabase.GetRevisionHistoryDict (rev)); //now add it to the docs to send docsToSend.AddItem (properties); } } } } // Post the revisions to the destination. "new_edits":false means that the server should // use the given _rev IDs instead of making up new ones. var numDocsToSend = docsToSend.Count; if (numDocsToSend > 0) { var bulkDocsBody = new Dictionary<String, Object> (); bulkDocsBody.Put ("docs", docsToSend); bulkDocsBody.Put ("new_edits", false); Log.V(Tag, string.Format("%s: POSTing " + numDocsToSend + " revisions to _bulk_docs: %s", this, docsToSend)); ChangesCount += numDocsToSend; Log.D(Tag, this + "|" + Thread.CurrentThread() + ": processInbox-before_bulk_docs() calling asyncTaskStarted()"); AsyncTaskStarted (); SendAsyncRequest (HttpMethod.Post, "/_bulk_docs", bulkDocsBody, (result, ex) => { try { if (ex != null) { LastError = ex; RevisionFailed(); } else { Log.V(Tag, string.Format("%s: POSTed to _bulk_docs: %s", this, docsToSend)); LastSequence = string.Format ("{0}", lastInboxSequence); } CompletedChangesCount += numDocsToSend; } finally { AsyncTaskFinished (1); } }); } } else { // If none of the revisions are new to the remote, just bump the lastSequence: LastSequence = string.Format ("{0}", lastInboxSequence); } } } finally { Log.D(Tag, this + "|" + Thread.CurrentThread() + ": processInbox() calling asyncTaskFinished()"); AsyncTaskFinished (1); } }); } private bool UploadMultipartRevision(RevisionInternal revision) { MultipartFormDataContent multiPart = null; var revProps = revision.GetProperties(); revProps.Put("_revisions", LocalDatabase.GetRevisionHistoryDict(revision)); var attachments = (IDictionary<string, object>)revProps.Get("_attachments"); foreach (var attachmentKey in attachments.Keys) { var attachment = (IDictionary<String, Object>)attachments.Get(attachmentKey); if (attachment.ContainsKey("follows")) { if (multiPart == null) { multiPart = new MultipartFormDataContent(); try { var json = Manager.GetObjectMapper().WriteValueAsString(revProps); var utf8charset = Encoding.UTF8; multiPart.Add(new StringContent(json, utf8charset, "application/json"), "param1"); } catch (IOException e) { throw new ArgumentException("Not able to serialize revision properties into a multipart request content.", e); } } var blobStore = LocalDatabase.Attachments; var base64Digest = (string)attachment.Get("digest"); var blobKey = new BlobKey(base64Digest); var inputStream = blobStore.BlobStreamForKey(blobKey); if (inputStream == null) { Log.W(Tag, "Unable to find blob file for blobKey: " + blobKey + " - Skipping upload of multipart revision."); multiPart = null; } else { string contentType = null; if (attachment.ContainsKey("content_type")) { contentType = (string)attachment.Get("content_type"); } else { if (attachment.ContainsKey("content-type")) { var message = string.Format("Found attachment that uses content-type" + " field name instead of content_type (see couchbase-lite-android" + " issue #80): " + attachment); Log.W(Tag, message); } } var content = new StreamContent(inputStream); content.Headers.ContentType = new MediaTypeHeaderValue(contentType); multiPart.Add(content, attachmentKey); } } } if (multiPart == null) { return false; } var path = string.Format("/{0}?new_edits=false", revision.GetDocId()); // TODO: need to throttle these requests Log.D(Tag, "Uploadeding multipart request. Revision: " + revision); Log.D(Tag, this + "|" + Thread.CurrentThread() + ": uploadMultipartRevision() calling asyncTaskStarted()"); AsyncTaskStarted(); SendAsyncMultipartRequest(HttpMethod.Put, path, multiPart, (result, e) => { try { if (e != null) { Log.E (Tag, "Exception uploading multipart request", e); LastError = e; RevisionFailed(); } else { Log.D (Tag, "Uploaded multipart request. Result: " + result); } } finally { AsyncTaskFinished (1); } }); return true; } } }
// 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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Microsoft.Build.Shared.FileSystem; #if FEATURE_FILE_TRACKER namespace Microsoft.Build.Utilities { /// <summary> /// Enumeration to express the type of executable being wrapped by Tracker.exe /// </summary> public enum ExecutableType { /// <summary> /// 32-bit native executable /// </summary> Native32Bit = 0, /// <summary> /// 64-bit native executable /// </summary> Native64Bit = 1, /// <summary> /// A managed executable without a specified bitness /// </summary> ManagedIL = 2, /// <summary> /// A managed executable specifically marked as 32-bit /// </summary> Managed32Bit = 3, /// <summary> /// A managed executable specifically marked as 64-bit /// </summary> Managed64Bit = 4, /// <summary> /// Use the same bitness as the currently running executable. /// </summary> SameAsCurrentProcess = 5 } /// <summary> /// This class contains utility functions to encapsulate launching and logging for the Tracker /// </summary> public static class FileTracker { #region Static Member Data // The default path to temp, used to create explicitly short and long paths private static readonly string s_tempPath = Path.GetTempPath(); // The short path to temp private static readonly string s_tempShortPath = FileUtilities.EnsureTrailingSlash(NativeMethodsShared.GetShortFilePath(s_tempPath).ToUpperInvariant()); // The long path to temp private static readonly string s_tempLongPath = FileUtilities.EnsureTrailingSlash(NativeMethodsShared.GetLongFilePath(s_tempPath).ToUpperInvariant()); // The path to ApplicationData (is equal to %USERPROFILE%\Application Data folder in Windows XP and %USERPROFILE%\AppData\Roaming in Vista and later) private static readonly string s_applicationDataPath = FileUtilities.EnsureTrailingSlash(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToUpperInvariant()); // The path to LocalApplicationData (is equal to %USERPROFILE%\Local Settings\Application Data folder in Windows XP and %USERPROFILE%\AppData\Local in Vista and later). private static readonly string s_localApplicationDataPath = FileUtilities.EnsureTrailingSlash(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData).ToUpperInvariant()); // The path to the LocalLow folder. In Vista and later, user application data is organized across %USERPROFILE%\AppData\LocalLow, %USERPROFILE%\AppData\Local (%LOCALAPPDATA%) // and %USERPROFILE%\AppData\Roaming (%APPDATA%). The LocalLow folder is not present in XP. private static readonly string s_localLowApplicationDataPath = FileUtilities.EnsureTrailingSlash(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "AppData\\LocalLow").ToUpperInvariant()); // The path to the common Application Data, which is also used by some programs (e.g. antivirus) that we wish to ignore. // Is equal to C:\Documents and Settings\All Users\Application Data on XP, and C:\ProgramData on Vista+. // But for backward compatibility, the paths "C:\Documents and Settings\All Users\Application Data" and "C:\Users\All Users\Application Data" are still accessible via Junction point on Vista+. // Thus this list is created to store all possible common application data paths to cover more cases as possible. private static readonly List<string> s_commonApplicationDataPaths; // The name of the standalone tracker tool. private static readonly string s_TrackerFilename = "Tracker.exe"; // The name of the assembly that is injected into the executing process. // Detours handles picking between FileTracker{32,64}.dll so only mention one. private static readonly string s_FileTrackerFilename = "FileTracker32.dll"; // The name of the PATH environment variable. private const string pathEnvironmentVariableName = "PATH"; // Static cache of the path separator character in an array for use in String.Split. private static readonly char[] pathSeparatorArray = { Path.PathSeparator }; // Static cache of the path separator character in an array for use in String.Split. private static readonly string pathSeparator = Path.PathSeparator.ToString(); #endregion #region Static constructor static FileTracker() { s_commonApplicationDataPaths = new List<string>(); string defaultCommonApplicationDataPath = FileUtilities.EnsureTrailingSlash(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData).ToUpperInvariant()); s_commonApplicationDataPaths.Add(defaultCommonApplicationDataPath); string defaultRootDirectory = Path.GetPathRoot(defaultCommonApplicationDataPath); string alternativeCommonApplicationDataPath1 = FileUtilities.EnsureTrailingSlash(Path.Combine(defaultRootDirectory, @"Documents and Settings\All Users\Application Data").ToUpperInvariant()); if (!alternativeCommonApplicationDataPath1.Equals(defaultCommonApplicationDataPath, StringComparison.Ordinal)) { s_commonApplicationDataPaths.Add(alternativeCommonApplicationDataPath1); } string alternativeCommonApplicationDataPath2 = FileUtilities.EnsureTrailingSlash(Path.Combine(defaultRootDirectory, @"Users\All Users\Application Data").ToUpperInvariant()); if (!alternativeCommonApplicationDataPath2.Equals(defaultCommonApplicationDataPath, StringComparison.Ordinal)) { s_commonApplicationDataPaths.Add(alternativeCommonApplicationDataPath2); } } #endregion #region Native method wrappers /// <summary> /// Stops tracking file accesses. /// </summary> public static void EndTrackingContext() => InprocTrackingNativeMethods.EndTrackingContext(); /// <summary> /// Resume tracking file accesses in the current tracking context. /// </summary> public static void ResumeTracking() => InprocTrackingNativeMethods.ResumeTracking(); /// <summary> /// Set the global thread count, and assign that count to the current thread. /// </summary> public static void SetThreadCount(int threadCount) => InprocTrackingNativeMethods.SetThreadCount(threadCount); /// <summary> /// Starts tracking file accesses. /// </summary> /// <param name="intermediateDirectory">The directory into which to write the tracking log files</param> /// <param name="taskName">The name of the task calling this function, used to determine the /// names of the tracking log files</param> public static void StartTrackingContext(string intermediateDirectory, string taskName) => InprocTrackingNativeMethods.StartTrackingContext(intermediateDirectory, taskName); /// <summary> /// Starts tracking file accesses, using the rooting marker in the response file provided. To /// automatically generate a response file given a rooting marker, call /// FileTracker.CreateRootingMarkerResponseFile. /// </summary> /// <param name="intermediateDirectory">The directory into which to write the tracking log files</param> /// <param name="taskName">The name of the task calling this function, used to determine the /// names of the tracking log files</param> /// <param name="rootMarkerResponseFile">The path to the root marker response file.</param> public static void StartTrackingContextWithRoot(string intermediateDirectory, string taskName, string rootMarkerResponseFile) => InprocTrackingNativeMethods.StartTrackingContextWithRoot(intermediateDirectory, taskName, rootMarkerResponseFile); /// <summary> /// Stop tracking file accesses and get rid of the current tracking contexts. /// </summary> public static void StopTrackingAndCleanup() => InprocTrackingNativeMethods.StopTrackingAndCleanup(); /// <summary> /// Temporarily suspend tracking of file accesses in the current tracking context. /// </summary> public static void SuspendTracking() => InprocTrackingNativeMethods.SuspendTracking(); /// <summary> /// Write tracking logs for all contexts and threads. /// </summary> /// <param name="intermediateDirectory">The directory into which to write the tracking log files</param> /// <param name="taskName">The name of the task calling this function, used to determine the /// names of the tracking log files</param> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "TLogs", Justification = "Has now shipped as public API; plus it's unclear whether 'Tlog' or 'TLog' is the preferred casing")] public static void WriteAllTLogs(string intermediateDirectory, string taskName) => InprocTrackingNativeMethods.WriteAllTLogs(intermediateDirectory, taskName); /// <summary> /// Write tracking logs corresponding to the current tracking context. /// </summary> /// <param name="intermediateDirectory">The directory into which to write the tracking log files</param> /// <param name="taskName">The name of the task calling this function, used to determine the /// names of the tracking log files</param> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "TLogs", Justification = "Has now shipped as public API; plus it's unclear whether 'Tlog' or 'TLog' is the preferred casing")] public static void WriteContextTLogs(string intermediateDirectory, string taskName) => InprocTrackingNativeMethods.WriteContextTLogs(intermediateDirectory, taskName); #endregion // Native method wrappers #region Methods /// <summary> /// Test to see if the specified file is excluded from tracked dependencies /// </summary> /// <param name="fileName"> /// Full path of the file to test /// </param> public static bool FileIsExcludedFromDependencies(string fileName) { // UNDONE: This check means that we cannot incremental build projects // that exist under the following directories on XP: // %USERPROFILE%\Application Data // %USERPROFILE%\Local Settings\Application Data // // and the following directories on Vista: // %USERPROFILE%\AppData\Local // %USERPROFILE%\AppData\LocalLow // %USERPROFILE%\AppData\Roaming // We don't want to be including these as dependencies or outputs: // 1. Files under %USERPROFILE%\Application Data in XP and %USERPROFILE%\AppData\Roaming in Vista and later. // 2. Files under %USERPROFILE%\Local Settings\Application Data in XP and %USERPROFILE%\AppData\Local in Vista and later. // 3. Files under %USERPROFILE%\AppData\LocalLow in Vista and later. // 4. Files that are in the TEMP directory (Since on XP, temp files are not // located under AppData, they would not be compacted out correctly otherwise). // 5. Files under the common ("All Users") Application Data location -- C:\Documents and Settings\All Users\Application Data // on XP and either C:\Users\All Users\Application Data or C:\ProgramData on Vista+ return FileIsUnderPath(fileName, s_applicationDataPath) || FileIsUnderPath(fileName, s_localApplicationDataPath) || FileIsUnderPath(fileName, s_localLowApplicationDataPath) || FileIsUnderPath(fileName, s_tempShortPath) || FileIsUnderPath(fileName, s_tempLongPath) || s_commonApplicationDataPaths.Any(p => FileIsUnderPath(fileName, p)); } /// <summary> /// Test to see if the specified file is under the specified path /// </summary> /// <param name="fileName"> /// Full path of the file to test /// </param> /// <param name="path"> /// Is the file under this full path? /// </param> public static bool FileIsUnderPath(string fileName, string path) { // UNDONE: Get the long file path for the entry // This is an incredibly expensive operation. The tracking log // as written by CL etc. does not contain short paths // fileDirectory = NativeMethods.GetFullLongFilePath(fileDirectory); // Ensure that the path has a trailing slash that we are checking under // By default the paths that we check for most often will have, so this will // return fast and not allocate memory in the process path = FileUtilities.EnsureTrailingSlash(path); // Is the fileName under the filePath? return string.Compare(fileName, 0, path, 0, path.Length, StringComparison.OrdinalIgnoreCase) == 0; } /// <summary> /// Construct a rooting marker string from the ITaskItem array of primary sources. /// </summary> /// <param name="source">An <see cref="ITaskItem"/> containing information about the primary source.</param> public static string FormatRootingMarker(ITaskItem source) => FormatRootingMarker(new[] { source }, null); /// <summary> /// Construct a rooting marker string from the ITaskItem array of primary sources. /// </summary> /// <param name="source">An <see cref="ITaskItem"/> containing information about the primary source.</param> /// <param name="output">An <see cref="ITaskItem"/> containing information about the output.</param> public static string FormatRootingMarker(ITaskItem source, ITaskItem output) => FormatRootingMarker(new[] { source }, new[] { output }); /// <summary> /// Construct a rooting marker string from the ITaskItem array of primary sources. /// </summary> /// <param name="sources"> /// ITaskItem array of primary sources. /// </param> public static string FormatRootingMarker(ITaskItem[] sources) => FormatRootingMarker(sources, null); /// <summary> /// Construct a rooting marker string from the ITaskItem array of primary sources. /// </summary> /// <param name="sources"> /// ITaskItem array of primary sources. /// </param> /// <param name="outputs">ITaskItem array of outputs.</param> public static string FormatRootingMarker(ITaskItem[] sources, ITaskItem[] outputs) { ErrorUtilities.VerifyThrowArgumentNull(sources, nameof(sources)); // So we don't have to deal with null checks. outputs ??= Array.Empty<ITaskItem>(); var rootSources = new List<string>(sources.Length + outputs.Length); foreach (ITaskItem source in sources) { rootSources.Add(FileUtilities.NormalizePath(source.ItemSpec).ToUpperInvariant()); } foreach (ITaskItem output in outputs) { rootSources.Add(FileUtilities.NormalizePath(output.ItemSpec).ToUpperInvariant()); } rootSources.Sort(StringComparer.OrdinalIgnoreCase); return string.Join("|", rootSources); } /// <summary> /// Given a set of source files in the form of ITaskItem, creates a temporary response /// file containing the rooting marker that corresponds to those sources. /// </summary> /// <param name="sources"> /// ITaskItem array of primary sources. /// </param> /// <returns>The response file path.</returns> public static string CreateRootingMarkerResponseFile(ITaskItem[] sources) => CreateRootingMarkerResponseFile(FormatRootingMarker(sources)); /// <summary> /// Given a rooting marker, creates a temporary response file with that rooting marker /// in it. /// </summary> /// <param name="rootMarker">The rooting marker to put in the response file.</param> /// <returns>The response file path.</returns> public static string CreateRootingMarkerResponseFile(string rootMarker) { string trackerResponseFile = FileUtilities.GetTemporaryFile(".rsp"); File.WriteAllText(trackerResponseFile, "/r \"" + rootMarker + "\"", Encoding.Unicode); return trackerResponseFile; } /// <summary> /// Prepends the path to the appropriate FileTracker assembly to the PATH /// environment variable. Used for inproc tracking, or when the .NET Framework may /// not be on the PATH. /// </summary> /// <returns>The old value of PATH</returns> public static string EnsureFileTrackerOnPath() => EnsureFileTrackerOnPath(null); /// <summary> /// Prepends the path to the appropriate FileTracker assembly to the PATH /// environment variable. Used for inproc tracking, or when the .NET Framework may /// not be on the PATH. /// </summary> /// <param name="rootPath">The root path for FileTracker.dll. Overrides the toolType if specified.</param> /// <returns>The old value of PATH</returns> public static string EnsureFileTrackerOnPath(string rootPath) { string oldPath = Environment.GetEnvironmentVariable(pathEnvironmentVariableName); string fileTrackerPath = GetFileTrackerPath(ExecutableType.SameAsCurrentProcess, rootPath); if (!string.IsNullOrEmpty(fileTrackerPath)) { Environment.SetEnvironmentVariable(pathEnvironmentVariableName, Path.GetDirectoryName(fileTrackerPath) + pathSeparator + oldPath); } return oldPath; } /// <summary> /// Searches %PATH% for the location of Tracker.exe, and returns the first /// path that matches. /// <returns>Matching full path to Tracker.exe or null if a matching path is not found.</returns> /// </summary> public static string FindTrackerOnPath() { string[] paths = Environment.GetEnvironmentVariable(pathEnvironmentVariableName).Split(pathSeparatorArray, StringSplitOptions.RemoveEmptyEntries); foreach (string path in paths) { try { string trackerPath = !Path.IsPathRooted(path) ? Path.GetFullPath(path) : path; trackerPath = Path.Combine(trackerPath, s_TrackerFilename); if (FileSystems.Default.FileExists(trackerPath)) { return trackerPath; } } catch (Exception e) when (ExceptionHandling.IsIoRelatedException(e)) { // ignore this path and move on -- it's just bad for some reason. } } // Still haven't found it. return null; } /// <summary> /// Determines whether we must track out-of-proc, or whether inproc tracking will work. /// </summary> /// <param name="toolType">The executable type for the tool being tracked</param> /// <returns>True if we need to track out-of-proc, false if inproc tracking is OK</returns> public static bool ForceOutOfProcTracking(ExecutableType toolType) => ForceOutOfProcTracking(toolType, null, null); /// <summary> /// Determines whether we must track out-of-proc, or whether inproc tracking will work. /// </summary> /// <param name="toolType">The executable type for the tool being tracked</param> /// <param name="dllName">An optional assembly name.</param> /// <param name="cancelEventName">The name of the cancel event tracker should listen for, or null if there isn't one</param> /// <returns>True if we need to track out-of-proc, false if inproc tracking is OK</returns> public static bool ForceOutOfProcTracking(ExecutableType toolType, string dllName, string cancelEventName) { bool trackOutOfProc = false; if (cancelEventName != null) { // If we have a cancel event, we must track out-of-proc. trackOutOfProc = true; } else if (dllName != null) { // If we have a DLL name, we need to track out of proc -- inproc tracking just uses // the default FileTracker trackOutOfProc = true; } // toolType is not relevant now that Detours can handle child processes of a different // bitness than the parent. return trackOutOfProc; } /// <summary> /// Given the ExecutableType of the tool being wrapped and information that we /// know about our current bitness, figures out and returns the path to the correct /// Tracker.exe. /// </summary> /// <param name="toolType">The <see cref="ExecutableType"/> of the tool being wrapped</param> public static string GetTrackerPath(ExecutableType toolType) => GetTrackerPath(toolType, null); /// <summary> /// Given the ExecutableType of the tool being wrapped and information that we /// know about our current bitness, figures out and returns the path to the correct /// Tracker.exe. /// </summary> /// <param name="toolType">The <see cref="ExecutableType"/> of the tool being wrapped</param> /// <param name="rootPath">The root path for Tracker.exe. Overrides the toolType if specified.</param> public static string GetTrackerPath(ExecutableType toolType, string rootPath) => GetPath(s_TrackerFilename, toolType, rootPath); /// <summary> /// Given the ExecutableType of the tool being wrapped and information that we /// know about our current bitness, figures out and returns the path to the correct /// FileTracker.dll. /// </summary> /// <param name="toolType">The <see cref="ExecutableType"/> of the tool being wrapped</param> public static string GetFileTrackerPath(ExecutableType toolType) => GetFileTrackerPath(toolType, null); /// <summary> /// Given the ExecutableType of the tool being wrapped and information that we /// know about our current bitness, figures out and returns the path to the correct /// FileTracker.dll. /// </summary> /// <param name="toolType">The <see cref="ExecutableType"/> of the tool being wrapped</param> /// <param name="rootPath">The root path for FileTracker.dll. Overrides the toolType if specified.</param> public static string GetFileTrackerPath(ExecutableType toolType, string rootPath) => GetPath(s_FileTrackerFilename, toolType, rootPath); /// <summary> /// Given a filename (only really meant to support either Tracker.exe or FileTracker.dll), returns /// the appropriate path for the appropriate file type. /// </summary> /// <param name="filename"></param> /// <param name="toolType"></param> /// <param name="rootPath">The root path for the file. Overrides the toolType if specified.</param> private static string GetPath(string filename, ExecutableType toolType, string rootPath) { string trackerPath; if (!string.IsNullOrEmpty(rootPath)) { trackerPath = Path.Combine(rootPath, filename); if (!FileSystems.Default.FileExists(trackerPath)) { // if an override path was specified, that's it -- we don't want to fall back if the file // is not found there. trackerPath = null; } } else { // Since Detours can handle cross-bitness process launches, the toolType // can be ignored; just return the path corresponding to the current architecture. trackerPath = GetPath(filename, DotNetFrameworkArchitecture.Current); } return trackerPath; } /// <summary> /// Given a filename (currently only Tracker.exe and FileTracker.dll are supported), return /// the path to that file. /// </summary> /// <param name="filename"></param> /// <param name="bitness"></param> /// <returns></returns> private static string GetPath(string filename, DotNetFrameworkArchitecture bitness) { // Make sure that if someone starts passing the wrong thing to this method we don't silently // eat it and do something possibly unexpected. ErrorUtilities.VerifyThrow( s_TrackerFilename.Equals(filename, StringComparison.OrdinalIgnoreCase) || s_FileTrackerFilename.Equals(filename, StringComparison.OrdinalIgnoreCase), "This method should only be passed s_TrackerFilename or s_FileTrackerFilename, but was passed {0} instead!", filename ); // Look for FileTracker.dll/Tracker.exe in the MSBuild tools directory. They may exist elsewhere on disk, // but other copies aren't guaranteed to be compatible with the latest. var path = ToolLocationHelper.GetPathToBuildToolsFile(filename, ToolLocationHelper.CurrentToolsVersion, bitness); // Due to a Detours limitation, the path to FileTracker32.dll must be // representable in ANSI characters. Look for it first in the global // shared location which is guaranteed to be ANSI. Fall back to // current folder. if (s_FileTrackerFilename.Equals(filename, StringComparison.OrdinalIgnoreCase)) { string progfilesPath = Path.Combine(FrameworkLocationHelper.GenerateProgramFiles32(), "MSBuild", "15.0", "FileTracker", s_FileTrackerFilename); if (FileSystems.Default.FileExists(progfilesPath)) { return progfilesPath; } } return path; } /// <summary> /// This method constructs the correct Tracker.exe response file arguments from its parameters /// </summary> /// <param name="dllName">The name of the dll that will do the tracking</param> /// <param name="intermediateDirectory">Intermediate directory where tracking logs will be written</param> /// <param name="rootFiles">Rooting marker</param> /// <returns>The arguments as a string</returns> public static string TrackerResponseFileArguments(string dllName, string intermediateDirectory, string rootFiles) => TrackerResponseFileArguments(dllName, intermediateDirectory, rootFiles, null); /// <summary> /// This method constructs the correct Tracker.exe response file arguments from its parameters /// </summary> /// <param name="dllName">The name of the dll that will do the tracking</param> /// <param name="intermediateDirectory">Intermediate directory where tracking logs will be written</param> /// <param name="rootFiles">Rooting marker</param> /// <param name="cancelEventName">If a cancel event has been created that Tracker should be listening for, its name is passed here</param> /// <returns>The arguments as a string</returns> public static string TrackerResponseFileArguments(string dllName, string intermediateDirectory, string rootFiles, string cancelEventName) { CommandLineBuilder builder = new CommandLineBuilder(); builder.AppendSwitchIfNotNull("/d ", dllName); if (!string.IsNullOrEmpty(intermediateDirectory)) { intermediateDirectory = FileUtilities.NormalizePath(intermediateDirectory); // If the intermediate directory ends up with a trailing slash, then be rid of it! if (FileUtilities.EndsWithSlash(intermediateDirectory)) { intermediateDirectory = Path.GetDirectoryName(intermediateDirectory); } builder.AppendSwitchIfNotNull("/i ", intermediateDirectory); } builder.AppendSwitchIfNotNull("/r ", rootFiles); builder.AppendSwitchIfNotNull("/b ", cancelEventName); // b for break return builder.ToString() + " "; } /// <summary> /// This method constructs the correct Tracker.exe command arguments from its parameters /// </summary> /// <param name="command">The command to track</param> /// <param name="arguments">The command to track's arguments</param> /// <returns>The arguments as a string</returns> public static string TrackerCommandArguments(string command, string arguments) { CommandLineBuilder builder = new CommandLineBuilder(); builder.AppendSwitch(" /c"); builder.AppendFileNameIfNotNull(command); string fullArguments = builder.ToString(); fullArguments += " " + arguments; return fullArguments; } /// <summary> /// This method constructs the correct Tracker.exe arguments from its parameters /// </summary> /// <param name="command">The command to track</param> /// <param name="arguments">The command to track's arguments</param> /// <param name="dllName">The name of the dll that will do the tracking</param> /// <param name="intermediateDirectory">Intermediate directory where tracking logs will be written</param> /// <param name="rootFiles">Rooting marker</param> /// <returns>The arguments as a string</returns> public static string TrackerArguments(string command, string arguments, string dllName, string intermediateDirectory, string rootFiles) => TrackerArguments(command, arguments, dllName, intermediateDirectory, rootFiles, null); /// <summary> /// This method constructs the correct Tracker.exe arguments from its parameters /// </summary> /// <param name="command">The command to track</param> /// <param name="arguments">The command to track's arguments</param> /// <param name="dllName">The name of the dll that will do the tracking</param> /// <param name="intermediateDirectory">Intermediate directory where tracking logs will be written</param> /// <param name="rootFiles">Rooting marker</param> /// <param name="cancelEventName">If a cancel event has been created that Tracker should be listening for, its name is passed here</param> /// <returns>The arguments as a string</returns> public static string TrackerArguments(string command, string arguments, string dllName, string intermediateDirectory, string rootFiles, string cancelEventName) => TrackerResponseFileArguments(dllName, intermediateDirectory, rootFiles, cancelEventName) + TrackerCommandArguments(command, arguments); #region StartProcess methods /// <summary> /// Start the process; tracking the command. /// </summary> /// <param name="command">The command to track</param> /// <param name="arguments">The command to track's arguments</param> /// <param name="toolType">The type of executable the wrapped tool is</param> /// <param name="dllName">The name of the dll that will do the tracking</param> /// <param name="intermediateDirectory">Intermediate directory where tracking logs will be written</param> /// <param name="rootFiles">Rooting marker</param> /// <param name="cancelEventName">If Tracker should be listening on a particular event for cancellation, pass its name here</param> /// <returns>Process instance</returns> public static Process StartProcess(string command, string arguments, ExecutableType toolType, string dllName, string intermediateDirectory, string rootFiles, string cancelEventName) { dllName ??= GetFileTrackerPath(toolType); string fullArguments = TrackerArguments(command, arguments, dllName, intermediateDirectory, rootFiles, cancelEventName); return Process.Start(GetTrackerPath(toolType), fullArguments); } /// <summary> /// Start the process; tracking the command. /// </summary> /// <param name="command">The command to track</param> /// <param name="arguments">The command to track's arguments</param> /// <param name="toolType">The type of executable the wrapped tool is</param> /// <param name="dllName">The name of the dll that will do the tracking</param> /// <param name="intermediateDirectory">Intermediate directory where tracking logs will be written</param> /// <param name="rootFiles">Rooting marker</param> /// <returns>Process instance</returns> public static Process StartProcess(string command, string arguments, ExecutableType toolType, string dllName, string intermediateDirectory, string rootFiles) => StartProcess(command, arguments, toolType, dllName, intermediateDirectory, rootFiles, null); /// <summary> /// Start the process; tracking the command. /// </summary> /// <param name="command">The command to track</param> /// <param name="arguments">The command to track's arguments</param> /// <param name="toolType">The type of executable the wrapped tool is</param> /// <param name="intermediateDirectory">Intermediate directory where tracking logs will be written</param> /// <param name="rootFiles">Rooting marker</param> /// <returns>Process instance</returns> public static Process StartProcess(string command, string arguments, ExecutableType toolType, string intermediateDirectory, string rootFiles) => StartProcess(command, arguments, toolType, null, intermediateDirectory, rootFiles, null); /// <summary> /// Start the process; tracking the command. /// </summary> /// <param name="command">The command to track</param> /// <param name="arguments">The command to track's arguments</param> /// <param name="toolType">The type of executable the wrapped tool is</param> /// <param name="rootFiles">Rooting marker</param> /// <returns>Process instance</returns> public static Process StartProcess(string command, string arguments, ExecutableType toolType, string rootFiles) => StartProcess(command, arguments, toolType, null, null, rootFiles, null); /// <summary> /// Start the process; tracking the command. /// </summary> /// <param name="command">The command to track</param> /// <param name="arguments">The command to track's arguments</param> /// <param name="toolType">The type of executable the wrapped tool is</param> /// <returns>Process instance</returns> public static Process StartProcess(string command, string arguments, ExecutableType toolType) => StartProcess(command, arguments, toolType, null, null, null, null); #endregion // StartProcess methods /// <summary> /// Logs a message of the given importance using the specified resource string. To the specified Log. /// </summary> /// <remarks>This method is not thread-safe.</remarks> /// <param name="Log">The Log to log to.</param> /// <param name="importance">The importance level of the message.</param> /// <param name="messageResourceName">The name of the string resource to load.</param> /// <param name="messageArgs">Optional arguments for formatting the loaded string.</param> /// <exception cref="ArgumentNullException">Thrown when <c>messageResourceName</c> is null.</exception> internal static void LogMessageFromResources(TaskLoggingHelper Log, MessageImportance importance, string messageResourceName, params object[] messageArgs) { // Only log when we have been passed a TaskLoggingHelper if (Log != null) { ErrorUtilities.VerifyThrowArgumentNull(messageResourceName, nameof(messageResourceName)); Log.LogMessage(importance, AssemblyResources.FormatResourceString(messageResourceName, messageArgs)); } } /// <summary> /// Logs a message of the given importance using the specified string. /// </summary> /// <remarks>This method is not thread-safe.</remarks> /// <param name="Log">The Log to log to.</param> /// <param name="importance">The importance level of the message.</param> /// <param name="message">The message string.</param> /// <param name="messageArgs">Optional arguments for formatting the message string.</param> /// <exception cref="ArgumentNullException">Thrown when <c>message</c> is null.</exception> internal static void LogMessage(TaskLoggingHelper Log, MessageImportance importance, string message, params object[] messageArgs) { // Only log when we have been passed a TaskLoggingHelper Log?.LogMessage(importance, message, messageArgs); } /// <summary> /// Logs a warning using the specified resource string. /// </summary> /// <param name="Log">The Log to log to.</param> /// <param name="messageResourceName">The name of the string resource to load.</param> /// <param name="messageArgs">Optional arguments for formatting the loaded string.</param> /// <exception cref="ArgumentNullException">Thrown when <c>messageResourceName</c> is null.</exception> internal static void LogWarningWithCodeFromResources(TaskLoggingHelper Log, string messageResourceName, params object[] messageArgs) { // Only log when we have been passed a TaskLoggingHelper Log?.LogWarningWithCodeFromResources(messageResourceName, messageArgs); } #endregion } /// <summary> /// Dependency filter delegate. Used during TLog saves in order for tasks to selectively remove dependencies from the written /// graph. /// </summary> /// <param name="fullPath">The full path to the dependency file about to be written to the compacted TLog</param> /// <returns>If the file should actually be written to the TLog (true) or not (false)</returns> public delegate bool DependencyFilter(string fullPath); } #endif
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsAzureCompositeModelClient { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// PrimitiveOperations operations. /// </summary> public partial interface IPrimitiveOperations { /// <summary> /// Get complex types with integer properties /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<IntWrapper>> GetIntWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put complex types with integer properties /// </summary> /// <param name='complexBody'> /// Please put -1 and 2 /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> PutIntWithHttpMessagesAsync(IntWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get complex types with long properties /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<LongWrapper>> GetLongWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put complex types with long properties /// </summary> /// <param name='complexBody'> /// Please put 1099511627775 and -999511627788 /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> PutLongWithHttpMessagesAsync(LongWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get complex types with float properties /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<FloatWrapper>> GetFloatWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put complex types with float properties /// </summary> /// <param name='complexBody'> /// Please put 1.05 and -0.003 /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> PutFloatWithHttpMessagesAsync(FloatWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get complex types with double properties /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<DoubleWrapper>> GetDoubleWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put complex types with double properties /// </summary> /// <param name='complexBody'> /// Please put 3e-100 and /// -0.000000000000000000000000000000000000000000000000000000005 /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> PutDoubleWithHttpMessagesAsync(DoubleWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get complex types with bool properties /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<BooleanWrapper>> GetBoolWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put complex types with bool properties /// </summary> /// <param name='complexBody'> /// Please put true and false /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> PutBoolWithHttpMessagesAsync(BooleanWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get complex types with string properties /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<StringWrapper>> GetStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put complex types with string properties /// </summary> /// <param name='complexBody'> /// Please put 'goodrequest', '', and null /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> PutStringWithHttpMessagesAsync(StringWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get complex types with date properties /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<DateWrapper>> GetDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put complex types with date properties /// </summary> /// <param name='complexBody'> /// Please put '0001-01-01' and '2016-02-29' /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> PutDateWithHttpMessagesAsync(DateWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get complex types with datetime properties /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<DatetimeWrapper>> GetDateTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put complex types with datetime properties /// </summary> /// <param name='complexBody'> /// Please put '0001-01-01T12:00:00-04:00' and /// '2015-05-18T11:38:00-08:00' /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> PutDateTimeWithHttpMessagesAsync(DatetimeWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get complex types with datetimeRfc1123 properties /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<Datetimerfc1123Wrapper>> GetDateTimeRfc1123WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put complex types with datetimeRfc1123 properties /// </summary> /// <param name='complexBody'> /// Please put 'Mon, 01 Jan 0001 12:00:00 GMT' and 'Mon, 18 May 2015 /// 11:38:00 GMT' /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> PutDateTimeRfc1123WithHttpMessagesAsync(Datetimerfc1123Wrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get complex types with duration properties /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<DurationWrapper>> GetDurationWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put complex types with duration properties /// </summary> /// <param name='field'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<AzureOperationResponse> PutDurationWithHttpMessagesAsync(TimeSpan? field = default(TimeSpan?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get complex types with byte properties /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<ByteWrapper>> GetByteWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put complex types with byte properties /// </summary> /// <param name='field'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<AzureOperationResponse> PutByteWithHttpMessagesAsync(byte[] field = default(byte[]), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Serialization { using System; using System.IO; using System.Collections; using System.Reflection; using System.Reflection.Emit; using System.Xml.Schema; using System.ComponentModel; using System.Diagnostics; using System.CodeDom.Compiler; using System.Globalization; using System.Text; using System.Threading; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Xml.Extensions; using XmlSchema = System.ServiceModel.Dispatcher.XmlSchemaConstants; /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter"]/*' /> ///<internalonly/> public abstract class XmlSerializationWriter : XmlSerializationGeneratedCode { private XmlWriter _w; private XmlSerializerNamespaces _namespaces; private int _tempNamespacePrefix; private HashSet<int> _usedPrefixes; private HashSet<object> _objectsInUse; private string _aliasBase = "q"; private bool _escapeName = true; // this method must be called before any generated serialization methods are called internal void Init(XmlWriter w, XmlSerializerNamespaces namespaces, string encodingStyle, string idBase) { _w = w; _namespaces = namespaces; } // this method must be called before any generated serialization methods are called internal void Init(XmlWriter w, XmlSerializerNamespaces namespaces, string encodingStyle, string idBase, TempAssembly tempAssembly) { Init(w, namespaces, encodingStyle, idBase); Init(tempAssembly); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.EscapeName"]/*' /> protected bool EscapeName { get { return _escapeName; } set { _escapeName = value; } } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.Writer"]/*' /> protected XmlWriter Writer { get { return _w; } set { _w = value; } } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.Namespaces"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected IList XmlNamespaces { get { return _namespaces == null ? null : _namespaces.NamespaceList; } set { if (value == null) { _namespaces = null; } else { Array array = Array.CreateInstance(typeof(XmlQualifiedName), value.Count); value.CopyTo(array, 0); XmlQualifiedName[] qnames = (XmlQualifiedName[])array; _namespaces = new XmlSerializerNamespaces(qnames); } } } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromByteArrayBase64"]/*' /> protected static byte[] FromByteArrayBase64(byte[] value) { // Unlike other "From" functions that one is just a place holder for automatic code generation. // The reason is performance and memory consumption for (potentially) big 64base-encoded chunks // And it is assumed that the caller generates the code that will distinguish between byte[] and string return types // return value; } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromByteArrayHex"]/*' /> protected static string FromByteArrayHex(byte[] value) { return XmlCustomFormatter.FromByteArrayHex(value); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromDateTime"]/*' /> protected static string FromDateTime(DateTime value) { return XmlCustomFormatter.FromDateTime(value); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromDate"]/*' /> protected static string FromDate(DateTime value) { return XmlCustomFormatter.FromDate(value); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromTime"]/*' /> protected static string FromTime(DateTime value) { return XmlCustomFormatter.FromTime(value); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromChar"]/*' /> protected static string FromChar(char value) { return XmlCustomFormatter.FromChar(value); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromEnum"]/*' /> protected static string FromEnum(long value, string[] values, long[] ids) { return XmlCustomFormatter.FromEnum(value, values, ids, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromEnum1"]/*' /> protected static string FromEnum(long value, string[] values, long[] ids, string typeName) { return XmlCustomFormatter.FromEnum(value, values, ids, typeName); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromXmlName"]/*' /> protected static string FromXmlName(string name) { return XmlCustomFormatter.FromXmlName(name); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromXmlNCName"]/*' /> protected static string FromXmlNCName(string ncName) { return XmlCustomFormatter.FromXmlNCName(ncName); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromXmlNmToken"]/*' /> protected static string FromXmlNmToken(string nmToken) { return XmlCustomFormatter.FromXmlNmToken(nmToken); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromXmlNmTokens"]/*' /> protected static string FromXmlNmTokens(string nmTokens) { return XmlCustomFormatter.FromXmlNmTokens(nmTokens); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteXsiType"]/*' /> protected void WriteXsiType(string name, string ns) { WriteAttribute("type", XmlSchema.InstanceNamespace, GetQualifiedName(name, ns)); } private XmlQualifiedName GetPrimitiveTypeName(Type type) { return GetPrimitiveTypeName(type, true); } private XmlQualifiedName GetPrimitiveTypeName(Type type, bool throwIfUnknown) { XmlQualifiedName qname = GetPrimitiveTypeNameInternal(type); if (throwIfUnknown && qname == null) throw CreateUnknownTypeException(type); return qname; } internal static XmlQualifiedName GetPrimitiveTypeNameInternal(Type type) { string typeName; string typeNs = XmlSchema.Namespace; switch (type.GetTypeCode()) { case TypeCode.String: typeName = "string"; break; case TypeCode.Int32: typeName = "int"; break; case TypeCode.Boolean: typeName = "boolean"; break; case TypeCode.Int16: typeName = "short"; break; case TypeCode.Int64: typeName = "long"; break; case TypeCode.Single: typeName = "float"; break; case TypeCode.Double: typeName = "double"; break; case TypeCode.Decimal: typeName = "decimal"; break; case TypeCode.DateTime: typeName = "dateTime"; break; case TypeCode.Byte: typeName = "unsignedByte"; break; case TypeCode.SByte: typeName = "byte"; break; case TypeCode.UInt16: typeName = "unsignedShort"; break; case TypeCode.UInt32: typeName = "unsignedInt"; break; case TypeCode.UInt64: typeName = "unsignedLong"; break; case TypeCode.Char: typeName = "char"; typeNs = UrtTypes.Namespace; break; default: if (type == typeof(XmlQualifiedName)) typeName = "QName"; else if (type == typeof(byte[])) typeName = "base64Binary"; else if (type == typeof(Guid)) { typeName = "guid"; typeNs = UrtTypes.Namespace; } else if (type == typeof (TimeSpan)) { typeName = "TimeSpan"; typeNs = UrtTypes.Namespace; } else if (type == typeof (XmlNode[])) { typeName = Soap.UrType; } else return null; break; } return new XmlQualifiedName(typeName, typeNs); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteTypedPrimitive"]/*' /> protected void WriteTypedPrimitive(string name, string ns, object o, bool xsiType) { string value = null; string type; string typeNs = XmlSchema.Namespace; bool writeRaw = true; bool writeDirect = false; Type t = o.GetType(); bool wroteStartElement = false; switch (t.GetTypeCode()) { case TypeCode.String: value = (string)o; type = "string"; writeRaw = false; break; case TypeCode.Int32: value = XmlConvert.ToString((int)o); type = "int"; break; case TypeCode.Boolean: value = XmlConvert.ToString((bool)o); type = "boolean"; break; case TypeCode.Int16: value = XmlConvert.ToString((short)o); type = "short"; break; case TypeCode.Int64: value = XmlConvert.ToString((long)o); type = "long"; break; case TypeCode.Single: value = XmlConvert.ToString((float)o); type = "float"; break; case TypeCode.Double: value = XmlConvert.ToString((double)o); type = "double"; break; case TypeCode.Decimal: value = XmlConvert.ToString((decimal)o); type = "decimal"; break; case TypeCode.DateTime: value = FromDateTime((DateTime)o); type = "dateTime"; break; case TypeCode.Char: value = FromChar((char)o); type = "char"; typeNs = UrtTypes.Namespace; break; case TypeCode.Byte: value = XmlConvert.ToString((byte)o); type = "unsignedByte"; break; case TypeCode.SByte: value = XmlConvert.ToString((sbyte)o); type = "byte"; break; case TypeCode.UInt16: value = XmlConvert.ToString((UInt16)o); type = "unsignedShort"; break; case TypeCode.UInt32: value = XmlConvert.ToString((UInt32)o); type = "unsignedInt"; break; case TypeCode.UInt64: value = XmlConvert.ToString((UInt64)o); type = "unsignedLong"; break; default: if (t == typeof(XmlQualifiedName)) { type = "QName"; // need to write start element ahead of time to establish context // for ns definitions by FromXmlQualifiedName wroteStartElement = true; if (name == null) _w.WriteStartElement(type, typeNs); else _w.WriteStartElement(name, ns); value = FromXmlQualifiedName((XmlQualifiedName)o, false); } else if (t == typeof(byte[])) { value = String.Empty; writeDirect = true; type = "base64Binary"; } else if (t == typeof(Guid)) { value = XmlConvert.ToString((Guid)o); type = "guid"; typeNs = UrtTypes.Namespace; } else if (t == typeof(TimeSpan)) { value = XmlConvert.ToString((TimeSpan)o); type = "TimeSpan"; typeNs = UrtTypes.Namespace; } else if (typeof(XmlNode[]).IsAssignableFrom(t)) { if (name == null) _w.WriteStartElement(Soap.UrType, XmlSchema.Namespace); else _w.WriteStartElement(name, ns); XmlNode[] xmlNodes = (XmlNode[])o; for (int i = 0; i < xmlNodes.Length; i++) { if (xmlNodes[i] == null) continue; xmlNodes[i].WriteTo(_w); } _w.WriteEndElement(); return; } else throw CreateUnknownTypeException(t); break; } if (!wroteStartElement) { if (name == null) _w.WriteStartElement(type, typeNs); else _w.WriteStartElement(name, ns); } if (xsiType) WriteXsiType(type, typeNs); if (value == null) { _w.WriteAttributeString("nil", XmlSchema.InstanceNamespace, "true"); } else if (writeDirect) { // only one type currently writes directly to XML stream XmlCustomFormatter.WriteArrayBase64(_w, (byte[])o, 0, ((byte[])o).Length); } else if (writeRaw) { _w.WriteRaw(value); } else _w.WriteString(value); _w.WriteEndElement(); } private string GetQualifiedName(string name, string ns) { if (ns == null || ns.Length == 0) return name; string prefix = _w.LookupPrefix(ns); if (prefix == null) { if (ns == XmlReservedNs.NsXml) { prefix = "xml"; } else { prefix = NextPrefix(); WriteAttribute("xmlns", prefix, null, ns); } } else if (prefix.Length == 0) { return name; } return prefix + ":" + name; } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromXmlQualifiedName"]/*' /> protected string FromXmlQualifiedName(XmlQualifiedName xmlQualifiedName) { return FromXmlQualifiedName(xmlQualifiedName, true); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromXmlQualifiedName"]/*' /> protected string FromXmlQualifiedName(XmlQualifiedName xmlQualifiedName, bool ignoreEmpty) { if (xmlQualifiedName == null) return null; if (xmlQualifiedName.IsEmpty && ignoreEmpty) return null; return GetQualifiedName(EscapeName ? XmlConvert.EncodeLocalName(xmlQualifiedName.Name) : xmlQualifiedName.Name, xmlQualifiedName.Namespace); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteStartElement"]/*' /> protected void WriteStartElement(string name) { WriteStartElement(name, null, null, false, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteStartElement1"]/*' /> protected void WriteStartElement(string name, string ns) { WriteStartElement(name, ns, null, false, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteStartElement4"]/*' /> protected void WriteStartElement(string name, string ns, bool writePrefixed) { WriteStartElement(name, ns, null, writePrefixed, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteStartElement2"]/*' /> protected void WriteStartElement(string name, string ns, object o) { WriteStartElement(name, ns, o, false, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteStartElement3"]/*' /> protected void WriteStartElement(string name, string ns, object o, bool writePrefixed) { WriteStartElement(name, ns, o, writePrefixed, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteStartElement5"]/*' /> protected void WriteStartElement(string name, string ns, object o, bool writePrefixed, XmlSerializerNamespaces xmlns) { if (o != null && _objectsInUse != null) { if (!_objectsInUse.Add(o)) throw new InvalidOperationException(SR.Format(SR.XmlCircularReference, o.GetType().FullName)); } string prefix = null; bool needEmptyDefaultNamespace = false; if (_namespaces != null) { foreach (string alias in _namespaces.Namespaces.Keys) { string aliasNs = (string)_namespaces.Namespaces[alias]; if (alias.Length > 0 && aliasNs == ns) prefix = alias; if (alias.Length == 0) { if (aliasNs == null || aliasNs.Length == 0) needEmptyDefaultNamespace = true; if (ns != aliasNs) writePrefixed = true; } } _usedPrefixes = ListUsedPrefixes(_namespaces.Namespaces, _aliasBase); } if (writePrefixed && prefix == null && ns != null && ns.Length > 0) { prefix = _w.LookupPrefix(ns); if (prefix == null || prefix.Length == 0) { prefix = NextPrefix(); } } if (prefix == null && xmlns != null) { prefix = xmlns.LookupPrefix(ns); } if (needEmptyDefaultNamespace && prefix == null && ns != null && ns.Length != 0) prefix = NextPrefix(); _w.WriteStartElement(prefix, name, ns); if (_namespaces != null) { foreach (string alias in _namespaces.Namespaces.Keys) { string aliasNs = (string)_namespaces.Namespaces[alias]; if (alias.Length == 0 && (aliasNs == null || aliasNs.Length == 0)) continue; if (aliasNs == null || aliasNs.Length == 0) { if (alias.Length > 0) throw new InvalidOperationException(SR.Format(SR.XmlInvalidXmlns, alias)); WriteAttribute("xmlns", alias, null, aliasNs); } else { if (_w.LookupPrefix(aliasNs) == null) { // write the default namespace declaration only if we have not written it already, over wise we just ignore one provided by the user if (prefix == null && alias.Length == 0) break; WriteAttribute("xmlns", alias, null, aliasNs); } } } } WriteNamespaceDeclarations(xmlns); } private HashSet<int> ListUsedPrefixes(Dictionary<string, string> nsList, string prefix) { var qnIndexes = new HashSet<int>(); int prefixLength = prefix.Length; const string MaxInt32 = "2147483647"; foreach (string alias in _namespaces.Namespaces.Keys) { string name; if (alias.Length > prefixLength) { name = alias; if (name.Length > prefixLength && name.Length <= prefixLength + MaxInt32.Length && name.StartsWith(prefix, StringComparison.Ordinal)) { bool numeric = true; for (int j = prefixLength; j < name.Length; j++) { if (!Char.IsDigit(name, j)) { numeric = false; break; } } if (numeric) { Int64 index = Int64.Parse(name.Substring(prefixLength), NumberStyles.Integer, CultureInfo.InvariantCulture); if (index <= Int32.MaxValue) { Int32 newIndex = (Int32)index; qnIndexes.Add(newIndex); } } } } } if (qnIndexes.Count > 0) { return qnIndexes; } return null; } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteNullTagEncoded"]/*' /> protected void WriteNullTagEncoded(string name) { WriteNullTagEncoded(name, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteNullTagEncoded1"]/*' /> protected void WriteNullTagEncoded(string name, string ns) { if (name == null || name.Length == 0) return; WriteStartElement(name, ns, null, true); _w.WriteAttributeString("nil", XmlSchema.InstanceNamespace, "true"); _w.WriteEndElement(); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteNullTagLiteral"]/*' /> protected void WriteNullTagLiteral(string name) { WriteNullTagLiteral(name, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteNullTag1"]/*' /> protected void WriteNullTagLiteral(string name, string ns) { if (name == null || name.Length == 0) return; WriteStartElement(name, ns, null, false); _w.WriteAttributeString("nil", XmlSchema.InstanceNamespace, "true"); _w.WriteEndElement(); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteEmptyTag"]/*' /> protected void WriteEmptyTag(string name) { WriteEmptyTag(name, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteEmptyTag1"]/*' /> protected void WriteEmptyTag(string name, string ns) { if (name == null || name.Length == 0) return; WriteStartElement(name, ns, null, false); _w.WriteEndElement(); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteEndElement"]/*' /> protected void WriteEndElement() { _w.WriteEndElement(); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteEndElement1"]/*' /> protected void WriteEndElement(object o) { _w.WriteEndElement(); if (o != null && _objectsInUse != null) { #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (!_objectsInUse.Contains(o)) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "missing stack object of type " + o.GetType().FullName)); #endif _objectsInUse.Remove(o); } } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteSerializable"]/*' /> protected void WriteSerializable(IXmlSerializable serializable, string name, string ns, bool isNullable) { WriteSerializable(serializable, name, ns, isNullable, true); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteSerializable1"]/*' /> protected void WriteSerializable(IXmlSerializable serializable, string name, string ns, bool isNullable, bool wrapped) { if (serializable == null) { if (isNullable) WriteNullTagLiteral(name, ns); return; } if (wrapped) { _w.WriteStartElement(name, ns); } serializable.WriteXml(_w); if (wrapped) { _w.WriteEndElement(); } } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteNullableStringEncoded"]/*' /> protected void WriteNullableStringEncoded(string name, string ns, string value, XmlQualifiedName xsiType) { if (value == null) WriteNullTagEncoded(name, ns); else WriteElementString(name, ns, value, xsiType); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteNullableStringLiteral"]/*' /> protected void WriteNullableStringLiteral(string name, string ns, string value) { if (value == null) WriteNullTagLiteral(name, ns); else WriteElementString(name, ns, value, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteNullableStringEncodedRaw"]/*' /> protected void WriteNullableStringEncodedRaw(string name, string ns, string value, XmlQualifiedName xsiType) { if (value == null) WriteNullTagEncoded(name, ns); else WriteElementStringRaw(name, ns, value, xsiType); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteNullableStringEncodedRaw1"]/*' /> protected void WriteNullableStringEncodedRaw(string name, string ns, byte[] value, XmlQualifiedName xsiType) { if (value == null) WriteNullTagEncoded(name, ns); else WriteElementStringRaw(name, ns, value, xsiType); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteNullableStringLiteralRaw"]/*' /> protected void WriteNullableStringLiteralRaw(string name, string ns, string value) { if (value == null) WriteNullTagLiteral(name, ns); else WriteElementStringRaw(name, ns, value, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteNullableStringLiteralRaw1"]/*' /> protected void WriteNullableStringLiteralRaw(string name, string ns, byte[] value) { if (value == null) WriteNullTagLiteral(name, ns); else WriteElementStringRaw(name, ns, value, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteNullableQualifiedNameEncoded"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected void WriteNullableQualifiedNameEncoded(string name, string ns, XmlQualifiedName value, XmlQualifiedName xsiType) { if (value == null) WriteNullTagEncoded(name, ns); else WriteElementQualifiedName(name, ns, value, xsiType); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteNullableQualifiedNameLiteral"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected void WriteNullableQualifiedNameLiteral(string name, string ns, XmlQualifiedName value) { if (value == null) WriteNullTagLiteral(name, ns); else WriteElementQualifiedName(name, ns, value, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementLiteral"]/*' /> protected void WriteElementLiteral(XmlNode node, string name, string ns, bool isNullable, bool any) { if (node == null) { if (isNullable) WriteNullTagLiteral(name, ns); return; } WriteElement(node, name, ns, isNullable, any); } private void WriteElement(XmlNode node, string name, string ns, bool isNullable, bool any) { if (typeof(XmlAttribute).IsAssignableFrom(node.GetType())) throw new InvalidOperationException(SR.XmlNoAttributeHere); if (node is XmlDocument) { node = ((XmlDocument)node).DocumentElement; if (node == null) { if (isNullable) WriteNullTagEncoded(name, ns); return; } } if (any) { if (node is XmlElement && name != null && name.Length > 0) { // need to check against schema if (node.LocalName != name || node.NamespaceURI != ns) throw new InvalidOperationException(SR.Format(SR.XmlElementNameMismatch, node.LocalName, node.NamespaceURI, name, ns)); } } else _w.WriteStartElement(name, ns); node.WriteTo(_w); if (!any) _w.WriteEndElement(); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.CreateUnknownTypeException"]/*' /> protected Exception CreateUnknownTypeException(object o) { return CreateUnknownTypeException(o.GetType()); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.CreateUnknownTypeException1"]/*' /> protected Exception CreateUnknownTypeException(Type type) { if (typeof(IXmlSerializable).IsAssignableFrom(type)) return new InvalidOperationException(SR.Format(SR.XmlInvalidSerializable, type.FullName)); TypeDesc typeDesc = new TypeScope().GetTypeDesc(type); if (!typeDesc.IsStructLike) return new InvalidOperationException(SR.Format(SR.XmlInvalidUseOfType, type.FullName)); return new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, type.FullName)); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.CreateMismatchChoiceException"]/*' /> protected Exception CreateMismatchChoiceException(string value, string elementName, string enumValue) { // Value of {0} mismatches the type of {1}, you need to set it to {2}. return new InvalidOperationException(SR.Format(SR.XmlChoiceMismatchChoiceException, elementName, value, enumValue)); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.CreateUnknownAnyElementException"]/*' /> protected Exception CreateUnknownAnyElementException(string name, string ns) { return new InvalidOperationException(SR.Format(SR.XmlUnknownAnyElement, name, ns)); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.CreateInvalidChoiceIdentifierValueException"]/*' /> protected Exception CreateInvalidChoiceIdentifierValueException(string type, string identifier) { return new InvalidOperationException(SR.Format(SR.XmlInvalidChoiceIdentifierValue, type, identifier)); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.CreateChoiceIdentifierValueException"]/*' /> protected Exception CreateChoiceIdentifierValueException(string value, string identifier, string name, string ns) { // XmlChoiceIdentifierMismatch=Value '{0}' of the choice identifier '{1}' does not match element '{2}' from namespace '{3}'. return new InvalidOperationException(SR.Format(SR.XmlChoiceIdentifierMismatch, value, identifier, name, ns)); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.CreateInvalidEnumValueException"]/*' /> protected Exception CreateInvalidEnumValueException(object value, string typeName) { return new InvalidOperationException(SR.Format(SR.XmlUnknownConstant, value, typeName)); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.CreateInvalidAnyTypeException"]/*' /> protected Exception CreateInvalidAnyTypeException(object o) { return CreateInvalidAnyTypeException(o.GetType()); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.CreateInvalidAnyTypeException1"]/*' /> protected Exception CreateInvalidAnyTypeException(Type type) { return new InvalidOperationException(SR.Format(SR.XmlIllegalAnyElement, type.FullName)); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteXmlAttribute1"]/*' /> protected void WriteXmlAttribute(XmlNode node) { WriteXmlAttribute(node, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteXmlAttribute2"]/*' /> protected void WriteXmlAttribute(XmlNode node, object container) { XmlAttribute attr = node as XmlAttribute; if (attr == null) throw new InvalidOperationException(SR.XmlNeedAttributeHere); if (attr.Value != null) { if (attr.NamespaceURI == Wsdl.Namespace && attr.LocalName == Wsdl.ArrayType) { string dims; XmlQualifiedName qname = TypeScope.ParseWsdlArrayType(attr.Value, out dims, (container is XmlSchemaObject) ? (XmlSchemaObject)container : null); string value = FromXmlQualifiedName(qname, true) + dims; //<xsd:attribute xmlns:q3="s0" wsdl:arrayType="q3:FoosBase[]" xmlns:q4="http://schemas.xmlsoap.org/soap/encoding/" ref="q4:arrayType" /> WriteAttribute(Wsdl.ArrayType, Wsdl.Namespace, value); } else { WriteAttribute(attr.Name, attr.NamespaceURI, attr.Value); } } } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteAttribute"]/*' /> protected void WriteAttribute(string localName, string ns, string value) { if (value == null) return; if (localName == "xmlns" || localName.StartsWith("xmlns:", StringComparison.Ordinal)) { ; } else { int colon = localName.IndexOf(':'); if (colon < 0) { if (ns == XmlReservedNs.NsXml) { string prefix = _w.LookupPrefix(ns); if (prefix == null || prefix.Length == 0) prefix = "xml"; _w.WriteAttributeString(prefix, localName, ns, value); } else { _w.WriteAttributeString(localName, ns, value); } } else { string prefix = localName.Substring(0, colon); _w.WriteAttributeString(prefix, localName.Substring(colon + 1), ns, value); } } } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteAttribute0"]/*' /> protected void WriteAttribute(string localName, string ns, byte[] value) { if (value == null) return; if (localName == "xmlns" || localName.StartsWith("xmlns:", StringComparison.Ordinal)) { ; } else { int colon = localName.IndexOf(':'); if (colon < 0) { if (ns == XmlReservedNs.NsXml) { string prefix = _w.LookupPrefix(ns); if (prefix == null || prefix.Length == 0) prefix = "xml"; _w.WriteStartAttribute("xml", localName, ns); } else { _w.WriteStartAttribute(null, localName, ns); } } else { string prefix = _w.LookupPrefix(ns); _w.WriteStartAttribute(prefix, localName.Substring(colon + 1), ns); } XmlCustomFormatter.WriteArrayBase64(_w, value, 0, value.Length); _w.WriteEndAttribute(); } } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteAttribute1"]/*' /> protected void WriteAttribute(string localName, string value) { if (value == null) return; _w.WriteAttributeString(localName, null, value); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteAttribute01"]/*' /> protected void WriteAttribute(string localName, byte[] value) { if (value == null) return; _w.WriteStartAttribute(null, localName, (string)null); XmlCustomFormatter.WriteArrayBase64(_w, value, 0, value.Length); _w.WriteEndAttribute(); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteAttribute2"]/*' /> protected void WriteAttribute(string prefix, string localName, string ns, string value) { if (value == null) return; _w.WriteAttributeString(prefix, localName, null, value); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteValue"]/*' /> protected void WriteValue(string value) { if (value == null) return; _w.WriteString(value); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteValue01"]/*' /> protected void WriteValue(byte[] value) { if (value == null) return; XmlCustomFormatter.WriteArrayBase64(_w, value, 0, value.Length); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteStartDocument"]/*' /> protected void WriteStartDocument() { if (_w.WriteState == WriteState.Start) { _w.WriteStartDocument(); } } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementString"]/*' /> protected void WriteElementString(String localName, String value) { WriteElementString(localName, null, value, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementString1"]/*' /> protected void WriteElementString(String localName, String ns, String value) { WriteElementString(localName, ns, value, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementString2"]/*' /> protected void WriteElementString(String localName, String value, XmlQualifiedName xsiType) { WriteElementString(localName, null, value, xsiType); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementString3"]/*' /> protected void WriteElementString(String localName, String ns, String value, XmlQualifiedName xsiType) { if (value == null) return; if (xsiType == null) _w.WriteElementString(localName, ns, value); else { _w.WriteStartElement(localName, ns); WriteXsiType(xsiType.Name, xsiType.Namespace); _w.WriteString(value); _w.WriteEndElement(); } } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementStringRaw"]/*' /> protected void WriteElementStringRaw(String localName, String value) { WriteElementStringRaw(localName, null, value, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementStringRaw0"]/*' /> protected void WriteElementStringRaw(String localName, byte[] value) { WriteElementStringRaw(localName, null, value, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementStringRaw1"]/*' /> protected void WriteElementStringRaw(String localName, String ns, String value) { WriteElementStringRaw(localName, ns, value, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementStringRaw01"]/*' /> protected void WriteElementStringRaw(String localName, String ns, byte[] value) { WriteElementStringRaw(localName, ns, value, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementStringRaw2"]/*' /> protected void WriteElementStringRaw(String localName, String value, XmlQualifiedName xsiType) { WriteElementStringRaw(localName, null, value, xsiType); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementStringRaw02"]/*' /> protected void WriteElementStringRaw(String localName, byte[] value, XmlQualifiedName xsiType) { WriteElementStringRaw(localName, null, value, xsiType); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementStringRaw3"]/*' /> protected void WriteElementStringRaw(String localName, String ns, String value, XmlQualifiedName xsiType) { if (value == null) return; _w.WriteStartElement(localName, ns); if (xsiType != null) WriteXsiType(xsiType.Name, xsiType.Namespace); _w.WriteRaw(value); _w.WriteEndElement(); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementStringRaw03"]/*' /> protected void WriteElementStringRaw(String localName, String ns, byte[] value, XmlQualifiedName xsiType) { if (value == null) return; _w.WriteStartElement(localName, ns); if (xsiType != null) WriteXsiType(xsiType.Name, xsiType.Namespace); XmlCustomFormatter.WriteArrayBase64(_w, value, 0, value.Length); _w.WriteEndElement(); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementQualifiedName"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected void WriteElementQualifiedName(String localName, XmlQualifiedName value) { WriteElementQualifiedName(localName, null, value, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementQualifiedName1"]/*' /> protected void WriteElementQualifiedName(string localName, XmlQualifiedName value, XmlQualifiedName xsiType) { WriteElementQualifiedName(localName, null, value, xsiType); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementQualifiedName2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected void WriteElementQualifiedName(String localName, String ns, XmlQualifiedName value) { WriteElementQualifiedName(localName, ns, value, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementQualifiedName3"]/*' /> protected void WriteElementQualifiedName(string localName, string ns, XmlQualifiedName value, XmlQualifiedName xsiType) { if (value == null) return; if (value.Namespace == null || value.Namespace.Length == 0) { WriteStartElement(localName, ns, null, true); WriteAttribute("xmlns", ""); } else _w.WriteStartElement(localName, ns); if (xsiType != null) WriteXsiType(xsiType.Name, xsiType.Namespace); _w.WriteString(FromXmlQualifiedName(value, false)); _w.WriteEndElement(); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.InitCallbacks"]/*' /> protected abstract void InitCallbacks(); /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.TopLevelElement"]/*' /> protected void TopLevelElement() { _objectsInUse = new HashSet<object>(); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteNamespaceDeclarations"]/*' /> ///<internalonly/> protected void WriteNamespaceDeclarations(XmlSerializerNamespaces xmlns) { if (xmlns != null) { foreach (KeyValuePair<string, string> entry in xmlns.Namespaces) { string prefix = (string)entry.Key; string ns = (string)entry.Value; if (_namespaces != null) { string oldNs = _namespaces.Namespaces[prefix] as string; if (oldNs != null && oldNs != ns) { throw new InvalidOperationException(SR.Format(SR.XmlDuplicateNs, prefix, ns)); } } string oldPrefix = (ns == null || ns.Length == 0) ? null : Writer.LookupPrefix(ns); if (oldPrefix == null || oldPrefix != prefix) { WriteAttribute("xmlns", prefix, null, ns); } } } _namespaces = null; } private string NextPrefix() { if (_usedPrefixes == null) { return _aliasBase + (++_tempNamespacePrefix); } while (_usedPrefixes.Contains(++_tempNamespacePrefix)) {; } return _aliasBase + _tempNamespacePrefix; } } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriteCallback"]/*' /> ///<internalonly/> public delegate void XmlSerializationWriteCallback(object o); }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Text; namespace System.Net.Http.Headers { public class CacheControlHeaderValue : ICloneable { private const string maxAgeString = "max-age"; private const string maxStaleString = "max-stale"; private const string minFreshString = "min-fresh"; private const string mustRevalidateString = "must-revalidate"; private const string noCacheString = "no-cache"; private const string noStoreString = "no-store"; private const string noTransformString = "no-transform"; private const string onlyIfCachedString = "only-if-cached"; private const string privateString = "private"; private const string proxyRevalidateString = "proxy-revalidate"; private const string publicString = "public"; private const string sharedMaxAgeString = "s-maxage"; private static readonly HttpHeaderParser s_nameValueListParser = GenericHeaderParser.MultipleValueNameValueParser; private static readonly Action<string> s_checkIsValidToken = CheckIsValidToken; private bool _noCache; private ObjectCollection<string> _noCacheHeaders; private bool _noStore; private TimeSpan? _maxAge; private TimeSpan? _sharedMaxAge; private bool _maxStale; private TimeSpan? _maxStaleLimit; private TimeSpan? _minFresh; private bool _noTransform; private bool _onlyIfCached; private bool _publicField; private bool _privateField; private ObjectCollection<string> _privateHeaders; private bool _mustRevalidate; private bool _proxyRevalidate; private ObjectCollection<NameValueHeaderValue> _extensions; public bool NoCache { get { return _noCache; } set { _noCache = value; } } public ICollection<string> NoCacheHeaders { get { if (_noCacheHeaders == null) { _noCacheHeaders = new ObjectCollection<string>(s_checkIsValidToken); } return _noCacheHeaders; } } public bool NoStore { get { return _noStore; } set { _noStore = value; } } public TimeSpan? MaxAge { get { return _maxAge; } set { _maxAge = value; } } public TimeSpan? SharedMaxAge { get { return _sharedMaxAge; } set { _sharedMaxAge = value; } } public bool MaxStale { get { return _maxStale; } set { _maxStale = value; } } public TimeSpan? MaxStaleLimit { get { return _maxStaleLimit; } set { _maxStaleLimit = value; } } public TimeSpan? MinFresh { get { return _minFresh; } set { _minFresh = value; } } public bool NoTransform { get { return _noTransform; } set { _noTransform = value; } } public bool OnlyIfCached { get { return _onlyIfCached; } set { _onlyIfCached = value; } } public bool Public { get { return _publicField; } set { _publicField = value; } } public bool Private { get { return _privateField; } set { _privateField = value; } } public ICollection<string> PrivateHeaders { get { if (_privateHeaders == null) { _privateHeaders = new ObjectCollection<string>(s_checkIsValidToken); } return _privateHeaders; } } public bool MustRevalidate { get { return _mustRevalidate; } set { _mustRevalidate = value; } } public bool ProxyRevalidate { get { return _proxyRevalidate; } set { _proxyRevalidate = value; } } public ICollection<NameValueHeaderValue> Extensions { get { if (_extensions == null) { _extensions = new ObjectCollection<NameValueHeaderValue>(); } return _extensions; } } public CacheControlHeaderValue() { } private CacheControlHeaderValue(CacheControlHeaderValue source) { Debug.Assert(source != null); _noCache = source._noCache; _noStore = source._noStore; _maxAge = source._maxAge; _sharedMaxAge = source._sharedMaxAge; _maxStale = source._maxStale; _maxStaleLimit = source._maxStaleLimit; _minFresh = source._minFresh; _noTransform = source._noTransform; _onlyIfCached = source._onlyIfCached; _publicField = source._publicField; _privateField = source._privateField; _mustRevalidate = source._mustRevalidate; _proxyRevalidate = source._proxyRevalidate; if (source._noCacheHeaders != null) { foreach (var noCacheHeader in source._noCacheHeaders) { NoCacheHeaders.Add(noCacheHeader); } } if (source._privateHeaders != null) { foreach (var privateHeader in source._privateHeaders) { PrivateHeaders.Add(privateHeader); } } if (source._extensions != null) { foreach (var extension in source._extensions) { Extensions.Add((NameValueHeaderValue)((ICloneable)extension).Clone()); } } } public override string ToString() { StringBuilder sb = new StringBuilder(); AppendValueIfRequired(sb, _noStore, noStoreString); AppendValueIfRequired(sb, _noTransform, noTransformString); AppendValueIfRequired(sb, _onlyIfCached, onlyIfCachedString); AppendValueIfRequired(sb, _publicField, publicString); AppendValueIfRequired(sb, _mustRevalidate, mustRevalidateString); AppendValueIfRequired(sb, _proxyRevalidate, proxyRevalidateString); if (_noCache) { AppendValueWithSeparatorIfRequired(sb, noCacheString); if ((_noCacheHeaders != null) && (_noCacheHeaders.Count > 0)) { sb.Append("=\""); AppendValues(sb, _noCacheHeaders); sb.Append('\"'); } } if (_maxAge.HasValue) { AppendValueWithSeparatorIfRequired(sb, maxAgeString); sb.Append('='); sb.Append(((int)_maxAge.Value.TotalSeconds).ToString(NumberFormatInfo.InvariantInfo)); } if (_sharedMaxAge.HasValue) { AppendValueWithSeparatorIfRequired(sb, sharedMaxAgeString); sb.Append('='); sb.Append(((int)_sharedMaxAge.Value.TotalSeconds).ToString(NumberFormatInfo.InvariantInfo)); } if (_maxStale) { AppendValueWithSeparatorIfRequired(sb, maxStaleString); if (_maxStaleLimit.HasValue) { sb.Append('='); sb.Append(((int)_maxStaleLimit.Value.TotalSeconds).ToString(NumberFormatInfo.InvariantInfo)); } } if (_minFresh.HasValue) { AppendValueWithSeparatorIfRequired(sb, minFreshString); sb.Append('='); sb.Append(((int)_minFresh.Value.TotalSeconds).ToString(NumberFormatInfo.InvariantInfo)); } if (_privateField) { AppendValueWithSeparatorIfRequired(sb, privateString); if ((_privateHeaders != null) && (_privateHeaders.Count > 0)) { sb.Append("=\""); AppendValues(sb, _privateHeaders); sb.Append('\"'); } } NameValueHeaderValue.ToString(_extensions, ',', false, sb); return sb.ToString(); } public override bool Equals(object obj) { CacheControlHeaderValue other = obj as CacheControlHeaderValue; if (other == null) { return false; } if ((_noCache != other._noCache) || (_noStore != other._noStore) || (_maxAge != other._maxAge) || (_sharedMaxAge != other._sharedMaxAge) || (_maxStale != other._maxStale) || (_maxStaleLimit != other._maxStaleLimit) || (_minFresh != other._minFresh) || (_noTransform != other._noTransform) || (_onlyIfCached != other._onlyIfCached) || (_publicField != other._publicField) || (_privateField != other._privateField) || (_mustRevalidate != other._mustRevalidate) || (_proxyRevalidate != other._proxyRevalidate)) { return false; } if (!HeaderUtilities.AreEqualCollections(_noCacheHeaders, other._noCacheHeaders, StringComparer.OrdinalIgnoreCase)) { return false; } if (!HeaderUtilities.AreEqualCollections(_privateHeaders, other._privateHeaders, StringComparer.OrdinalIgnoreCase)) { return false; } if (!HeaderUtilities.AreEqualCollections(_extensions, other._extensions)) { return false; } return true; } public override int GetHashCode() { // Use a different bit for bool fields: bool.GetHashCode() will return 0 (false) or 1 (true). So we would // end up having the same hash code for e.g. two instances where one has only noCache set and the other // only noStore. int result = _noCache.GetHashCode() ^ (_noStore.GetHashCode() << 1) ^ (_maxStale.GetHashCode() << 2) ^ (_noTransform.GetHashCode() << 3) ^ (_onlyIfCached.GetHashCode() << 4) ^ (_publicField.GetHashCode() << 5) ^ (_privateField.GetHashCode() << 6) ^ (_mustRevalidate.GetHashCode() << 7) ^ (_proxyRevalidate.GetHashCode() << 8); // XOR the hashcode of timespan values with different numbers to make sure two instances with the same // timespan set on different fields result in different hashcodes. result = result ^ (_maxAge.HasValue ? _maxAge.Value.GetHashCode() ^ 1 : 0) ^ (_sharedMaxAge.HasValue ? _sharedMaxAge.Value.GetHashCode() ^ 2 : 0) ^ (_maxStaleLimit.HasValue ? _maxStaleLimit.Value.GetHashCode() ^ 4 : 0) ^ (_minFresh.HasValue ? _minFresh.Value.GetHashCode() ^ 8 : 0); if ((_noCacheHeaders != null) && (_noCacheHeaders.Count > 0)) { foreach (var noCacheHeader in _noCacheHeaders) { result = result ^ StringComparer.OrdinalIgnoreCase.GetHashCode(noCacheHeader); } } if ((_privateHeaders != null) && (_privateHeaders.Count > 0)) { foreach (var privateHeader in _privateHeaders) { result = result ^ StringComparer.OrdinalIgnoreCase.GetHashCode(privateHeader); } } if ((_extensions != null) && (_extensions.Count > 0)) { foreach (var extension in _extensions) { result = result ^ extension.GetHashCode(); } } return result; } public static CacheControlHeaderValue Parse(string input) { int index = 0; return (CacheControlHeaderValue)CacheControlHeaderParser.Parser.ParseValue(input, null, ref index); } public static bool TryParse(string input, out CacheControlHeaderValue parsedValue) { int index = 0; object output; parsedValue = null; if (CacheControlHeaderParser.Parser.TryParseValue(input, null, ref index, out output)) { parsedValue = (CacheControlHeaderValue)output; return true; } return false; } internal static int GetCacheControlLength(string input, int startIndex, CacheControlHeaderValue storeValue, out CacheControlHeaderValue parsedValue) { Debug.Assert(startIndex >= 0); parsedValue = null; if (string.IsNullOrEmpty(input) || (startIndex >= input.Length)) { return 0; } // Cache-Control header consists of a list of name/value pairs, where the value is optional. So use an // instance of NameValueHeaderParser to parse the string. int current = startIndex; object nameValue = null; List<NameValueHeaderValue> nameValueList = new List<NameValueHeaderValue>(); while (current < input.Length) { if (!s_nameValueListParser.TryParseValue(input, null, ref current, out nameValue)) { return 0; } nameValueList.Add(nameValue as NameValueHeaderValue); } // If we get here, we were able to successfully parse the string as list of name/value pairs. Now analyze // the name/value pairs. // Cache-Control is a header supporting lists of values. However, expose the header as an instance of // CacheControlHeaderValue. So if we already have an instance of CacheControlHeaderValue, add the values // from this string to the existing instances. CacheControlHeaderValue result = storeValue; if (result == null) { result = new CacheControlHeaderValue(); } if (!TrySetCacheControlValues(result, nameValueList)) { return 0; } // If we had an existing store value and we just updated that instance, return 'null' to indicate that // we don't have a new instance of CacheControlHeaderValue, but just updated an existing one. This is the // case if we have multiple 'Cache-Control' headers set in a request/response message. if (storeValue == null) { parsedValue = result; } // If we get here we successfully parsed the whole string. return input.Length - startIndex; } private static bool TrySetCacheControlValues(CacheControlHeaderValue cc, List<NameValueHeaderValue> nameValueList) { foreach (NameValueHeaderValue nameValue in nameValueList) { bool success = true; string name = nameValue.Name.ToLowerInvariant(); switch (name) { case noCacheString: success = TrySetOptionalTokenList(nameValue, ref cc._noCache, ref cc._noCacheHeaders); break; case noStoreString: success = TrySetTokenOnlyValue(nameValue, ref cc._noStore); break; case maxAgeString: success = TrySetTimeSpan(nameValue, ref cc._maxAge); break; case maxStaleString: success = ((nameValue.Value == null) || TrySetTimeSpan(nameValue, ref cc._maxStaleLimit)); if (success) { cc._maxStale = true; } break; case minFreshString: success = TrySetTimeSpan(nameValue, ref cc._minFresh); break; case noTransformString: success = TrySetTokenOnlyValue(nameValue, ref cc._noTransform); break; case onlyIfCachedString: success = TrySetTokenOnlyValue(nameValue, ref cc._onlyIfCached); break; case publicString: success = TrySetTokenOnlyValue(nameValue, ref cc._publicField); break; case privateString: success = TrySetOptionalTokenList(nameValue, ref cc._privateField, ref cc._privateHeaders); break; case mustRevalidateString: success = TrySetTokenOnlyValue(nameValue, ref cc._mustRevalidate); break; case proxyRevalidateString: success = TrySetTokenOnlyValue(nameValue, ref cc._proxyRevalidate); break; case sharedMaxAgeString: success = TrySetTimeSpan(nameValue, ref cc._sharedMaxAge); break; default: cc.Extensions.Add(nameValue); // success is always true break; } if (!success) { return false; } } return true; } private static bool TrySetTokenOnlyValue(NameValueHeaderValue nameValue, ref bool boolField) { if (nameValue.Value != null) { return false; } boolField = true; return true; } private static bool TrySetOptionalTokenList(NameValueHeaderValue nameValue, ref bool boolField, ref ObjectCollection<string> destination) { Debug.Assert(nameValue != null); if (nameValue.Value == null) { boolField = true; return true; } // We need the string to be at least 3 chars long: 2x quotes and at least 1 character. Also make sure we // have a quoted string. Note that NameValueHeaderValue will never have leading/trailing whitespace. string valueString = nameValue.Value; if ((valueString.Length < 3) || (valueString[0] != '\"') || (valueString[valueString.Length - 1] != '\"')) { return false; } // We have a quoted string. Now verify that the string contains a list of valid tokens separated by ','. int current = 1; // skip the initial '"' character. int maxLength = valueString.Length - 1; // -1 because we don't want to parse the final '"'. bool separatorFound = false; int originalValueCount = destination == null ? 0 : destination.Count; while (current < maxLength) { current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(valueString, current, true, out separatorFound); if (current == maxLength) { break; } int tokenLength = HttpRuleParser.GetTokenLength(valueString, current); if (tokenLength == 0) { // We already skipped whitespace and separators. If we don't have a token it must be an invalid // character. return false; } if (destination == null) { destination = new ObjectCollection<string>(s_checkIsValidToken); } destination.Add(valueString.Substring(current, tokenLength)); current = current + tokenLength; } // After parsing a valid token list, we expect to have at least one value if ((destination != null) && (destination.Count > originalValueCount)) { boolField = true; return true; } return false; } private static bool TrySetTimeSpan(NameValueHeaderValue nameValue, ref TimeSpan? timeSpan) { Debug.Assert(nameValue != null); if (nameValue.Value == null) { return false; } int seconds; if (!HeaderUtilities.TryParseInt32(nameValue.Value, out seconds)) { return false; } timeSpan = new TimeSpan(0, 0, seconds); return true; } private static void AppendValueIfRequired(StringBuilder sb, bool appendValue, string value) { if (appendValue) { AppendValueWithSeparatorIfRequired(sb, value); } } private static void AppendValueWithSeparatorIfRequired(StringBuilder sb, string value) { if (sb.Length > 0) { sb.Append(", "); } sb.Append(value); } private static void AppendValues(StringBuilder sb, ObjectCollection<string> values) { bool first = true; foreach (string value in values) { if (first) { first = false; } else { sb.Append(", "); } sb.Append(value); } } private static void CheckIsValidToken(string item) { HeaderUtilities.CheckValidToken(item, "item"); } object ICloneable.Clone() { return new CacheControlHeaderValue(this); } } }
namespace Gu.Wpf.UiAutomation { using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.InteropServices; using System.Windows.Automation; using Gu.Wpf.UiAutomation.WindowsAPI; public class Window : UiElement { public Window(AutomationElement automationElement) : this(automationElement, Equals(automationElement.Parent(), Desktop.AutomationElement)) { } public Window(AutomationElement automationElement, bool isMainWindow) : base(automationElement) { this.IsMainWindow = isMainWindow; } /// <summary> /// Flag to indicate, if the window is the application's main window. /// Is used so that it does not need to be looked up again in some cases (e.g. Context Menu). /// </summary> public bool IsMainWindow { get; } public string Title => this.Name; /// <summary> /// Get TransformPattern.CanResize. /// </summary> public bool CanResize => this.AutomationElement.TryGetTransformPattern(out var valuePattern) && valuePattern.Current.CanResize; /// <summary> /// Get TransformPattern.CanMove. /// </summary> public bool CanMove => this.AutomationElement.TryGetTransformPattern(out var valuePattern) && valuePattern.Current.CanMove; public bool IsModal => this.AutomationElement.WindowPattern().Current.IsModal; public TitleBar TitleBar => new TitleBar(this.AutomationElement.FindFirstChild(Conditions.TitleBar)); public IReadOnlyList<Window> ModalWindows => this.FindAllChildren(Conditions.ModalWindow) .Select(e => new Window(e.AutomationElement, isMainWindow: false)) .ToArray(); /// <summary> /// Gets the current WPF popup window. /// </summary> [Obsolete("Changed to method FindPopup()")] public Popup Popup { get { var mainWindow = this.GetMainWindow(); var popup = mainWindow.FindFirstChild( new AndCondition( Conditions.Window, Conditions.ByName(string.Empty), Conditions.ByClassName("Popup"))); if (popup is null) { throw new InvalidOperationException("Did not find a popup"); } return new Popup(popup.AutomationElement); } } /// <summary> /// Gets the contest menu for the window. /// Note: It uses the FrameworkType of the window as lookup logic. Use <see cref="GetContextMenuByFrameworkType" /> if you want to control this. /// </summary> public ContextMenu? ContextMenu => this.GetContextMenuByFrameworkType(this.FrameworkType); public IntPtr NativeWindowHandle => new IntPtr(this.AutomationElement.NativeWindowHandle()); public WindowPattern WindowPattern => this.AutomationElement.WindowPattern(); public MessageBox FindMessageBox() => new MessageBox(this.AutomationElement.FindFirstChild(Conditions.MessageBox)); /// <summary> /// Find the first <see cref="Popup"/>. /// </summary> public Popup FindPopup() => this.TryFindFirst(TreeScope.Children, Conditions.Popup, x => new Popup(x), Retry.Time, out var result) || Desktop.Instance.TryFindFirst(TreeScope.Children, Conditions.Popup, x => new Popup(x), Retry.Time, out result) ? result : throw new InvalidOperationException($"Did not find a {typeof(Popup).Name} matching {Conditions.Popup.Description()}."); public Window FindDialog() => this.FindFirstChild(Conditions.ModalWindow, e => new Window(e, isMainWindow: false)); public ContextMenu? GetContextMenuByFrameworkType(FrameworkType frameworkType) { if (frameworkType == FrameworkType.Win32) { this.WaitUntilResponsive(); // The main menu is directly under the desktop with the name "Context" or in a few cases "System" if (Desktop.AutomationElement.TryFindFirst( TreeScope.Children, new AndCondition( Conditions.Menu, new OrCondition( Conditions.ByName("Context"), Conditions.ByName("System"))), out var element)) { return new ContextMenu(element, isWin32Menu: true); } } var mainWindow = this.GetMainWindow(); if (mainWindow is null) { throw new InvalidOperationException("Could not find MainWindow"); } if (frameworkType == FrameworkType.WinForms) { var ctxMenu = mainWindow.AutomationElement.FindFirstChild( new AndCondition( Conditions.Menu, Conditions.ByName("DropDown"))); return new ContextMenu(ctxMenu); } if (frameworkType == FrameworkType.Wpf) { // In WPF, there is a window (Popup) where the menu is inside var popup = this.FindPopup(); var ctxMenu = popup.AutomationElement.FindFirstChild(Conditions.Menu); return new ContextMenu(ctxMenu); } // No menu found return null; } public void WaitUntilResponsive() => Wait.UntilResponsive(this); public void Close() { this.WaitUntilResponsive(); if (!WindowsVersion.IsWindows7()) { var closeButton = this.TitleBar?.CloseButton; if (closeButton is { }) { closeButton.Invoke(); return; } } this.AutomationElement.WindowPattern().Close(); } /// <summary>Moves the control.</summary> /// <param name="x">Absolute screen coordinates of the left side of the control.</param> /// <param name="y">Absolute screen coordinates of the top of the control.</param> /// <exception cref="System.InvalidOperationException">The <see cref="System.Windows.Automation.TransformPattern.TransformPatternInformation.CanMove" /> property is false.</exception> public void MoveTo(int x, int y) { this.AutomationElement.TransformPattern().Move(x, y); } /// <summary>Resizes the control.</summary> /// <param name="width">The new width of the window, in pixels.</param> /// <param name="height">The new height of the window, in pixels.</param> /// <exception cref="System.InvalidOperationException">The <see cref="System.Windows.Automation.TransformPattern.TransformPatternInformation.CanResize" /> property is false.</exception> public void Resize(int width, int height) { this.AutomationElement.TransformPattern().Resize(width, height); } /// <summary> /// Brings the element to the foreground. /// </summary> public void SetTransparency(byte alpha) { if (User32.SetWindowLong(this.NativeWindowHandle, WindowLongParam.GWL_EXSTYLE, WindowStyles.WS_EX_LAYERED) == 0) { throw new Win32Exception(Marshal.GetLastWin32Error()); } if (!User32.SetLayeredWindowAttributes(this.NativeWindowHandle, 0, alpha, LayeredWindowAttributes.LWA_ALPHA)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } #pragma warning disable CA1822 public UiElement FocusedElement() => FromAutomationElement(AutomationElement.FocusedElement); #pragma warning restore CA1822 /// <summary> /// Gets the main window (first window on desktop with the same process as this window). /// </summary> private Window GetMainWindow() { if (this.IsMainWindow) { return this; } var element = AutomationElement.RootElement .FindFirst( TreeScope.Children, Conditions.ByProcessId(this.ProcessId)); var mainWindow = new Window(element, isMainWindow: true); return mainWindow; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V8.Resources { /// <summary>Resource name for the <c>Customer</c> resource.</summary> public sealed partial class CustomerName : gax::IResourceName, sys::IEquatable<CustomerName> { /// <summary>The possible contents of <see cref="CustomerName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>customers/{customer_id}</c>.</summary> Customer = 1, } private static gax::PathTemplate s_customer = new gax::PathTemplate("customers/{customer_id}"); /// <summary>Creates a <see cref="CustomerName"/> 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="CustomerName"/> containing the provided <paramref name="unparsedResourceName"/> /// . /// </returns> public static CustomerName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new CustomerName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary>Creates a <see cref="CustomerName"/> with the pattern <c>customers/{customer_id}</c>.</summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="CustomerName"/> constructed from the provided ids.</returns> public static CustomerName FromCustomer(string customerId) => new CustomerName(ResourceNameType.Customer, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="CustomerName"/> with pattern /// <c>customers/{customer_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CustomerName"/> with pattern <c>customers/{customer_id}</c>. /// </returns> public static string Format(string customerId) => FormatCustomer(customerId); /// <summary> /// Formats the IDs into the string representation of this <see cref="CustomerName"/> with pattern /// <c>customers/{customer_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CustomerName"/> with pattern <c>customers/{customer_id}</c>. /// </returns> public static string FormatCustomer(string customerId) => s_customer.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId))); /// <summary>Parses the given resource name string into a new <see cref="CustomerName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"><item><description><c>customers/{customer_id}</c></description></item></list> /// </remarks> /// <param name="customerName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="CustomerName"/> if successful.</returns> public static CustomerName Parse(string customerName) => Parse(customerName, false); /// <summary> /// Parses the given resource name string into a new <see cref="CustomerName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"><item><description><c>customers/{customer_id}</c></description></item></list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="customerName">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="CustomerName"/> if successful.</returns> public static CustomerName Parse(string customerName, bool allowUnparsed) => TryParse(customerName, allowUnparsed, out CustomerName 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="CustomerName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"><item><description><c>customers/{customer_id}</c></description></item></list> /// </remarks> /// <param name="customerName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="CustomerName"/>, 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 customerName, out CustomerName result) => TryParse(customerName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CustomerName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"><item><description><c>customers/{customer_id}</c></description></item></list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="customerName">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="CustomerName"/>, 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 customerName, bool allowUnparsed, out CustomerName result) { gax::GaxPreconditions.CheckNotNull(customerName, nameof(customerName)); gax::TemplatedResourceName resourceName; if (s_customer.TryParseName(customerName, out resourceName)) { result = FromCustomer(resourceName[0]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(customerName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private CustomerName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null) { Type = type; UnparsedResource = unparsedResourceName; CustomerId = customerId; } /// <summary> /// Constructs a new instance of a <see cref="CustomerName"/> class from the component parts of pattern /// <c>customers/{customer_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> public CustomerName(string customerId) : this(ResourceNameType.Customer, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary>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.Customer: return s_customer.Expand(CustomerId); 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 CustomerName); /// <inheritdoc/> public bool Equals(CustomerName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(CustomerName a, CustomerName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(CustomerName a, CustomerName b) => !(a == b); } public partial class Customer { /// <summary> /// <see cref="CustomerName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal CustomerName ResourceNameAsCustomerName { get => string.IsNullOrEmpty(ResourceName) ? null : CustomerName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } } public partial class CallReportingSetting { /// <summary> /// <see cref="ConversionActionName"/>-typed view over the <see cref="CallConversionAction"/> resource name /// property. /// </summary> internal ConversionActionName CallConversionActionAsConversionActionName { get => string.IsNullOrEmpty(CallConversionAction) ? null : ConversionActionName.Parse(CallConversionAction, allowUnparsed: true); set => CallConversionAction = value?.ToString() ?? ""; } } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010-2015 FUJIWARA, Yusuke // // 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 -- License Terms -- #if UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT #define UNITY #endif using System; using System.Linq; using System.Reflection; #if !SILVERLIGHT && !NETFX_35 && !UNITY using System.Collections.Concurrent; #else // !SILVERLIGHT && !NETFX_35 && !UNITY using System.Collections.Generic; #endif // !SILVERLIGHT && !NETFX_35 && !UNITY #if !UNITY #if XAMIOS || XAMDROID using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; #endif // XAMIOS || XAMDROID #endif // !UNITY #if NETFX_CORE using System.Linq.Expressions; #endif // NETFX_CORE using System.Threading; using MsgPack.Serialization.DefaultSerializers; using MsgPack.Serialization.Polymorphic; namespace MsgPack.Serialization { /// <summary> /// <strong>This is intened to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Represents serialization context information for internal serialization logic. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "Rerely instanticated and backward compatibility" )] public sealed partial class SerializationContext { #if UNITY private static readonly object DefaultContextSyncRoot = new object(); #endif // UNITY #if UNITY || XAMIOS || XAMDROID private static readonly MethodInfo GetSerializer1Method = typeof( SerializationContext ).GetMethod( "GetSerializer", new[] { typeof( object ) } ); #endif // UNITY || XAMIOS || XAMDROID // Set SerializerRepository null because it requires SerializationContext, so re-init in constructor. private static SerializationContext _default = new SerializationContext( PackerCompatibilityOptions.None ); /// <summary> /// Gets or sets the default instance. /// </summary> /// <value> /// The default <see cref="SerializationContext"/> instance. /// </value> /// <exception cref="ArgumentNullException">The setting value is <c>null</c>.</exception> public static SerializationContext Default { get { #if !UNITY return Interlocked.CompareExchange( ref _default, null, null ); #else lock( DefaultContextSyncRoot ) { return _default; } #endif // !UNITY } set { if ( value == null ) { throw new ArgumentNullException( "value" ); } #if !UNITY Interlocked.Exchange( ref _default, value ); #else lock( DefaultContextSyncRoot ) { _default = value; } #endif // !UNITY } } private readonly SerializerRepository _serializers; #if SILVERLIGHT || NETFX_35 || UNITY private readonly Dictionary<Type, object> _typeLock; #else private readonly ConcurrentDictionary<Type, object> _typeLock; #endif // SILVERLIGHT || NETFX_35 || UNITY /// <summary> /// Gets the current <see cref="SerializerRepository"/>. /// </summary> /// <value> /// The current <see cref="SerializerRepository"/>. /// </value> public SerializerRepository Serializers { get { #if !UNITY Contract.Ensures( Contract.Result<SerializerRepository>() != null ); #endif // !UNITY return this._serializers; } } #if XAMIOS || XAMDROID || UNITY_IPHONE || UNITY_ANDROID private EmitterFlavor _emitterFlavor = EmitterFlavor.ReflectionBased; #elif !NETFX_CORE private EmitterFlavor _emitterFlavor = EmitterFlavor.FieldBased; #else private EmitterFlavor _emitterFlavor = EmitterFlavor.ExpressionBased; #endif /// <summary> /// Gets or sets the <see cref="EmitterFlavor"/>. /// </summary> /// <value> /// The <see cref="EmitterFlavor"/> /// </value> /// <remarks> /// For testing purposes. /// </remarks> internal EmitterFlavor EmitterFlavor { get { return this._emitterFlavor; } set { this._emitterFlavor = value; } } private readonly SerializationCompatibilityOptions _compatibilityOptions; /// <summary> /// Gets the compatibility options. /// </summary> /// <value> /// The <see cref="SerializationCompatibilityOptions"/> which stores compatibility options. This value will not be <c>null</c>. /// </value> public SerializationCompatibilityOptions CompatibilityOptions { get { #if !UNITY Contract.Ensures( Contract.Result<SerializationCompatibilityOptions>() != null ); #endif // !UNITY return this._compatibilityOptions; } } private SerializationMethod _serializationMethod; /// <summary> /// Gets or sets the <see cref="SerializationMethod"/> to determine serialization strategy. /// </summary> /// <value> /// The <see cref="SerializationMethod"/> to determine serialization strategy. /// </value> public SerializationMethod SerializationMethod { get { #if !UNITY Contract.Ensures( Enum.IsDefined( typeof( SerializationMethod ), Contract.Result<SerializationMethod>() ) ); #endif // !UNITY return this._serializationMethod; } set { switch ( value ) { case SerializationMethod.Array: case SerializationMethod.Map: { break; } default: { throw new ArgumentOutOfRangeException( "value" ); } } #if !UNITY Contract.EndContractBlock(); #endif // !UNITY this._serializationMethod = value; } } private EnumSerializationMethod _enumSerializationMethod; /// <summary> /// Gets or sets the <see cref="EnumSerializationMethod"/> to determine default serialization strategy of enum types. /// </summary> /// <value> /// The <see cref="EnumSerializationMethod"/> to determine default serialization strategy of enum types. /// </value> /// <remarks> /// A serialization strategy for specific <strong>member</strong> is determined as following: /// <list type="numeric"> /// <item>If the member is marked with <see cref="MessagePackEnumMemberAttribute"/> and its value is not <see cref="EnumMemberSerializationMethod.Default"/>, then it will be used.</item> /// <item>Otherwise, if the enum type itself is marked with <see cref="MessagePackEnumAttribute"/>, then it will be used.</item> /// <item>Otherwise, the value of this property will be used.</item> /// </list> /// Note that the default value of this property is <see cref="T:EnumSerializationMethod.ByName"/>, it is not size efficient but tolerant to unexpected enum definition change. /// </remarks> public EnumSerializationMethod EnumSerializationMethod { get { #if !UNITY Contract.Ensures( Enum.IsDefined( typeof( EnumSerializationMethod ), Contract.Result<EnumSerializationMethod>() ) ); #endif // !UNITY return this._enumSerializationMethod; } set { switch ( value ) { case EnumSerializationMethod.ByName: case EnumSerializationMethod.ByUnderlyingValue: { break; } default: { throw new ArgumentOutOfRangeException( "value" ); } } #if !UNITY Contract.EndContractBlock(); #endif // !UNITY this._enumSerializationMethod = value; } } #if !XAMIOS && !UNITY_IPHONE private SerializationMethodGeneratorOption _generatorOption; /// <summary> /// Gets or sets the <see cref="SerializationMethodGeneratorOption"/> to control code generation. /// </summary> /// <value> /// The <see cref="SerializationMethodGeneratorOption"/>. /// </value> public SerializationMethodGeneratorOption GeneratorOption { get { #if !UNITY Contract.Ensures( Enum.IsDefined( typeof( SerializationMethod ), Contract.Result<SerializationMethodGeneratorOption>() ) ); #endif // !UNITY return this._generatorOption; } set { switch ( value ) { case SerializationMethodGeneratorOption.Fast: #if !SILVERLIGHT case SerializationMethodGeneratorOption.CanCollect: case SerializationMethodGeneratorOption.CanDump: #endif { break; } default: { throw new ArgumentOutOfRangeException( "value" ); } } #if !UNITY Contract.EndContractBlock(); #endif // !UNITY this._generatorOption = value; } } #endif // !XAMIOS && !UNITY_IPHONE private readonly DefaultConcreteTypeRepository _defaultCollectionTypes; /// <summary> /// Gets the default collection types. /// </summary> /// <value> /// The default collection types. This value will not be <c>null</c>. /// </value> public DefaultConcreteTypeRepository DefaultCollectionTypes { get { return this._defaultCollectionTypes; } } #if !XAMIOS && !UNITY_IPHONE /// <summary> /// Gets or sets a value indicating whether runtime generation is disabled or not. /// </summary> /// <value> /// <c>true</c> if runtime generation is disabled; otherwise, <c>false</c>. /// </value> internal bool IsRuntimeGenerationDisabled { get; set; } #endif // !XAMIOS && !UNITY_IPHONE /// <summary> /// Gets or sets the default <see cref="DateTime"/> conversion methods of built-in serializers. /// </summary> /// <value> /// The default <see cref="DateTime"/> conversion methods of built-in serializers. The default is <see cref="F:DateTimeConversionMethod.Native"/>. /// </value> /// <remarks> /// As of 0.6, <see cref="DateTime"/> value is serialized as its native representation instead of interoperable UTC milliseconds Unix epoc. /// This behavior solves some debugging problem and interop issues, but breaks compability. /// If you want to change this behavior, set this value to <see cref="F:DateTimeConversionMethod.UnixEpoc"/>. /// </remarks> public DateTimeConversionMethod DefaultDateTimeConversionMethod { get; set; } /// <summary> /// Configures <see cref="Default"/> as new classic <see cref="SerializationContext"/> instance. /// </summary> /// <returns>The previously set context as <see cref="Default"/>.</returns> /// <seealso cref="CreateClassicContext()"/> public static SerializationContext ConfigureClassic() { #if !UNITY return Interlocked.Exchange( ref _default, CreateClassicContext() ); #else lock ( DefaultContextSyncRoot ) { var old = _default; _default = CreateClassicContext(); return old; } #endif // !UNITY } /// <summary> /// Creates a new <see cref="SerializationContext"/> which is configured as same as 0.5. /// </summary> /// <returns> /// A new <see cref="SerializationContext"/> which is configured as same as 0.5. /// </returns> /// <remarks> /// There are breaking changes of <see cref="SerializationContext"/> properties to improve API usability and to prevent accidental failure. /// This method returns a <see cref="SerializationContext"/> which configured as classic style settings as follows: /// <list type="table"> /// <listheader> /// <term></term> /// <description>Default (as of 0.6)</description> /// <description>Classic (before 0.6)</description> /// </listheader> /// <item> /// <term>Packed object members order (if members are not marked with <see cref="MessagePackMemberAttribute"/> nor <c>System.Runtime.Serialization.DataMemberAttribute</c> and serializer uses <see cref="F:SerializationMethod.Array"/>)</term> /// <description>As declared (metadata table order)</description> /// <description>As lexicographical</description> /// </item> /// <item> /// <term><see cref="DateTime"/> value</term> /// <description>Native representation (100-nano ticks, preserving <see cref="DateTimeKind"/>.)</description> /// <description>UTC, milliseconds Unix epoc.</description> /// </item> /// </list> /// </remarks> public static SerializationContext CreateClassicContext() { return new SerializationContext( PackerCompatibilityOptions.Classic ) { DefaultDateTimeConversionMethod = DateTimeConversionMethod.UnixEpoc }; } /// <summary> /// Initializes a new instance of the <see cref="SerializationContext"/> class with copy of <see cref="SerializerRepository.GetDefault()"/>. /// </summary> public SerializationContext() : this( PackerCompatibilityOptions.None ) { } /// <summary> /// Initializes a new instance of the <see cref="SerializationContext"/> class with copy of <see cref="SerializerRepository.GetDefault(PackerCompatibilityOptions)"/> for specified <see cref="PackerCompatibilityOptions"/>. /// </summary> /// <param name="packerCompatibilityOptions"><see cref="PackerCompatibilityOptions"/> which will be used on built-in serializers.</param> public SerializationContext( PackerCompatibilityOptions packerCompatibilityOptions ) { this._compatibilityOptions = new SerializationCompatibilityOptions { PackerCompatibilityOptions = packerCompatibilityOptions }; this._serializers = new SerializerRepository( SerializerRepository.GetDefault( this ) ); #if SILVERLIGHT || NETFX_35 || UNITY this._typeLock = new Dictionary<Type, object>(); #else this._typeLock = new ConcurrentDictionary<Type, object>(); #endif // SILVERLIGHT || NETFX_35 || UNITY this._defaultCollectionTypes = new DefaultConcreteTypeRepository(); #if !XAMIOS &&!UNITY this._generatorOption = SerializationMethodGeneratorOption.Fast; #endif // !XAMIOS && !UNITY } internal bool ContainsSerializer( Type rootType ) { return this._serializers.Contains( rootType ); } /// <summary> /// Gets the <see cref="MessagePackSerializer{T}"/> with this instance without provider parameter. /// </summary> /// <typeparam name="T">Type of serialization/deserialization target.</typeparam> /// <returns> /// <see cref="MessagePackSerializer{T}"/>. /// If there is exiting one, returns it. /// Else the new instance will be created. /// </returns> /// <remarks> /// This method automatically register new instance via <see cref="SerializerRepository.Register{T}(MessagePackSerializer{T})"/>. /// </remarks> public MessagePackSerializer<T> GetSerializer<T>() { return this.GetSerializer<T>( null ); } /// <summary> /// Gets the <see cref="MessagePackSerializer{T}"/> with this instance. /// </summary> /// <typeparam name="T">Type of serialization/deserialization target.</typeparam> /// <param name="providerParameter">A provider specific parameter. See remarks section for details.</param> /// <returns> /// <see cref="MessagePackSerializer{T}"/>. /// If there is exiting one, returns it. /// Else the new instance will be created. /// </returns> /// <remarks> /// <para> /// This method automatically register new instance via <see cref="SerializerRepository.Register{T}(MessagePackSerializer{T})"/>. /// </para> /// <para> /// Currently, only following provider parameters are supported. /// <list type="table"> /// <listheader> /// <term>Target type</term> /// <description>Provider parameter</description> /// </listheader> /// <item> /// <term><see cref="EnumMessagePackSerializer{TEnum}"/> or its descendants.</term> /// <description><see cref="EnumSerializationMethod"/>. The returning instance corresponds to this value for serialization.</description> /// </item> /// </list> /// <note><c>null</c> is valid value for <paramref name="providerParameter"/> and it indeicates default behavior of parameter.</note> /// </para> /// </remarks> public MessagePackSerializer<T> GetSerializer<T>( object providerParameter ) { #if !UNITY Contract.Ensures( Contract.Result<MessagePackSerializer<T>>() != null ); #endif // !UNITY var schema = providerParameter as PolymorphismSchema; // Explicitly generated serializer should always used, so get it first. MessagePackSerializer<T> serializer = this._serializers.Get<T>( this, providerParameter ); if ( serializer != null ) { return serializer; } object aquiredLock = null; bool lockTaken = false; try { try { } finally { var newLock = new object(); #if SILVERLIGHT || NETFX_35 || UNITY Monitor.Enter( newLock ); try { lock ( this._typeLock ) { lockTaken = !this._typeLock.TryGetValue( typeof( T ), out aquiredLock ); if ( lockTaken ) { aquiredLock = newLock; this._typeLock.Add( typeof( T ), newLock ); } } #else bool newLockTaken = false; try { Monitor.Enter( newLock, ref newLockTaken ); aquiredLock = this._typeLock.GetOrAdd( typeof( T ), _ => newLock ); lockTaken = newLock == aquiredLock; #endif // if SILVERLIGHT || NETFX_35 || UNITY } finally { #if SILVERLIGHT || NETFX_35 || UNITY if ( !lockTaken ) #else if ( !lockTaken && newLockTaken ) #endif // if SILVERLIGHT || NETFX_35 || UNITY { // Release the lock which failed to become 'primary' lock. Monitor.Exit( newLock ); } } } if ( Monitor.TryEnter( aquiredLock ) ) { // Decrement monitor counter. Monitor.Exit( aquiredLock ); if ( lockTaken ) { // First try to create generic serializer w/o code generation. serializer = GenericSerializer.Create<T>( this, schema ); if ( serializer == null ) { #if !XAMIOS && !XAMDROID && !UNITY if ( this.IsRuntimeGenerationDisabled ) { #endif // !XAMIOS && !XAMDROID && !UNITY // On debugging, or AOT only envs, use reflection based aproach. serializer = this.GetSerializerWithoutGeneration<T>( schema ) ?? MessagePackSerializer.CreateReflectionInternal<T>( this, this.EnsureConcreteTypeRegistered( typeof( T ) ), schema ); #if !XAMIOS && !XAMDROID && !UNITY } else { // This thread creating new type serializer. serializer = MessagePackSerializer.CreateInternal<T>( this, schema ); } #endif // !XAMIOS && !XAMDROID && !UNITY } } else { // This thread owns existing lock -- thus, constructing self-composite type. // Prevent release owned lock. aquiredLock = null; return new LazyDelegatingMessagePackSerializer<T>( this, providerParameter ); } // Some types always have to use provider. MessagePackSerializerProvider provider; var asEnumSerializer = serializer as ICustomizableEnumSerializer; if ( asEnumSerializer != null ) { #if DEBUG && !UNITY Contract.Assert( typeof( T ).GetIsEnum(), typeof( T ) + " is not enum but generated serializer is ICustomizableEnumSerializer" ); #endif // DEBUG && !UNITY provider = new EnumMessagePackSerializerProvider( typeof( T ), asEnumSerializer ); } else { #if DEBUG && !UNITY Contract.Assert( !typeof( T ).GetIsEnum(), typeof( T ) + " is enum but generated serializer is not ICustomizableEnumSerializer : " + ( serializer == null ? "null" : serializer.GetType().FullName ) ); #endif // DEBUG && !UNITY // Creates provider even if no schema -- the schema might be specified future for the type. // It is OK to use polymorphic provider for value type. #if !UNITY provider = new PolymorphicSerializerProvider<T>( serializer ); #else provider = new PolymorphicSerializerProvider<T>( this, serializer ); #endif // !UNITY } this._serializers.Register( typeof( T ), provider ); } else { // Wait creation by other thread. // Acquire as 'waiting' lock. Monitor.Enter( aquiredLock ); } // Re-get to avoid duplicated registration and handle provider parameter or get the one created by prececing thread. // If T is null and schema is not provided or default schema is provided, then exception will be thrown here from the new provider. return this._serializers.Get<T>( this, providerParameter ); } finally { if ( lockTaken ) { #if SILVERLIGHT || NETFX_35 || UNITY lock ( this._typeLock ) { this._typeLock.Remove( typeof( T ) ); } #else object dummy; this._typeLock.TryRemove( typeof( T ), out dummy ); #endif // if SILVERLIGHT || NETFX_35 || UNITY } if ( aquiredLock != null ) { // Release primary lock or waiting lock. Monitor.Exit( aquiredLock ); } } } private Type EnsureConcreteTypeRegistered( Type mayBeAbstractType ) { if ( !mayBeAbstractType.GetIsAbstract() && !mayBeAbstractType.GetIsInterface() ) { return mayBeAbstractType; } var concreteType = this.DefaultCollectionTypes.GetConcreteType( mayBeAbstractType ); if ( concreteType == null ) { throw SerializationExceptions.NewNotSupportedBecauseCannotInstanciateAbstractType( mayBeAbstractType ); } return concreteType; } private MessagePackSerializer<T> GetSerializerWithoutGeneration<T>( PolymorphismSchema schema ) { PolymorphicSerializerProvider<T> provider; if ( typeof( T ).GetIsInterface() || typeof( T ).GetIsAbstract() ) { var concreteCollectionType = this._defaultCollectionTypes.GetConcreteType( typeof( T ) ); if ( concreteCollectionType != null ) { var serializer = GenericSerializer.TryCreateAbstractCollectionSerializer( this, typeof( T ), concreteCollectionType, schema ); #if !UNITY if ( serializer != null ) { var typedSerializer = serializer as MessagePackSerializer<T>; #if DEBUG && !UNITY Contract.Assert( typedSerializer != null, serializer.GetType() + " : " + serializer.GetType().GetBaseType() + " is " + typeof( MessagePackSerializer<T> ) ); #endif // DEBUG && !UNITY provider = new PolymorphicSerializerProvider<T>( typedSerializer ); } else { provider = new PolymorphicSerializerProvider<T>( null ); } #else provider = new PolymorphicSerializerProvider<T>( this, serializer ); #endif } else { #if !UNITY provider = new PolymorphicSerializerProvider<T>( null ); #else provider = new PolymorphicSerializerProvider<T>( this, null ); #endif // !UNITY } } else { // Go to reflection mode. return null; } // Fail when already registered manually. this.Serializers.Register( typeof( T ), provider ); return provider.Get( this, schema ) as MessagePackSerializer<T>; } /// <summary> /// Gets the serializer for the specified <see cref="Type"/>. /// </summary> /// <param name="targetType">Type of the serialization target.</param> /// <returns> /// <see cref="IMessagePackSingleObjectSerializer"/>. /// If there is exiting one, returns it. /// Else the new instance will be created. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="targetType"/> is <c>null</c>. /// </exception> /// <remarks> /// Although <see cref="GetSerializer{T}()"/> is preferred, /// this method can be used from non-generic type or methods. /// </remarks> public IMessagePackSingleObjectSerializer GetSerializer( Type targetType ) { return this.GetSerializer( targetType, null ); } /// <summary> /// Gets the serializer for the specified <see cref="Type"/>. /// </summary> /// <param name="targetType">Type of the serialization target.</param> /// <param name="providerParameter">A provider specific parameter. See remarks section of <see cref="GetSerializer{T}(Object)"/> for details.</param> /// <returns> /// <see cref="IMessagePackSingleObjectSerializer"/>. /// If there is exiting one, returns it. /// Else the new instance will be created. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="targetType"/> is <c>null</c>. /// </exception> /// <remarks> /// Although <see cref="GetSerializer{T}(Object)"/> is preferred, /// this method can be used from non-generic type or methods. /// </remarks> public IMessagePackSingleObjectSerializer GetSerializer( Type targetType, object providerParameter ) { if ( targetType == null ) { throw new ArgumentNullException( "targetType" ); } #if !UNITY Contract.Ensures( Contract.Result<IMessagePackSerializer>() != null ); #endif // !UNITY return SerializerGetter.Instance.Get( this, targetType, providerParameter ); } private sealed class SerializerGetter { public static readonly SerializerGetter Instance = new SerializerGetter(); #if UNITY private static readonly MethodInfo GetSerializer1Method = typeof( SerializationContext ).GetMethods() .Single( m => m.IsGenericMethodDefinition && m.Name == "GetSerializer" && m.GetParameters().Length == 1 ); #endif // UNITY #if !SILVERLIGHT && !NETFX_35 && !UNITY private readonly ConcurrentDictionary<RuntimeTypeHandle, Func<SerializationContext, object, IMessagePackSingleObjectSerializer>> _cache = new ConcurrentDictionary<RuntimeTypeHandle, Func<SerializationContext, object, IMessagePackSingleObjectSerializer>>(); #elif UNITY private readonly Dictionary<RuntimeTypeHandle, MethodInfo> _cache = new Dictionary<RuntimeTypeHandle, MethodInfo>(); #else private readonly Dictionary<RuntimeTypeHandle, Func<SerializationContext, object, IMessagePackSingleObjectSerializer>> _cache = new Dictionary<RuntimeTypeHandle, Func<SerializationContext, object, IMessagePackSingleObjectSerializer>>(); #endif // !SILVERLIGHT && !NETFX_35 && !UNITY private SerializerGetter() { } public IMessagePackSingleObjectSerializer Get( SerializationContext context, Type targetType, object providerParameter ) { #if UNITY MethodInfo method; if ( !this._cache.TryGetValue( targetType.TypeHandle, out method ) || method == null ) { method = GetSerializer1Method.MakeGenericMethod( targetType ); this._cache[ targetType.TypeHandle ] = method; } return ( IMessagePackSingleObjectSerializer )method.InvokePreservingExceptionType( context, providerParameter ); #else Func<SerializationContext, object, IMessagePackSingleObjectSerializer> func; #if SILVERLIGHT || NETFX_35 || UNITY lock ( this._cache ) { #endif // SILVERLIGHT || NETFX_35 || UNITY if ( !this._cache.TryGetValue( targetType.TypeHandle, out func ) || func == null ) { #if !NETFX_CORE func = Delegate.CreateDelegate( typeof( Func<SerializationContext, object, IMessagePackSingleObjectSerializer> ), typeof( SerializerGetter<> ).MakeGenericType( targetType ).GetMethod( "Get" ) ) as Func<SerializationContext, object, IMessagePackSingleObjectSerializer>; #else var contextParameter = Expression.Parameter( typeof( SerializationContext ), "context" ); var providerParameterParameter = Expression.Parameter( typeof( Object ), "providerParameter" ); func = Expression.Lambda<Func<SerializationContext, object, IMessagePackSingleObjectSerializer>>( Expression.Call( null, typeof( SerializerGetter<> ).MakeGenericType( targetType ).GetRuntimeMethods().Single( m => m.Name == "Get" ), contextParameter, providerParameterParameter ), contextParameter, providerParameterParameter ).Compile(); #endif // !NETFX_CORE #if DEBUG && !UNITY Contract.Assert( func != null, "func != null" ); #endif // if DEBUG && !UNITY this._cache[ targetType.TypeHandle ] = func; } #if SILVERLIGHT || NETFX_35 || UNITY } #endif // SILVERLIGHT || NETFX_35 || UNITY return func( context, providerParameter ); #endif // UNITY } } #if !UNITY private static class SerializerGetter<T> { #if !NETFX_CORE private static readonly Func<SerializationContext, object, MessagePackSerializer<T>> _func = Delegate.CreateDelegate( typeof( Func<SerializationContext, object, MessagePackSerializer<T>> ), #if XAMIOS || XAMDROID GetSerializer1Method.MakeGenericMethod( typeof( T ) ) #else Metadata._SerializationContext.GetSerializer1_Parameter_Method.MakeGenericMethod( typeof( T ) ) #endif // XAMIOS || XAMDROID ) as Func<SerializationContext, object, MessagePackSerializer<T>>; #else private static readonly Func<SerializationContext, object, MessagePackSerializer<T>> _func = CreateFunc(); private static Func<SerializationContext, object, MessagePackSerializer<T>> CreateFunc() { var thisParameter = Expression.Parameter( typeof( SerializationContext ), "this" ); var providerParameterParameter = Expression.Parameter( typeof( Object ), "providerParameter" ); return Expression.Lambda<Func<SerializationContext, object, MessagePackSerializer<T>>>( Expression.Call( thisParameter, Metadata._SerializationContext.GetSerializer1_Parameter_Method.MakeGenericMethod( typeof( T ) ), providerParameterParameter ), thisParameter, providerParameterParameter ).Compile(); } #endif // if !NETFX_CORE // ReSharper disable UnusedMember.Local // This method is invoked via Reflection on SerializerGetter.Get(). public static IMessagePackSingleObjectSerializer Get( SerializationContext context, object providerParameter ) { return _func( context, providerParameter ); } // ReSharper restore UnusedMember.Local } #endif // !UNITY } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Data.SqlClient; using System.Runtime.InteropServices; namespace System.Data.SqlClient { internal static class SNINativeMethodWrapper { #if !MANAGED_SNI private const string SNI = "sni.dll"; private static int s_sniMaxComposedSpnLength = -1; [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void SqlAsyncCallbackDelegate(IntPtr m_ConsKey, IntPtr pPacket, uint dwError); internal static int SniMaxComposedSpnLength { get { if (s_sniMaxComposedSpnLength == -1) { s_sniMaxComposedSpnLength = checked((int)GetSniMaxComposedSpnLength()); } return s_sniMaxComposedSpnLength; } } #endif #region Structs\Enums #if !MANAGED_SNI [StructLayout(LayoutKind.Sequential)] internal struct ConsumerInfo { internal int defaultBufferSize; internal SqlAsyncCallbackDelegate readDelegate; internal SqlAsyncCallbackDelegate writeDelegate; internal IntPtr key; } internal enum ConsumerNumber { SNI_Consumer_SNI, SNI_Consumer_SSB, SNI_Consumer_PacketIsReleased, SNI_Consumer_Invalid, } internal enum IOType { READ, WRITE, } internal enum PrefixEnum { UNKNOWN_PREFIX, SM_PREFIX, TCP_PREFIX, NP_PREFIX, VIA_PREFIX, INVALID_PREFIX, } internal enum ProviderEnum { HTTP_PROV, NP_PROV, SESSION_PROV, SIGN_PROV, SM_PROV, SMUX_PROV, SSL_PROV, TCP_PROV, VIA_PROV, MAX_PROVS, INVALID_PROV, } internal enum QTypes { SNI_QUERY_CONN_INFO, SNI_QUERY_CONN_BUFSIZE, SNI_QUERY_CONN_KEY, SNI_QUERY_CLIENT_ENCRYPT_POSSIBLE, SNI_QUERY_SERVER_ENCRYPT_POSSIBLE, SNI_QUERY_CERTIFICATE, SNI_QUERY_LOCALDB_HMODULE, SNI_QUERY_CONN_ENCRYPT, SNI_QUERY_CONN_PROVIDERNUM, SNI_QUERY_CONN_CONNID, SNI_QUERY_CONN_PARENTCONNID, SNI_QUERY_CONN_SECPKG, SNI_QUERY_CONN_NETPACKETSIZE, SNI_QUERY_CONN_NODENUM, SNI_QUERY_CONN_PACKETSRECD, SNI_QUERY_CONN_PACKETSSENT, SNI_QUERY_CONN_PEERADDR, SNI_QUERY_CONN_PEERPORT, SNI_QUERY_CONN_LASTREADTIME, SNI_QUERY_CONN_LASTWRITETIME, SNI_QUERY_CONN_CONSUMER_ID, SNI_QUERY_CONN_CONNECTTIME, SNI_QUERY_CONN_HTTPENDPOINT, SNI_QUERY_CONN_LOCALADDR, SNI_QUERY_CONN_LOCALPORT, SNI_QUERY_CONN_SSLHANDSHAKESTATE, SNI_QUERY_CONN_SOBUFAUTOTUNING, SNI_QUERY_CONN_SECPKGNAME, SNI_QUERY_CONN_SECPKGMUTUALAUTH, SNI_QUERY_CONN_CONSUMERCONNID, SNI_QUERY_CONN_SNIUCI, SNI_QUERY_CONN_SUPPORTS_EXTENDED_PROTECTION, SNI_QUERY_CONN_CHANNEL_PROVIDES_AUTHENTICATION_CONTEXT, SNI_QUERY_CONN_PEERID, SNI_QUERY_CONN_SUPPORTS_SYNC_OVER_ASYNC, } [StructLayout(LayoutKind.Sequential)] private struct Sni_Consumer_Info { public int DefaultUserDataLength; public IntPtr ConsumerKey; public IntPtr fnReadComp; public IntPtr fnWriteComp; public IntPtr fnTrace; public IntPtr fnAcceptComp; public uint dwNumProts; public IntPtr rgListenInfo; public uint NodeAffinity; } [StructLayout(LayoutKind.Sequential)] private unsafe struct SNI_CLIENT_CONSUMER_INFO { public Sni_Consumer_Info ConsumerInfo; [MarshalAs(UnmanagedType.LPWStr)] public string wszConnectionString; public PrefixEnum networkLibrary; public byte* szSPN; public uint cchSPN; public byte* szInstanceName; public uint cchInstanceName; [MarshalAs(UnmanagedType.Bool)] public bool fOverrideLastConnectCache; [MarshalAs(UnmanagedType.Bool)] public bool fSynchronousConnection; public int timeout; [MarshalAs(UnmanagedType.Bool)] public bool fParallel; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct SNI_Error { internal ProviderEnum provider; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 261)] internal string errorMessage; internal uint nativeError; internal uint sniError; [MarshalAs(UnmanagedType.LPWStr)] internal string fileName; [MarshalAs(UnmanagedType.LPWStr)] internal string function; internal uint lineNumber; } #endif internal enum SniSpecialErrors : uint { LocalDBErrorCode = 50, // multi-subnet-failover specific error codes MultiSubnetFailoverWithMoreThan64IPs = 47, MultiSubnetFailoverWithInstanceSpecified = 48, MultiSubnetFailoverWithNonTcpProtocol = 49, // max error code value MaxErrorValue = 50157 } #endregion #region DLL Imports #if !MANAGED_SNI [DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIAddProviderWrapper")] internal static extern uint SNIAddProvider(SNIHandle pConn, ProviderEnum ProvNum, [In] ref uint pInfo); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNICheckConnectionWrapper")] internal static extern uint SNICheckConnection([In] SNIHandle pConn); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNICloseWrapper")] internal static extern uint SNIClose(IntPtr pConn); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] internal static extern void SNIGetLastError(out SNI_Error pErrorStruct); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] internal static extern void SNIPacketRelease(IntPtr pPacket); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIPacketResetWrapper")] internal static extern void SNIPacketReset([In] SNIHandle pConn, IOType IOType, SNIPacket pPacket, ConsumerNumber ConsNum); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] internal static extern uint SNIQueryInfo(QTypes QType, ref uint pbQInfo); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] internal static extern uint SNIQueryInfo(QTypes QType, ref IntPtr pbQInfo); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIReadAsyncWrapper")] internal static extern uint SNIReadAsync(SNIHandle pConn, ref IntPtr ppNewPacket); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] internal static extern uint SNIReadSyncOverAsync(SNIHandle pConn, ref IntPtr ppNewPacket, int timeout); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIRemoveProviderWrapper")] internal static extern uint SNIRemoveProvider(SNIHandle pConn, ProviderEnum ProvNum); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] internal static extern uint SNISecInitPackage(ref uint pcbMaxToken); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNISetInfoWrapper")] internal static extern uint SNISetInfo(SNIHandle pConn, QTypes QType, [In] ref uint pbQInfo); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] internal static extern uint SNITerminate(); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIWaitForSSLHandshakeToCompleteWrapper")] internal static extern uint SNIWaitForSSLHandshakeToComplete([In] SNIHandle pConn, int dwMilliseconds); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] internal static extern uint UnmanagedIsTokenRestricted([In] IntPtr token, [MarshalAs(UnmanagedType.Bool)] out bool isRestricted); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] private static extern uint GetSniMaxComposedSpnLength(); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] private static extern uint SNIGetInfoWrapper([In] SNIHandle pConn, SNINativeMethodWrapper.QTypes QType, out Guid pbQInfo); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] private static extern uint SNIInitialize([In] IntPtr pmo); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] private static extern uint SNIOpenSyncExWrapper(ref SNI_CLIENT_CONSUMER_INFO pClientConsumerInfo, out IntPtr ppConn); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] private static extern uint SNIOpenWrapper( [In] ref Sni_Consumer_Info pConsumerInfo, [MarshalAs(UnmanagedType.LPStr)] string szConnect, [In] SNIHandle pConn, out IntPtr ppConn, [MarshalAs(UnmanagedType.Bool)] bool fSync); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr SNIPacketAllocateWrapper([In] SafeHandle pConn, IOType IOType); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] private static extern uint SNIPacketGetDataWrapper([In] IntPtr packet, [In, Out] byte[] readBuffer, uint readBufferLength, out uint dataSize); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] private static unsafe extern void SNIPacketSetData(SNIPacket pPacket, [In] byte* pbBuf, uint cbBuf); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] private static unsafe extern uint SNISecGenClientContextWrapper( [In] SNIHandle pConn, [In, Out] byte[] pIn, uint cbIn, [In, Out] byte[] pOut, [In] ref uint pcbOut, [MarshalAsAttribute(UnmanagedType.Bool)] out bool pfDone, byte* szServerInfo, uint cbServerInfo, [MarshalAsAttribute(UnmanagedType.LPWStr)] string pwszUserName, [MarshalAsAttribute(UnmanagedType.LPWStr)] string pwszPassword); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] private static extern uint SNIWriteAsyncWrapper(SNIHandle pConn, [In] SNIPacket pPacket); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] private static extern uint SNIWriteSyncOverAsync(SNIHandle pConn, [In] SNIPacket pPacket); #endif #endregion #if !MANAGED_SNI internal static uint SniGetConnectionId(SNIHandle pConn, ref Guid connId) { return SNIGetInfoWrapper(pConn, QTypes.SNI_QUERY_CONN_CONNID, out connId); } internal static uint SNIInitialize() { return SNIInitialize(IntPtr.Zero); } internal static unsafe uint SNIOpenMarsSession(ConsumerInfo consumerInfo, SNIHandle parent, ref IntPtr pConn, bool fSync) { // initialize consumer info for MARS Sni_Consumer_Info native_consumerInfo = new Sni_Consumer_Info(); MarshalConsumerInfo(consumerInfo, ref native_consumerInfo); return SNIOpenWrapper(ref native_consumerInfo, "session:", parent, out pConn, fSync); } internal static unsafe uint SNIOpenSyncEx(ConsumerInfo consumerInfo, string constring, ref IntPtr pConn, byte[] spnBuffer, byte[] instanceName, bool fOverrideCache, bool fSync, int timeout, bool fParallel) { fixed (byte* pin_instanceName = &instanceName[0]) { SNI_CLIENT_CONSUMER_INFO clientConsumerInfo = new SNI_CLIENT_CONSUMER_INFO(); // initialize client ConsumerInfo part first MarshalConsumerInfo(consumerInfo, ref clientConsumerInfo.ConsumerInfo); clientConsumerInfo.wszConnectionString = constring; clientConsumerInfo.networkLibrary = PrefixEnum.UNKNOWN_PREFIX; clientConsumerInfo.szInstanceName = pin_instanceName; clientConsumerInfo.cchInstanceName = (uint)instanceName.Length; clientConsumerInfo.fOverrideLastConnectCache = fOverrideCache; clientConsumerInfo.fSynchronousConnection = fSync; clientConsumerInfo.timeout = timeout; clientConsumerInfo.fParallel = fParallel; if (spnBuffer != null) { fixed (byte* pin_spnBuffer = &spnBuffer[0]) { clientConsumerInfo.szSPN = pin_spnBuffer; clientConsumerInfo.cchSPN = (uint)spnBuffer.Length; return SNIOpenSyncExWrapper(ref clientConsumerInfo, out pConn); } } else { // else leave szSPN null (SQL Auth) return SNIOpenSyncExWrapper(ref clientConsumerInfo, out pConn); } } } internal static void SNIPacketAllocate(SafeHandle pConn, IOType IOType, ref IntPtr pPacket) { pPacket = SNIPacketAllocateWrapper(pConn, IOType); } internal static unsafe uint SNIPacketGetData(IntPtr packet, byte[] readBuffer, ref uint dataSize) { return SNIPacketGetDataWrapper(packet, readBuffer, (uint)readBuffer.Length, out dataSize); } internal static unsafe void SNIPacketSetData(SNIPacket packet, byte[] data, int length) { fixed (byte* pin_data = &data[0]) { SNIPacketSetData(packet, pin_data, (uint)length); } } internal static unsafe uint SNISecGenClientContext(SNIHandle pConnectionObject, byte[] inBuff, uint receivedLength, byte[] OutBuff, ref uint sendLength, byte[] serverUserName) { fixed (byte* pin_serverUserName = &serverUserName[0]) { bool local_fDone; return SNISecGenClientContextWrapper( pConnectionObject, inBuff, receivedLength, OutBuff, ref sendLength, out local_fDone, pin_serverUserName, (uint)(serverUserName == null ? 0 : serverUserName.Length), null, null); } } internal static uint SNIWritePacket(SNIHandle pConn, SNIPacket packet, bool sync) { if (sync) { return SNIWriteSyncOverAsync(pConn, packet); } else { return SNIWriteAsyncWrapper(pConn, packet); } } private static void MarshalConsumerInfo(ConsumerInfo consumerInfo, ref Sni_Consumer_Info native_consumerInfo) { native_consumerInfo.DefaultUserDataLength = consumerInfo.defaultBufferSize; native_consumerInfo.fnReadComp = null != consumerInfo.readDelegate ? Marshal.GetFunctionPointerForDelegate(consumerInfo.readDelegate) : IntPtr.Zero; native_consumerInfo.fnWriteComp = null != consumerInfo.writeDelegate ? Marshal.GetFunctionPointerForDelegate(consumerInfo.writeDelegate) : IntPtr.Zero; native_consumerInfo.ConsumerKey = consumerInfo.key; } #endif } } namespace System.Data { internal static class SafeNativeMethods { [DllImport("api-ms-win-core-libraryloader-l1-1-0.dll", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)] internal static extern IntPtr GetProcAddress(IntPtr HModule, [MarshalAs(UnmanagedType.LPStr), In] string funcName); } } namespace System.Data { internal static class Win32NativeMethods { internal static bool IsTokenRestrictedWrapper(IntPtr token) { #if MANAGED_SNI throw new PlatformNotSupportedException("The Win32NativeMethods.IsTokenRestrictedWrapper is not supported on non-Windows platform"); #else bool isRestricted; uint result = SNINativeMethodWrapper.UnmanagedIsTokenRestricted(token, out isRestricted); if (result != 0) { Marshal.ThrowExceptionForHR(unchecked((int)result)); } return isRestricted; #endif } } }
namespace Ioke.Math { using System; using System.Text; public abstract class RealNum : Complex { public override RealNum re() { return this; } public override RealNum im() { return IntNum.zero(); } public abstract bool isNegative (); /** Return 1 if >0; 0 if ==0; -1 if <0; -2 if NaN. */ public abstract int sign (); public RealNum max (RealNum x) { RealNum result = grt (x) ? this : x; return result; } public RealNum min (RealNum x) { RealNum result = grt (x) ? x : this; return result; } public static RealNum add (RealNum x, RealNum y, int k) { return (RealNum)(x.add(y, k)); } public static RealNum times(RealNum x, RealNum y) { return (RealNum)(x.mul(y)); } public static RealNum divide (RealNum x, RealNum y) { return (RealNum)(x.div(y)); } /* These are defined in Complex, but have to be overridden. */ public override abstract Numeric add (object obj, int k); public override abstract Numeric mul (object obj); public override abstract Numeric div (object obj); public override Numeric abs () { return isNegative () ? neg () : this; } public RealNum rneg() { return (RealNum) neg(); } public override bool isZero () { return sign () == 0; } /** Converts a real to an integer, according to a specified rounding mode. * Note an inexact argument gives an inexact result, following Scheme. * See also RatNum.toExactInt. */ public static double toInt (double d, int rounding_mode) { switch (rounding_mode) { case FLOOR: return Math.Floor(d); case CEILING: return Math.Ceiling(d); case TRUNCATE: return d < 0.0 ? Math.Ceiling (d) : Math.Floor (d); case ROUND: return Math.Round(d); default: // Illegal rounding_mode return d; } } /** Converts to an exact integer, with specified rounding mode. */ public virtual IntNum toExactInt (int rounding_mode) { return toExactInt(doubleValue(), rounding_mode); } public abstract RealNum toInt (int rounding_mode); /** Converts real to an exact integer, with specified rounding mode. */ public static IntNum toExactInt (double value, int rounding_mode) { return toExactInt(toInt(value, rounding_mode)); } /** Converts an integral double (such as a toInt result) to an IntNum. */ public static IntNum toExactInt (double value) { if (Double.IsInfinity (value) || Double.IsNaN (value)) throw new ArithmeticException ("cannot convert "+value+" to exact integer"); long bits = BitConverter.DoubleToInt64Bits(value); bool neg = bits < 0; int exp = (int) (bits >> 52) & 0x7FF; bits &= 0xfffffffffffffL; if (exp == 0) bits <<= 1; else bits |= 0x10000000000000L; if (exp <= 1075) { int rshift = 1075 - exp; if (rshift > 53) return IntNum.zero(); bits >>= rshift; return IntNum.make (neg ? -bits : bits); } return IntNum.shift (IntNum.make (neg ? -bits : bits), exp - 1075); } /** Convert rational to (rounded) integer, after multiplying by 10**k. */ public static IntNum toScaledInt (RatNum r, int k) { if (k != 0) { IntNum power = IntNum.power(IntNum.ten(), k < 0 ? -k : k); IntNum num = r.numerator(); IntNum den = r.denominator(); if (k >= 0) num = IntNum.times(num, power); else den = IntNum.times(den, power); r = RatNum.make(num, den); } return r.toExactInt(ROUND); } public static string toStringScientific (float d) { return toStringScientific(d.ToString()); } public static string toStringScientific (double d) { return toStringScientific(d.ToString()); } /** Convert result of Double.toString or Float.toString to * scientific notation. * Does not validate the input. */ public static string toStringScientific (string dstr) { int indexE = dstr.IndexOf('E'); if (indexE >= 0) return dstr; int len = dstr.Length; // Check for "Infinity" or "NaN". char ch = dstr[len-1]; if (ch == 'y' || ch == 'N') return dstr; StringBuilder sbuf = new StringBuilder(len+10); int exp = toStringScientific(dstr, sbuf); sbuf.Append('E'); sbuf.Append(exp); return sbuf.ToString(); } public static int toStringScientific (string dstr, StringBuilder sbuf) { bool neg = dstr[0] == '-'; if (neg) sbuf.Append('-'); int pos = neg ? 1 : 0; int exp; int len = dstr.Length; if (dstr[pos] == '0') { // Value is < 1.0. int start = pos; for (;;) { if (pos == len) { sbuf.Append("0"); exp = 0; break; } char ch = dstr[pos++]; if (ch >= '0' && ch <= '9' && (ch != '0' || pos == len)) { sbuf.Append(ch); sbuf.Append('.'); exp = ch == '0' ? 0 : start - pos + 2; if (pos == len) sbuf.Append('0'); else { while (pos < len) sbuf.Append(dstr[pos++]); } break; } } } else { // Number of significant digits in string. int ndigits = len - (neg ? 2 : 1); int dot = dstr.IndexOf('.'); // Number of fractional digits is len-dot-1. // We want ndigits-1 fractional digits. Hence we need to move the // decimal point ndigits-1-(len-dot-1) == ndigits-len+dot positions // to the left. This becomes the exponent we need. exp = ndigits - len + dot; sbuf.Append(dstr[pos++]); // Copy initial digit before point. sbuf.Append('.'); while (pos < len) { char ch = dstr[pos++]; if (ch != '.') sbuf.Append(ch); } } // Remove excess zeros. pos = sbuf.Length; int slen = -1; for (;;) { char ch = sbuf[--pos]; if (ch == '0') slen = pos; else { if (ch == '.') slen = pos + 2; break; } } if (slen >= 0) sbuf.Length = slen; return exp; } public static string toStringDecimal (string dstr) { int indexE = dstr.IndexOf('E'); if (indexE < 0) return dstr; int len = dstr.Length; // Check for "Infinity" or "NaN". char ch = dstr[len-1]; if (ch == 'y' || ch == 'N') return dstr; StringBuilder sbuf = new StringBuilder(len+10); bool neg = dstr[0] == '-'; if (dstr[indexE+1] != '-') { throw new Exception("not implemented: toStringDecimal given non-negative exponent: "+dstr); } else { int pos = indexE+2; // skip "E-". int exp = 0; while (pos < len) exp = 10 * exp + (dstr[pos++] - '0'); if (neg) sbuf.Append('-'); sbuf.Append("0."); while (--exp > 0) sbuf.Append('0'); for (pos = 0; (ch = dstr[pos++]) != 'E'; ) { if (ch != '-' & ch != '.' && (ch != '0' || pos < indexE)) sbuf.Append(ch); } return sbuf.ToString(); } } public virtual decimal AsDecimal() { return System.Convert.ToDecimal(doubleValue()); } public virtual BigDecimal AsBigDecimal() { return new BigDecimal(doubleValue().ToString()); } } }
// // File.cs: // // Author: // Brian Nickel (brian.nickel@gmail.com) // // Original Source: // oggfile.cpp from TagLib // // Copyright (C) 2005-2007 Brian Nickel // Copyright (C) 2003 Scott Wheeler (Original Implementation) // // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License version // 2.1 as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 // USA // using System.Collections.Generic; using System; namespace TagLib.Ogg { /// <summary> /// This class extends <see cref="TagLib.File" /> to provide tagging /// and properties support for Ogg files. /// </summary> [SupportedMimeType("taglib/ogg", "ogg")] [SupportedMimeType("taglib/oga", "oga")] [SupportedMimeType("taglib/ogv", "ogv")] [SupportedMimeType("application/ogg")] [SupportedMimeType("application/x-ogg")] [SupportedMimeType("audio/vorbis")] [SupportedMimeType("audio/x-vorbis")] [SupportedMimeType("audio/x-vorbis+ogg")] [SupportedMimeType("audio/ogg")] [SupportedMimeType("audio/x-ogg")] [SupportedMimeType("video/ogg")] [SupportedMimeType("video/x-ogm+ogg")] [SupportedMimeType("video/x-theora+ogg")] [SupportedMimeType("video/x-theora")] public class File : TagLib.File { #region Private Fields /// <summary> /// Contains the tags for the file. /// </summary> //private GroupedComment tag; /// <summary> /// Contains the media properties. /// </summary> private Properties properties; #endregion #region Constructors /// <summary> /// Constructs and initializes a new instance of <see /// cref="File" /> for a specified path in the local file /// system and specified read style. /// </summary> /// <param name="path"> /// A <see cref="string" /> object containing the path of the /// file to use in the new instance. /// </param> /// <param name="propertiesStyle"> /// A <see cref="ReadStyle" /> value specifying at what level /// of accuracy to read the media properties, or <see /// cref="ReadStyle.None" /> to ignore the properties. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="path" /> is <see langword="null" />. /// </exception> public File (string path, ReadStyle propertiesStyle) : this (new File.LocalFileAbstraction (path), propertiesStyle) { } /// <summary> /// Constructs and initializes a new instance of <see /// cref="File" /> for a specified path in the local file /// system with an average read style. /// </summary> /// <param name="path"> /// A <see cref="string" /> object containing the path of the /// file to use in the new instance. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="path" /> is <see langword="null" />. /// </exception> public File (string path) : this (path, ReadStyle.Average) { } /// <summary> /// Constructs and initializes a new instance of <see /// cref="File" /> for a specified file abstraction and /// specified read style. /// </summary> /// <param name="abstraction"> /// A <see cref="IFileAbstraction" /> object to use when /// reading from and writing to the file. /// </param> /// <param name="propertiesStyle"> /// A <see cref="ReadStyle" /> value specifying at what level /// of accuracy to read the media properties, or <see /// cref="ReadStyle.None" /> to ignore the properties. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="abstraction" /> is <see langword="null" /// />. /// </exception> public File (File.IFileAbstraction abstraction, ReadStyle propertiesStyle) : base (abstraction) { Mode = AccessMode.Read; try { //tag = new GroupedComment (); Read (propertiesStyle); //TagTypesOnDisk = TagTypes; } finally { Mode = AccessMode.Closed; } } /// <summary> /// Constructs and initializes a new instance of <see /// cref="File" /> for a specified file abstraction with an /// average read style. /// </summary> /// <param name="abstraction"> /// A <see cref="IFileAbstraction" /> object to use when /// reading from and writing to the file. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="abstraction" /> is <see langword="null" /// />. /// </exception> public File (File.IFileAbstraction abstraction) : this (abstraction, ReadStyle.Average) { } #endregion #region Public Methods /// <summary> /// Saves the changes made in the current instance to the /// file it represents. /// </summary> public override void Save () { Mode = AccessMode.Write; try { long end; List<Page> pages = new List<Page> (); Dictionary<uint, Bitstream> streams = ReadStreams (pages, out end); Dictionary<uint, Paginator> paginators = new Dictionary<uint, Paginator> (); List<List<Page>> new_pages = new List<List<Page>> (); Dictionary<uint, int> shifts = new Dictionary<uint, int> (); foreach (Page page in pages) { uint id = page.Header.StreamSerialNumber; if (!paginators.ContainsKey (id)) paginators.Add (id, new Paginator ( streams [id].Codec)); paginators [id].AddPage (page); } foreach (uint id in paginators.Keys) { //paginators [id].SetComment ( // tag.GetComment (id)); int shift; new_pages.Add (new List<Page> ( paginators [id] .Paginate (out shift))); shifts.Add (id, shift); } ByteVector output = new ByteVector (); bool empty; do { empty = true; foreach (List<Page> stream_pages in new_pages) { if (stream_pages.Count == 0) continue; output.Add (stream_pages [0].Render ()); stream_pages.RemoveAt (0); if (stream_pages.Count != 0) empty = false; } } while (!empty); Insert (output, 0, end); InvariantStartPosition = output.Count; InvariantEndPosition = Length; //TagTypesOnDisk = TagTypes; Page.OverwriteSequenceNumbers (this, output.Count, shifts); } finally { Mode = AccessMode.Closed; } } /// <summary> /// Removes a set of tag types from the current instance. /// </summary> /// <param name="types"> /// A bitwise combined <see cref="TagLib.TagTypes" /> value /// containing tag types to be removed from the file. /// </param> /// <remarks> /// In order to remove all tags from a file, pass <see /// cref="TagTypes.AllTags" /> as <paramref name="types" />. /// </remarks> //public override void RemoveTags (TagLib.TagTypes types) //{ // if ((types & TagLib.TagTypes.Xiph) // != TagLib.TagTypes.None) // tag.Clear (); //} /// <summary> /// Gets a tag of a specified type from the current instance, /// optionally creating a new tag if possible. /// </summary> /// <param name="type"> /// A <see cref="TagLib.TagTypes" /> value indicating the /// type of tag to read. /// </param> /// <param name="create"> /// A <see cref="bool" /> value specifying whether or not to /// try and create the tag if one is not found. /// </param> /// <returns> /// A <see cref="Tag" /> object containing the tag that was /// found in or added to the current instance. If no /// matching tag was found and none was created, <see /// langword="null" /> is returned. /// </returns> //public override TagLib.Tag GetTag (TagLib.TagTypes type, // bool create) //{ // if (type == TagLib.TagTypes.Xiph) // foreach (XiphComment comment in tag.Comments) // return comment; // return null; //} #endregion #region Public Properties /// <summary> /// Gets a abstract representation of all tags stored in the /// current instance. /// </summary> /// <value> /// A <see cref="TagLib.Tag" /> object representing all tags /// stored in the current instance. /// </value> //public override Tag Tag { // get {return tag;} //} /// <summary> /// Gets the media properties of the file represented by the /// current instance. /// </summary> /// <value> /// A <see cref="TagLib.Properties" /> object containing the /// media properties of the file represented by the current /// instance. /// </value> public override TagLib.Properties Properties { get {return properties;} } #endregion #region Private Methods /// <summary> /// Reads the file with a specified read style. /// </summary> /// <param name="propertiesStyle"> /// A <see cref="ReadStyle" /> value specifying at what level /// of accuracy to read the media properties, or <see /// cref="ReadStyle.None" /> to ignore the properties. /// </param> private void Read (ReadStyle propertiesStyle) { long end; Dictionary<uint, Bitstream> streams = ReadStreams (null, out end); List<ICodec> codecs = new List<ICodec> (); InvariantStartPosition = end; InvariantEndPosition = Length; foreach (uint id in streams.Keys) { //tag.AddComment (id, // streams [id].Codec.CommentData); codecs.Add (streams [id].Codec); } if (propertiesStyle == ReadStyle.None) return; PageHeader last_header = LastPageHeader; TimeSpan duration = streams [last_header .StreamSerialNumber].GetDuration ( last_header.AbsoluteGranularPosition); properties = new Properties (duration, codecs); } /// <summary> /// Reads the file until all streams have finished their /// property and tagging data. /// </summary> /// <param name="pages"> /// A <see cref="T:System.Collections.Generic.List`1"/> /// object to be filled with <see cref="Page" /> objects as /// they are read, or <see langword="null"/> if the pages /// are not to be stored. /// </param> /// <param name="end"> /// A <see cref="long" /> value reference to be updated to /// the postion of the first page not read by the current /// instance. /// </param> /// <returns> /// A <see cref="T:System.Collections.Generic.Dictionary`2" /// /> object containing stream serial numbers as the keys /// <see cref="Bitstream" /> objects as the values. /// </returns> private Dictionary<uint, Bitstream> ReadStreams (List<Page> pages, out long end) { Dictionary<uint, Bitstream> streams = new Dictionary<uint, Bitstream> (); List<Bitstream> active_streams = new List<Bitstream> (); long position = 0; do { Bitstream stream = null; Page page = new Page (this, position); if ((page.Header.Flags & PageFlags.FirstPageOfStream) != 0) { stream = new Bitstream (page); streams.Add (page.Header .StreamSerialNumber, stream); active_streams.Add (stream); } if (stream == null) stream = streams [ page.Header.StreamSerialNumber]; if (active_streams.Contains (stream) && stream.ReadPage (page)) active_streams.Remove (stream); if (pages != null) pages.Add (page); position += page.Size; } while (active_streams.Count > 0); end = position; return streams; } #endregion #region Private Properties /// <summary> /// Gets the last page header in the file. /// </summary> /// <value> /// A <see cref="PageHeader" /> object containing the last /// page header in the file. /// </value> /// <remarks> /// The last page header is used to determine the last /// absolute granular position of a stream so the duration /// can be calculated. /// </remarks> private PageHeader LastPageHeader { get { long last_page_header_offset = RFind ("OggS"); if (last_page_header_offset < 0) System.Console.WriteLine( "Could not find last header."); return new PageHeader (this, last_page_header_offset); } } #endregion } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ namespace MVImportTool { partial class CommandControl { /// <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.groupBox4 = new System.Windows.Forms.GroupBox(); this.ConvertCheckBox = new System.Windows.Forms.CheckBox(); this.CommandFlagTextBox = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.InstallControlsPanel = new System.Windows.Forms.Panel(); this.OverwritePolicyGroup = new System.Windows.Forms.GroupBox(); this.AskRadioButton = new System.Windows.Forms.RadioButton(); this.NeverRadioButton = new System.Windows.Forms.RadioButton(); this.AlwaysRadioButton = new System.Windows.Forms.RadioButton(); this.ConfirmInstallationCheckBox = new System.Windows.Forms.CheckBox(); this.FilterGroupBox = new System.Windows.Forms.GroupBox(); this.InstallTexturesCheckBox = new System.Windows.Forms.CheckBox(); this.InstallPhysicsCheckBox = new System.Windows.Forms.CheckBox(); this.InstallMeshCheckBox = new System.Windows.Forms.CheckBox(); this.InstallMaterialCheckBox = new System.Windows.Forms.CheckBox(); this.InstallSkeletonCheckBox = new System.Windows.Forms.CheckBox(); this.InstallCheckBox = new System.Windows.Forms.CheckBox(); this.groupBox4.SuspendLayout(); this.groupBox2.SuspendLayout(); this.InstallControlsPanel.SuspendLayout(); this.OverwritePolicyGroup.SuspendLayout(); this.FilterGroupBox.SuspendLayout(); this.SuspendLayout(); // // groupBox4 // this.groupBox4.Anchor = ((System.Windows.Forms.AnchorStyles) (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox4.Controls.Add( this.ConvertCheckBox ); this.groupBox4.Controls.Add( this.CommandFlagTextBox ); this.groupBox4.Controls.Add( this.label1 ); this.groupBox4.Location = new System.Drawing.Point( 3, 3 ); this.groupBox4.Name = "groupBox4"; this.groupBox4.Size = new System.Drawing.Size( 427, 94 ); this.groupBox4.TabIndex = 7; this.groupBox4.TabStop = false; this.groupBox4.Text = "Conversion"; // // ConvertCheckBox // this.ConvertCheckBox.AutoSize = true; this.ConvertCheckBox.Checked = true; this.ConvertCheckBox.CheckState = System.Windows.Forms.CheckState.Checked; this.ConvertCheckBox.Location = new System.Drawing.Point( 7, 19 ); this.ConvertCheckBox.Name = "ConvertCheckBox"; this.ConvertCheckBox.Size = new System.Drawing.Size( 115, 17 ); this.ConvertCheckBox.TabIndex = 2; this.ConvertCheckBox.Text = "Convert COLLADA"; this.ConvertCheckBox.UseVisualStyleBackColor = true; this.ConvertCheckBox.CheckedChanged += new System.EventHandler( this.ConvertCheckBox_CheckedChanged ); // // CommandFlagTextBox // this.CommandFlagTextBox.Anchor = ((System.Windows.Forms.AnchorStyles) (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.CommandFlagTextBox.Location = new System.Drawing.Point( 7, 55 ); this.CommandFlagTextBox.Name = "CommandFlagTextBox"; this.CommandFlagTextBox.Size = new System.Drawing.Size( 414, 20 ); this.CommandFlagTextBox.TabIndex = 0; this.CommandFlagTextBox.TextChanged += new System.EventHandler( this.CommandFlagTextBox_TextChanged ); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point( 6, 39 ); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size( 101, 13 ); this.label1.TabIndex = 1; this.label1.Text = "Command-line Flags"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // groupBox2 // this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles) (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox2.Controls.Add( this.InstallControlsPanel ); this.groupBox2.Controls.Add( this.InstallCheckBox ); this.groupBox2.Location = new System.Drawing.Point( 3, 103 ); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size( 427, 168 ); this.groupBox2.TabIndex = 6; this.groupBox2.TabStop = false; this.groupBox2.Text = "Copying"; // // InstallControlsPanel // this.InstallControlsPanel.Anchor = ((System.Windows.Forms.AnchorStyles) (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.InstallControlsPanel.Controls.Add( this.OverwritePolicyGroup ); this.InstallControlsPanel.Controls.Add( this.ConfirmInstallationCheckBox ); this.InstallControlsPanel.Controls.Add( this.FilterGroupBox ); this.InstallControlsPanel.Location = new System.Drawing.Point( 9, 42 ); this.InstallControlsPanel.Name = "InstallControlsPanel"; this.InstallControlsPanel.Size = new System.Drawing.Size( 414, 122 ); this.InstallControlsPanel.TabIndex = 4; // // OverwritePolicyGroup // this.OverwritePolicyGroup.Anchor = ((System.Windows.Forms.AnchorStyles) (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.OverwritePolicyGroup.Controls.Add( this.AskRadioButton ); this.OverwritePolicyGroup.Controls.Add( this.NeverRadioButton ); this.OverwritePolicyGroup.Controls.Add( this.AlwaysRadioButton ); this.OverwritePolicyGroup.Location = new System.Drawing.Point( 3, 71 ); this.OverwritePolicyGroup.Name = "OverwritePolicyGroup"; this.OverwritePolicyGroup.Size = new System.Drawing.Size( 408, 40 ); this.OverwritePolicyGroup.TabIndex = 5; this.OverwritePolicyGroup.TabStop = false; this.OverwritePolicyGroup.Text = "Overwrite existing files?"; // // AskRadioButton // this.AskRadioButton.AutoSize = true; this.AskRadioButton.Location = new System.Drawing.Point( 146, 17 ); this.AskRadioButton.Name = "AskRadioButton"; this.AskRadioButton.Size = new System.Drawing.Size( 43, 17 ); this.AskRadioButton.TabIndex = 2; this.AskRadioButton.Text = "Ask"; this.AskRadioButton.UseVisualStyleBackColor = true; this.AskRadioButton.CheckedChanged += new System.EventHandler( this.OverwritePolicyRadioButton_CheckedChanged ); // // NeverRadioButton // this.NeverRadioButton.AutoSize = true; this.NeverRadioButton.Location = new System.Drawing.Point( 76, 17 ); this.NeverRadioButton.Name = "NeverRadioButton"; this.NeverRadioButton.Size = new System.Drawing.Size( 54, 17 ); this.NeverRadioButton.TabIndex = 1; this.NeverRadioButton.Text = "Never"; this.NeverRadioButton.UseVisualStyleBackColor = true; this.NeverRadioButton.CheckedChanged += new System.EventHandler( this.OverwritePolicyRadioButton_CheckedChanged ); // // AlwaysRadioButton // this.AlwaysRadioButton.AutoSize = true; this.AlwaysRadioButton.Checked = true; this.AlwaysRadioButton.Location = new System.Drawing.Point( 6, 17 ); this.AlwaysRadioButton.Name = "AlwaysRadioButton"; this.AlwaysRadioButton.Size = new System.Drawing.Size( 58, 17 ); this.AlwaysRadioButton.TabIndex = 0; this.AlwaysRadioButton.TabStop = true; this.AlwaysRadioButton.Text = "Always"; this.AlwaysRadioButton.UseVisualStyleBackColor = true; this.AlwaysRadioButton.CheckedChanged += new System.EventHandler( this.OverwritePolicyRadioButton_CheckedChanged ); // // ConfirmInstallationCheckBox // this.ConfirmInstallationCheckBox.AutoSize = true; this.ConfirmInstallationCheckBox.Checked = true; this.ConfirmInstallationCheckBox.CheckState = System.Windows.Forms.CheckState.Checked; this.ConfirmInstallationCheckBox.Location = new System.Drawing.Point( 9, 3 ); this.ConfirmInstallationCheckBox.Name = "ConfirmInstallationCheckBox"; this.ConfirmInstallationCheckBox.Size = new System.Drawing.Size( 134, 17 ); this.ConfirmInstallationCheckBox.TabIndex = 4; this.ConfirmInstallationCheckBox.Text = "Confirm before copying"; this.ConfirmInstallationCheckBox.UseVisualStyleBackColor = true; this.ConfirmInstallationCheckBox.CheckedChanged += new System.EventHandler( this.ConfirmInstallationCheckBox_CheckedChanged ); // // FilterGroupBox // this.FilterGroupBox.Anchor = ((System.Windows.Forms.AnchorStyles) (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.FilterGroupBox.Controls.Add( this.InstallTexturesCheckBox ); this.FilterGroupBox.Controls.Add( this.InstallPhysicsCheckBox ); this.FilterGroupBox.Controls.Add( this.InstallMeshCheckBox ); this.FilterGroupBox.Controls.Add( this.InstallMaterialCheckBox ); this.FilterGroupBox.Controls.Add( this.InstallSkeletonCheckBox ); this.FilterGroupBox.Location = new System.Drawing.Point( 3, 26 ); this.FilterGroupBox.Name = "FilterGroupBox"; this.FilterGroupBox.Size = new System.Drawing.Size( 408, 40 ); this.FilterGroupBox.TabIndex = 3; this.FilterGroupBox.TabStop = false; this.FilterGroupBox.Text = "Check types to copy to Asset Repositories"; // // InstallTexturesCheckBox // this.InstallTexturesCheckBox.AutoSize = true; this.InstallTexturesCheckBox.Checked = true; this.InstallTexturesCheckBox.CheckState = System.Windows.Forms.CheckState.Checked; this.InstallTexturesCheckBox.Location = new System.Drawing.Point( 286, 16 ); this.InstallTexturesCheckBox.Name = "InstallTexturesCheckBox"; this.InstallTexturesCheckBox.Size = new System.Drawing.Size( 67, 17 ); this.InstallTexturesCheckBox.TabIndex = 8; this.InstallTexturesCheckBox.Text = "Textures"; this.InstallTexturesCheckBox.UseVisualStyleBackColor = true; this.InstallTexturesCheckBox.CheckedChanged += new System.EventHandler( this.InstallFilterCheckBox_CheckedChanged ); // // InstallPhysicsCheckBox // this.InstallPhysicsCheckBox.AutoSize = true; this.InstallPhysicsCheckBox.Checked = true; this.InstallPhysicsCheckBox.CheckState = System.Windows.Forms.CheckState.Checked; this.InstallPhysicsCheckBox.Location = new System.Drawing.Point( 216, 16 ); this.InstallPhysicsCheckBox.Name = "InstallPhysicsCheckBox"; this.InstallPhysicsCheckBox.Size = new System.Drawing.Size( 62, 17 ); this.InstallPhysicsCheckBox.TabIndex = 7; this.InstallPhysicsCheckBox.Text = "Physics"; this.InstallPhysicsCheckBox.UseVisualStyleBackColor = true; this.InstallPhysicsCheckBox.CheckedChanged += new System.EventHandler( this.InstallFilterCheckBox_CheckedChanged ); // // InstallMeshCheckBox // this.InstallMeshCheckBox.AutoSize = true; this.InstallMeshCheckBox.Checked = true; this.InstallMeshCheckBox.CheckState = System.Windows.Forms.CheckState.Checked; this.InstallMeshCheckBox.Location = new System.Drawing.Point( 6, 16 ); this.InstallMeshCheckBox.Name = "InstallMeshCheckBox"; this.InstallMeshCheckBox.Size = new System.Drawing.Size( 52, 17 ); this.InstallMeshCheckBox.TabIndex = 4; this.InstallMeshCheckBox.Text = "Mesh"; this.InstallMeshCheckBox.UseVisualStyleBackColor = true; this.InstallMeshCheckBox.CheckedChanged += new System.EventHandler( this.InstallFilterCheckBox_CheckedChanged ); // // InstallMaterialCheckBox // this.InstallMaterialCheckBox.AutoSize = true; this.InstallMaterialCheckBox.Checked = true; this.InstallMaterialCheckBox.CheckState = System.Windows.Forms.CheckState.Checked; this.InstallMaterialCheckBox.Location = new System.Drawing.Point( 76, 16 ); this.InstallMaterialCheckBox.Name = "InstallMaterialCheckBox"; this.InstallMaterialCheckBox.Size = new System.Drawing.Size( 63, 17 ); this.InstallMaterialCheckBox.TabIndex = 5; this.InstallMaterialCheckBox.Text = "Material"; this.InstallMaterialCheckBox.UseVisualStyleBackColor = true; this.InstallMaterialCheckBox.CheckedChanged += new System.EventHandler( this.InstallFilterCheckBox_CheckedChanged ); // // InstallSkeletonCheckBox // this.InstallSkeletonCheckBox.AutoSize = true; this.InstallSkeletonCheckBox.Checked = true; this.InstallSkeletonCheckBox.CheckState = System.Windows.Forms.CheckState.Checked; this.InstallSkeletonCheckBox.Location = new System.Drawing.Point( 146, 16 ); this.InstallSkeletonCheckBox.Name = "InstallSkeletonCheckBox"; this.InstallSkeletonCheckBox.Size = new System.Drawing.Size( 68, 17 ); this.InstallSkeletonCheckBox.TabIndex = 6; this.InstallSkeletonCheckBox.Text = "Skeleton"; this.InstallSkeletonCheckBox.UseVisualStyleBackColor = true; this.InstallSkeletonCheckBox.CheckedChanged += new System.EventHandler( this.InstallFilterCheckBox_CheckedChanged ); // // InstallCheckBox // this.InstallCheckBox.AutoSize = true; this.InstallCheckBox.Checked = true; this.InstallCheckBox.CheckState = System.Windows.Forms.CheckState.Checked; this.InstallCheckBox.Location = new System.Drawing.Point( 9, 19 ); this.InstallCheckBox.Name = "InstallCheckBox"; this.InstallCheckBox.Size = new System.Drawing.Size( 173, 17 ); this.InstallCheckBox.TabIndex = 3; this.InstallCheckBox.Text = "Copy files to Asset Repositories"; this.InstallCheckBox.UseVisualStyleBackColor = true; this.InstallCheckBox.CheckedChanged += new System.EventHandler( this.InstallCheckBox_CheckedChanged ); // // CommandControl // this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F ); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add( this.groupBox4 ); this.Controls.Add( this.groupBox2 ); this.MinimumSize = new System.Drawing.Size( 210, 250 ); this.Name = "CommandControl"; this.Size = new System.Drawing.Size( 433, 279 ); this.Load += new System.EventHandler( this.CommandControl_Load ); this.groupBox4.ResumeLayout( false ); this.groupBox4.PerformLayout(); this.groupBox2.ResumeLayout( false ); this.groupBox2.PerformLayout(); this.InstallControlsPanel.ResumeLayout( false ); this.InstallControlsPanel.PerformLayout(); this.OverwritePolicyGroup.ResumeLayout( false ); this.OverwritePolicyGroup.PerformLayout(); this.FilterGroupBox.ResumeLayout( false ); this.FilterGroupBox.PerformLayout(); this.ResumeLayout( false ); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox CommandFlagTextBox; private System.Windows.Forms.CheckBox InstallCheckBox; private System.Windows.Forms.CheckBox ConvertCheckBox; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.CheckBox InstallMeshCheckBox; private System.Windows.Forms.CheckBox InstallPhysicsCheckBox; private System.Windows.Forms.CheckBox InstallSkeletonCheckBox; private System.Windows.Forms.CheckBox InstallMaterialCheckBox; private System.Windows.Forms.GroupBox FilterGroupBox; private System.Windows.Forms.CheckBox InstallTexturesCheckBox; private System.Windows.Forms.Panel InstallControlsPanel; private System.Windows.Forms.GroupBox OverwritePolicyGroup; private System.Windows.Forms.CheckBox ConfirmInstallationCheckBox; private System.Windows.Forms.RadioButton AskRadioButton; private System.Windows.Forms.RadioButton NeverRadioButton; private System.Windows.Forms.RadioButton AlwaysRadioButton; private System.Windows.Forms.GroupBox groupBox4; } }
using System.Configuration; using Rhino.Etl.Core.Infrastructure; namespace Rhino.Etl.Core.Operations { using System; using System.Linq; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using DataReaders; /// <summary> /// Allows to execute an operation that perform a bulk insert into a sql server database /// </summary> public abstract class SqlBulkInsertOperation : AbstractDatabaseOperation { /// <summary> /// The schema of the destination table /// </summary> private IDictionary<string, Type> _schema = new Dictionary<string, Type>(); /// <summary> /// The mapping of columns from the row to the database schema. /// Important: The column name in the database is case sensitive! /// </summary> public IDictionary<string, string> Mappings = new Dictionary<string, string>(); private readonly IDictionary<string, Type> _inputSchema = new Dictionary<string, Type>(); private SqlBulkCopy sqlBulkCopy; private string targetTable; private int timeout; private int batchSize; private int notifyBatchSize; private SqlBulkCopyOptions bulkCopyOptions = SqlBulkCopyOptions.Default; /// <summary> /// Initializes a new instance of the <see cref="SqlBulkInsertOperation"/> class. /// </summary> /// <param name="connectionStringName">Name of the connection string.</param> /// <param name="targetTable">The target table.</param> protected SqlBulkInsertOperation(string connectionStringName, string targetTable) : this(ConfigurationManager.ConnectionStrings[connectionStringName], targetTable) { } /// <summary> /// Initializes a new instance of the <see cref="SqlBulkInsertOperation"/> class. /// </summary> /// <param name="connectionStringSettings">Connection string settings to use.</param> /// <param name="targetTable">The target table.</param> protected SqlBulkInsertOperation(ConnectionStringSettings connectionStringSettings, string targetTable) : this(connectionStringSettings, targetTable, 600) { } /// <summary> /// Initializes a new instance of the <see cref="SqlBulkInsertOperation"/> class. /// </summary> /// <param name="connectionStringName">Name of the connection string.</param> /// <param name="targetTable">The target table.</param> /// <param name="timeout">The timeout.</param> protected SqlBulkInsertOperation(string connectionStringName, string targetTable, int timeout) : this(ConfigurationManager.ConnectionStrings[connectionStringName], targetTable, timeout) { Guard.Against(string.IsNullOrEmpty(targetTable), "TargetTable was not set, but it is mandatory"); this.targetTable = targetTable; this.timeout = timeout; } /// <summary> /// Initializes a new instance of the <see cref="SqlBulkInsertOperation"/> class. /// </summary> /// <param name="connectionStringSettings">Connection string settings to use.</param> /// <param name="targetTable">The target table.</param> /// <param name="timeout">The timeout.</param> protected SqlBulkInsertOperation(ConnectionStringSettings connectionStringSettings, string targetTable, int timeout) : base(connectionStringSettings) { Guard.Against(string.IsNullOrEmpty(targetTable), "TargetTable was not set, but it is mandatory"); this.targetTable = targetTable; this.timeout = timeout; } /// <summary>The timeout value of the bulk insert operation</summary> public virtual int Timeout { get { return timeout; } set { timeout = value; } } /// <summary>The batch size value of the bulk insert operation</summary> public virtual int BatchSize { get { return batchSize; } set { batchSize = value; } } /// <summary>The batch size value of the bulk insert operation</summary> public virtual int NotifyBatchSize { get { return notifyBatchSize>0 ? notifyBatchSize : batchSize; } set { notifyBatchSize = value; } } /// <summary>The table or view to bulk load the data into.</summary> public string TargetTable { get { return targetTable; } set { targetTable = value; } } /// <summary><c>true</c> to turn the <see cref="SqlBulkCopyOptions.TableLock"/> option on, otherwise <c>false</c>.</summary> public virtual bool LockTable { get { return IsOptionOn(SqlBulkCopyOptions.TableLock); } set { ToggleOption(SqlBulkCopyOptions.TableLock, value); } } /// <summary><c>true</c> to turn the <see cref="SqlBulkCopyOptions.KeepIdentity"/> option on, otherwise <c>false</c>.</summary> public virtual bool KeepIdentity { get { return IsOptionOn(SqlBulkCopyOptions.KeepIdentity); } set { ToggleOption(SqlBulkCopyOptions.KeepIdentity, value); } } /// <summary><c>true</c> to turn the <see cref="SqlBulkCopyOptions.KeepNulls"/> option on, otherwise <c>false</c>.</summary> public virtual bool KeepNulls { get { return IsOptionOn(SqlBulkCopyOptions.KeepNulls); } set { ToggleOption(SqlBulkCopyOptions.KeepNulls, value); } } /// <summary><c>true</c> to turn the <see cref="SqlBulkCopyOptions.CheckConstraints"/> option on, otherwise <c>false</c>.</summary> public virtual bool CheckConstraints { get { return IsOptionOn(SqlBulkCopyOptions.CheckConstraints); } set { ToggleOption(SqlBulkCopyOptions.CheckConstraints, value); } } /// <summary><c>true</c> to turn the <see cref="SqlBulkCopyOptions.FireTriggers"/> option on, otherwise <c>false</c>.</summary> public virtual bool FireTriggers { get { return IsOptionOn(SqlBulkCopyOptions.FireTriggers); } set { ToggleOption(SqlBulkCopyOptions.FireTriggers, value); } } /// <summary>Turns a <see cref="bulkCopyOptions"/> on or off depending on the value of <paramref name="on"/></summary> /// <param name="option">The <see cref="SqlBulkCopyOptions"/> to turn on or off.</param> /// <param name="on"><c>true</c> to set the <see cref="SqlBulkCopyOptions"/> <paramref name="option"/> on otherwise <c>false</c> to turn the <paramref name="option"/> off.</param> protected void ToggleOption(SqlBulkCopyOptions option, bool on) { if (on) { TurnOptionOn(option); } else { TurnOptionOff(option); } } /// <summary>Returns <c>true</c> if the <paramref name="option"/> is turned on, otherwise <c>false</c></summary> /// <param name="option">The <see cref="SqlBulkCopyOptions"/> option to test for.</param> /// <returns></returns> protected bool IsOptionOn(SqlBulkCopyOptions option) { return (bulkCopyOptions & option) == option; } /// <summary>Turns the <paramref name="option"/> on.</summary> /// <param name="option"></param> protected void TurnOptionOn(SqlBulkCopyOptions option) { bulkCopyOptions |= option; } /// <summary>Turns the <paramref name="option"/> off.</summary> /// <param name="option"></param> protected void TurnOptionOff(SqlBulkCopyOptions option) { if (IsOptionOn(option)) bulkCopyOptions ^= option; } /// <summary>The table or view's schema information.</summary> public IDictionary<string, Type> Schema { get { return _schema; } set { _schema = value; } } /// <summary> /// Prepares the mapping for use, by default, it uses the schema mapping. /// This is the preferred appraoch /// </summary> public virtual void PrepareMapping() { foreach (KeyValuePair<string, Type> pair in _schema) { Mappings[pair.Key] = pair.Key; } } /// <summary>Use the destination Schema and Mappings to create the /// operations input schema so it can build the adapter for sending /// to the WriteToServer method.</summary> public virtual void CreateInputSchema() { foreach(KeyValuePair<string, string> pair in Mappings) { _inputSchema.Add(pair.Key, _schema[pair.Value]); } } /// <summary> /// Executes this operation /// </summary> public override IEnumerable<Row> Execute(IEnumerable<Row> rows) { Guard.Against<ArgumentException>(rows == null, "SqlBulkInsertOperation cannot accept a null enumerator"); PrepareSchema(); PrepareMapping(); CreateInputSchema(); using (SqlConnection connection = (SqlConnection)Use.Connection(ConnectionStringSettings)) using (SqlTransaction transaction = (SqlTransaction) BeginTransaction(connection)) { sqlBulkCopy = CreateSqlBulkCopy(connection, transaction); DictionaryEnumeratorDataReader adapter = new DictionaryEnumeratorDataReader(_inputSchema, rows); try { sqlBulkCopy.WriteToServer(adapter); } catch (InvalidOperationException) { CompareSqlColumns(connection, transaction, rows); throw; } if (PipelineExecuter.HasErrors) { Warn("Rolling back transaction in {0}", Name); if (transaction != null) transaction.Rollback(); Warn("Rolled back transaction in {0}", Name); } else { Debug("Committing {0}", Name); if (transaction != null) transaction.Commit(); Debug("Committed {0}", Name); } } yield break; } /// <summary> /// Handle sql notifications /// </summary> protected virtual void onSqlRowsCopied(object sender, SqlRowsCopiedEventArgs e) { Debug("{0} rows copied to database", e.RowsCopied); } /// <summary> /// Prepares the schema of the target table /// </summary> protected abstract void PrepareSchema(); /// <summary> /// Creates the SQL bulk copy instance /// </summary> private SqlBulkCopy CreateSqlBulkCopy(SqlConnection connection, SqlTransaction transaction) { SqlBulkCopy copy = new SqlBulkCopy(connection, bulkCopyOptions, transaction); copy.BatchSize = batchSize; foreach (KeyValuePair<string, string> pair in Mappings) { copy.ColumnMappings.Add(pair.Key, pair.Value); } copy.NotifyAfter = NotifyBatchSize; copy.SqlRowsCopied += onSqlRowsCopied; copy.DestinationTableName = TargetTable; copy.BulkCopyTimeout = Timeout; return copy; } private void CompareSqlColumns(SqlConnection connection, SqlTransaction transaction, IEnumerable<Row> rows) { var command = connection.CreateCommand(); command.CommandText = "select * from {TargetTable} where 1=0".Replace("{TargetTable}", TargetTable); command.CommandType = CommandType.Text; command.Transaction = transaction; using (var reader = command.ExecuteReader(CommandBehavior.KeyInfo)) { var schemaTable = reader.GetSchemaTable(); var databaseColumns = schemaTable.Rows .OfType<DataRow>() .Select(r => new { Name = (string)r["ColumnName"], Type = (Type)r["DataType"], IsNullable = (bool)r["AllowDBNull"], MaxLength = (int)r["ColumnSize"] }) .ToArray(); var missingColumns = _schema.Keys.Except( databaseColumns.Select(c => c.Name)); if (missingColumns.Any()) throw new InvalidOperationException( "The following columns are not in the target table: " + string.Join(", ", missingColumns.ToArray())); var differentColumns = _schema .Select(s => new { Name = s.Key, SchemaType = s.Value, DatabaseType = databaseColumns.Single(c => c.Name == s.Key) }) .Where(c => !TypesMatch(c.SchemaType, c.DatabaseType.Type, c.DatabaseType.IsNullable)); if (differentColumns.Any()) throw new InvalidOperationException( "The following columns have different types in the target table: " + string.Join(", ", differentColumns //.Select(c => $"{c.Name}: is {GetFriendlyName(c.SchemaType)}, but should be {GetFriendlyName(c.DatabaseType.Type)}{(c.DatabaseType.IsNullable ? "?" : "")}.") // c.Name, GetFriendlyName(c.SchemaType), GetFriendlyName(c.DatabaseType.Type), (c.DatabaseType.IsNullable ? \"?\" : \"\") .Select(c => string.Format("{0}: is {1}, but should be {2}{3}.", c.Name, GetFriendlyName(c.SchemaType), GetFriendlyName(c.DatabaseType.Type), (c.DatabaseType.IsNullable ? "?" : ""))) .ToArray() )); var stringsTooLong = (from column in databaseColumns where column.Type == typeof(string) from mapping in Mappings where mapping.Value == column.Name let name = mapping.Key from row in rows let value = (string)row[name] where value != null && value.Length > column.MaxLength select new { column.Name, column.MaxLength, Value = value }) .ToArray(); if (stringsTooLong.Any()) throw new InvalidOperationException( "The folowing columns have values too long for the target table: " + string.Join(", ", stringsTooLong .Select(s => "{s.Name}: max length is {s.MaxLength}, value is {s.Value}." .Replace("{s.Name}", s.Name) .Replace("{s.MaxLength}", s.MaxLength.ToString()) .Replace("{s.Value}", s.Value) ) .ToArray())); } } private static string GetFriendlyName(Type type) { var friendlyName = type.Name; if (!type.IsGenericType) return friendlyName; var iBacktick = friendlyName.IndexOf('`'); if (iBacktick > 0) friendlyName = friendlyName.Remove(iBacktick); var genericParameters = type.GetGenericArguments() .Select(x => GetFriendlyName(x)) .ToArray(); friendlyName += "<" + string.Join(", ", genericParameters) + ">"; return friendlyName; } private bool TypesMatch(Type schemaType, Type databaseType, bool isNullable) { if (schemaType == databaseType) return true; if (isNullable && schemaType == typeof(Nullable<>).MakeGenericType(databaseType)) return true; return false; } } }
/****************************************************************************** * Spine Runtimes Software License v2.5 * * Copyright (c) 2013-2016, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable, and * non-transferable license to use, install, execute, and perform the Spine * Runtimes software and derivative works solely for personal or internal * use. Without the written permission of Esoteric Software (see Section 2 of * the Spine Software License Agreement), you may not (a) modify, translate, * adapt, or develop new applications using the Spine Runtimes or otherwise * create derivative works or improvements of the Spine Runtimes or (b) remove, * delete, alter, or obscure any trademarks or any copyright, trademark, patent, * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF * USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ #define SPINE_OPTIONAL_RENDEROVERRIDE #define SPINE_OPTIONAL_MATERIALOVERRIDE using System.Collections.Generic; using UnityEngine; namespace Spine.Unity { /// <summary>Renders a skeleton.</summary> [ExecuteInEditMode, RequireComponent(typeof(MeshFilter), typeof(MeshRenderer)), DisallowMultipleComponent] [HelpURL("http://esotericsoftware.com/spine-unity-documentation#Rendering")] public class SkeletonRenderer : MonoBehaviour, ISkeletonComponent { public delegate void SkeletonRendererDelegate (SkeletonRenderer skeletonRenderer); public event SkeletonRendererDelegate OnRebuild; /// <summary> Occurs after the vertex data is populated every frame, before the vertices are pushed into the mesh.</summary> public event Spine.Unity.MeshGeneratorDelegate OnPostProcessVertices; public SkeletonDataAsset skeletonDataAsset; public SkeletonDataAsset SkeletonDataAsset { get { return skeletonDataAsset; } } // ISkeletonComponent public string initialSkinName; public bool initialFlipX, initialFlipY; #region Advanced // Submesh Separation [UnityEngine.Serialization.FormerlySerializedAs("submeshSeparators")] [SpineSlot] public string[] separatorSlotNames = new string[0]; [System.NonSerialized] public readonly List<Slot> separatorSlots = new List<Slot>(); [Range(-0.1f, 0f)] public float zSpacing; //public bool renderMeshes = true; public bool useClipping = true; public bool immutableTriangles = false; public bool pmaVertexColors = true; public bool clearStateOnDisable = false; public bool tintBlack = false; public bool singleSubmesh = false; [UnityEngine.Serialization.FormerlySerializedAs("calculateNormals")] public bool addNormals; public bool calculateTangents; public bool logErrors = false; #if SPINE_OPTIONAL_RENDEROVERRIDE public bool disableRenderingOnOverride = true; public delegate void InstructionDelegate (SkeletonRendererInstruction instruction); event InstructionDelegate generateMeshOverride; public event InstructionDelegate GenerateMeshOverride { add { generateMeshOverride += value; if (disableRenderingOnOverride && generateMeshOverride != null) { Initialize(false); meshRenderer.enabled = false; } } remove { generateMeshOverride -= value; if (disableRenderingOnOverride && generateMeshOverride == null) { Initialize(false); meshRenderer.enabled = true; } } } #endif #if SPINE_OPTIONAL_MATERIALOVERRIDE [System.NonSerialized] readonly Dictionary<Material, Material> customMaterialOverride = new Dictionary<Material, Material>(); public Dictionary<Material, Material> CustomMaterialOverride { get { return customMaterialOverride; } } #endif // Custom Slot Material [System.NonSerialized] readonly Dictionary<Slot, Material> customSlotMaterials = new Dictionary<Slot, Material>(); public Dictionary<Slot, Material> CustomSlotMaterials { get { return customSlotMaterials; } } #endregion MeshRenderer meshRenderer; MeshFilter meshFilter; [System.NonSerialized] public bool valid; [System.NonSerialized] public Skeleton skeleton; public Skeleton Skeleton { get { Initialize(false); return skeleton; } } [System.NonSerialized] readonly SkeletonRendererInstruction currentInstructions = new SkeletonRendererInstruction(); readonly MeshGenerator meshGenerator = new MeshGenerator(); [System.NonSerialized] readonly MeshRendererBuffers rendererBuffers = new MeshRendererBuffers(); #region Runtime Instantiation public static T NewSpineGameObject<T> (SkeletonDataAsset skeletonDataAsset) where T : SkeletonRenderer { return SkeletonRenderer.AddSpineComponent<T>(new GameObject("New Spine GameObject"), skeletonDataAsset); } /// <summary>Add and prepare a Spine component that derives from SkeletonRenderer to a GameObject at runtime.</summary> /// <typeparam name="T">T should be SkeletonRenderer or any of its derived classes.</typeparam> public static T AddSpineComponent<T> (GameObject gameObject, SkeletonDataAsset skeletonDataAsset) where T : SkeletonRenderer { var c = gameObject.AddComponent<T>(); if (skeletonDataAsset != null) { c.skeletonDataAsset = skeletonDataAsset; c.Initialize(false); } return c; } #endregion public virtual void Awake () { Initialize(false); } void OnDisable () { if (clearStateOnDisable && valid) ClearState(); } void OnDestroy () { rendererBuffers.Dispose(); } public virtual void ClearState () { meshFilter.sharedMesh = null; currentInstructions.Clear(); if (skeleton != null) skeleton.SetToSetupPose(); } public virtual void Initialize (bool overwrite) { if (valid && !overwrite) return; // Clear { if (meshFilter != null) meshFilter.sharedMesh = null; meshRenderer = GetComponent<MeshRenderer>(); if (meshRenderer != null) meshRenderer.sharedMaterial = null; currentInstructions.Clear(); rendererBuffers.Clear(); meshGenerator.Begin(); skeleton = null; valid = false; } if (!skeletonDataAsset) { if (logErrors) Debug.LogError("Missing SkeletonData asset.", this); return; } SkeletonData skeletonData = skeletonDataAsset.GetSkeletonData(false); if (skeletonData == null) return; valid = true; meshFilter = GetComponent<MeshFilter>(); meshRenderer = GetComponent<MeshRenderer>(); rendererBuffers.Initialize(); skeleton = new Skeleton(skeletonData) { flipX = initialFlipX, flipY = initialFlipY }; if (!string.IsNullOrEmpty(initialSkinName) && !string.Equals(initialSkinName, "default", System.StringComparison.Ordinal)) skeleton.SetSkin(initialSkinName); separatorSlots.Clear(); for (int i = 0; i < separatorSlotNames.Length; i++) separatorSlots.Add(skeleton.FindSlot(separatorSlotNames[i])); LateUpdate(); if (OnRebuild != null) OnRebuild(this); } public virtual void LateUpdate () { if (!valid) return; #if SPINE_OPTIONAL_RENDEROVERRIDE bool doMeshOverride = generateMeshOverride != null; if ((!meshRenderer.enabled) && !doMeshOverride) return; #else const bool doMeshOverride = false; if (!meshRenderer.enabled) return; #endif var currentInstructions = this.currentInstructions; var workingSubmeshInstructions = currentInstructions.submeshInstructions; var currentSmartMesh = rendererBuffers.GetNextMesh(); // Double-buffer for performance. bool updateTriangles; if (this.singleSubmesh) { // STEP 1. Determine a SmartMesh.Instruction. Split up instructions into submeshes. ============================================= MeshGenerator.GenerateSingleSubmeshInstruction(currentInstructions, skeleton, skeletonDataAsset.atlasAssets[0].materials[0]); // STEP 1.9. Post-process workingInstructions. ================================================================================== #if SPINE_OPTIONAL_MATERIALOVERRIDE if (customMaterialOverride.Count > 0) // isCustomMaterialOverridePopulated MeshGenerator.TryReplaceMaterials(workingSubmeshInstructions, customMaterialOverride); #endif // STEP 2. Update vertex buffer based on verts from the attachments. =========================================================== meshGenerator.settings = new MeshGenerator.Settings { pmaVertexColors = this.pmaVertexColors, zSpacing = this.zSpacing, useClipping = this.useClipping, tintBlack = this.tintBlack, calculateTangents = this.calculateTangents, addNormals = this.addNormals }; meshGenerator.Begin(); updateTriangles = SkeletonRendererInstruction.GeometryNotEqual(currentInstructions, currentSmartMesh.instructionUsed); if (currentInstructions.hasActiveClipping) { meshGenerator.AddSubmesh(workingSubmeshInstructions.Items[0], updateTriangles); } else { meshGenerator.BuildMeshWithArrays(currentInstructions, updateTriangles); } } else { // STEP 1. Determine a SmartMesh.Instruction. Split up instructions into submeshes. ============================================= MeshGenerator.GenerateSkeletonRendererInstruction(currentInstructions, skeleton, customSlotMaterials, separatorSlots, doMeshOverride, this.immutableTriangles); // STEP 1.9. Post-process workingInstructions. ================================================================================== #if SPINE_OPTIONAL_MATERIALOVERRIDE if (customMaterialOverride.Count > 0) // isCustomMaterialOverridePopulated MeshGenerator.TryReplaceMaterials(workingSubmeshInstructions, customMaterialOverride); #endif #if SPINE_OPTIONAL_RENDEROVERRIDE if (doMeshOverride) { this.generateMeshOverride(currentInstructions); if (disableRenderingOnOverride) return; } #endif updateTriangles = SkeletonRendererInstruction.GeometryNotEqual(currentInstructions, currentSmartMesh.instructionUsed); // STEP 2. Update vertex buffer based on verts from the attachments. =========================================================== meshGenerator.settings = new MeshGenerator.Settings { pmaVertexColors = this.pmaVertexColors, zSpacing = this.zSpacing, useClipping = this.useClipping, tintBlack = this.tintBlack, calculateTangents = this.calculateTangents, addNormals = this.addNormals }; meshGenerator.Begin(); if (currentInstructions.hasActiveClipping) meshGenerator.BuildMesh(currentInstructions, updateTriangles); else meshGenerator.BuildMeshWithArrays(currentInstructions, updateTriangles); } if (OnPostProcessVertices != null) OnPostProcessVertices.Invoke(this.meshGenerator.Buffers); // STEP 3. Move the mesh data into a UnityEngine.Mesh =========================================================================== var currentMesh = currentSmartMesh.mesh; meshGenerator.FillVertexData(currentMesh); rendererBuffers.UpdateSharedMaterials(workingSubmeshInstructions); if (updateTriangles) { // Check if the triangles should also be updated. meshGenerator.FillTriangles(currentMesh); meshRenderer.sharedMaterials = rendererBuffers.GetUpdatedShaderdMaterialsArray(); } else if (rendererBuffers.MaterialsChangedInLastUpdate()) { meshRenderer.sharedMaterials = rendererBuffers.GetUpdatedShaderdMaterialsArray(); } // STEP 4. The UnityEngine.Mesh is ready. Set it as the MeshFilter's mesh. Store the instructions used for that mesh. =========== meshFilter.sharedMesh = currentMesh; currentSmartMesh.instructionUsed.Set(currentInstructions); } } }
// 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.Storage { using Azure; using Management; using Rest; using Rest.Azure; using Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// The Azure Storage Management API. /// </summary> public partial class StorageManagementClient : ServiceClient<StorageManagementClient>, IStorageManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets subscription credentials which uniquely identify the Microsoft Azure /// subscription. The subscription ID forms part of the URI for every service /// call. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Client Api Version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IStorageAccountsOperations. /// </summary> public virtual IStorageAccountsOperations StorageAccounts { get; private set; } /// <summary> /// Gets the IUsageOperations. /// </summary> public virtual IUsageOperations Usage { get; private set; } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected StorageManagementClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected StorageManagementClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected StorageManagementClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected StorageManagementClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public StorageManagementClient(ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public StorageManagementClient(ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public StorageManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public StorageManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { StorageAccounts = new StorageAccountsOperations(this); Usage = new UsageOperations(this); BaseUri = new System.Uri("https://management.azure.com"); ApiVersion = "2016-12-01"; AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // #if logging using System; using System.Collections.Generic; using System.IO; using System.Text; using Encog.Util; #endif using System.Collections.Generic; using System.IO; using System.Text; using System; using Encog.Util; namespace Encog.Parse.Tags.Read { /// <summary> /// Base class used to read tags. This base class is used by both the /// XML and HTML parsing. /// </summary> public class ReadTags { /// <summary> /// The bullet character. /// </summary> public int CharBullet = 149; /// <summary> /// The bullet character. /// </summary> public int CharTrademark = 129; /// <summary> /// Maximum length string to read. /// </summary> public int MaxLength = 10000; /// <summary> /// A mapping of certain HTML encoded values to their actual /// character values. /// </summary> private static IDictionary<string, char> _charMap; /// <summary> /// The stream that we are parsing from. /// </summary> private readonly PeekableInputStream _source; /// <summary> /// The current HTML tag. Access this property if the read function returns /// 0. /// </summary> private readonly Tag _tag = new Tag(); /// <summary> /// Are we locked, looking for an end tag? Such as the end of a /// comment? /// </summary> private string _lockedEndTag; /// <summary> /// Does a "fake" end-tag need to be added, because of a compound /// tag (i.e. <br/>)? If so, this will hold a string for that tag. /// </summary> private string _insertEndTag; /// <summary> /// The constructor should be passed an InputStream that we will parse from. /// </summary> /// <param name="istream">A stream to parse from.</param> public ReadTags(Stream istream) { _source = new PeekableInputStream(istream); if (_charMap == null) { _charMap = new Dictionary<string, char>(); _charMap["nbsp"] = ' '; _charMap["lt"] = '<'; _charMap["gt"] = '>'; _charMap["amp"] = '&'; _charMap["quot"] = '\"'; _charMap["bull"] = (char) CharBullet; _charMap["trade"] = (char) CharTrademark; } } /// <summary> /// Remove any whitespace characters that are next in the InputStream. /// </summary> protected void EatWhitespace() { while (char.IsWhiteSpace((char) _source.Peek())) { _source.Read(); } } /// <summary> /// Return the last tag found, this is normally called just after the read /// function returns a zero. /// </summary> public Tag LastTag { get { return _tag; } } /// <summary> /// Checks to see if the next tag is the tag specified. /// </summary> /// <param name="name">The name of the tag desired.</param> /// <param name="start">True if a starting tag is desired.</param> /// <returns>True if the next tag matches these criteria.</returns> public bool IsIt(string name, bool start) { if (!LastTag.Name.Equals(name)) { return false; } if (start) { return LastTag.TagType == Tag.Type.Begin; } return LastTag.TagType == Tag.Type.End; } /// <summary> /// Parse an attribute name, if one is present. /// </summary> /// <returns>Return the attribute name, or null if none present.</returns> protected string ParseAttributeName() { EatWhitespace(); if ("\"\'".IndexOf((char) _source.Peek()) == -1) { var buffer = new StringBuilder(); while (!char.IsWhiteSpace((char) _source.Peek()) && (_source.Peek() != '=') && (_source.Peek() != '>') && (_source.Peek() != -1)) { int ch = ParseSpecialCharacter(); buffer.Append((char) ch); } return buffer.ToString(); } return (ParseString()); } /// <summary> /// Parse any special characters /// </summary> /// <returns>The character that was parsed.</returns> private char ParseSpecialCharacter() { var result = (char) _source.Read(); int advanceBy = 0; // is there a special character? if (result == '&') { int ch; var buffer = new StringBuilder(); // loop through and read special character do { ch = _source.Peek(advanceBy++); if ((ch != '&') && (ch != ';') && !char.IsWhiteSpace((char) ch)) { buffer.Append((char) ch); } } while ((ch != ';') && (ch != -1) && !char.IsWhiteSpace((char) ch)); string b = buffer.ToString().Trim().ToLower(); // did we find a special character? if (b.Length > 0) { if (b[0] == '#') { try { result = (char) int.Parse(b.Substring(1)); } catch (Exception) { advanceBy = 0; } } else { if (_charMap.ContainsKey(b)) { result = _charMap[b]; } else { advanceBy = 0; } } } else { advanceBy = 0; } } while (advanceBy > 0) { Read(); advanceBy--; } return result; } /// <summary> /// Called to parse a double or single quote string. /// </summary> /// <returns>The string parsed.</returns> protected string ParseString() { var result = new StringBuilder(); EatWhitespace(); if ("\"\'".IndexOf((char) _source.Peek()) != -1) { int delim = _source.Read(); while ((_source.Peek() != delim) && (_source.Peek() != -1)) { if (result.Length > MaxLength) { break; } int ch = ParseSpecialCharacter(); if ((ch == '\r') || (ch == '\n')) { continue; } result.Append((char) ch); } if ("\"\'".IndexOf((char) _source.Peek()) != -1) { _source.Read(); } } else { while (!char.IsWhiteSpace((char) _source.Peek()) && (_source.Peek() != -1) && (_source.Peek() != '>')) { result.Append(ParseSpecialCharacter()); } } return result.ToString(); } /// <summary> /// Called when a tag is detected. This method will parse the tag. /// </summary> protected void ParseTag() { _tag.Clear(); _insertEndTag = null; var tagName = new StringBuilder(); _source.Read(); // Is it a comment? if (_source.Peek(TagConst.CommentBegin)) { _source.Skip(TagConst.CommentBegin.Length); while (!_source.Peek(TagConst.CommentEnd)) { int ch = _source.Read(); if (ch != -1) { tagName.Append((char) ch); } else { break; } } _source.Skip(TagConst.CommentEnd.Length); _tag.TagType = Tag.Type.Comment; _tag.Name = tagName.ToString(); return; } // Is it CDATA? if (_source.Peek(TagConst.CDATABegin)) { _source.Skip(TagConst.CDATABegin.Length); while (!_source.Peek(TagConst.CDATAEnd)) { int ch = _source.Read(); if (ch != -1) { tagName.Append((char) ch); } else { break; } } _source.Skip(TagConst.CDATAEnd.Length); _tag.TagType = Tag.Type.CDATA; _tag.Name = tagName.ToString(); return; } // Find the tag name while (_source.Peek() != -1) { // if this is the end of the tag, then stop if (char.IsWhiteSpace((char) _source.Peek()) || (_source.Peek() == '>')) { break; } // if this is both a begin and end tag then stop if ((tagName.Length > 0) && (_source.Peek() == '/')) { break; } tagName.Append((char) _source.Read()); } EatWhitespace(); if (tagName[0] == '/') { _tag.Name = tagName.ToString().Substring(1); _tag.TagType = Tag.Type.End; } else { _tag.Name = tagName.ToString(); _tag.TagType = Tag.Type.Begin; } // get the attributes while ((_source.Peek() != '>') && (_source.Peek() != -1)) { string attributeName = ParseAttributeName(); string attributeValue = null; if (attributeName.Equals("/")) { EatWhitespace(); if (_source.Peek() == '>') { _insertEndTag = _tag.Name; break; } } // is there a value? EatWhitespace(); if (_source.Peek() == '=') { _source.Read(); attributeValue = ParseString(); } _tag.SetAttribute(attributeName, attributeValue); } _source.Read(); } /// <summary> /// Check to see if the ending tag is present. /// </summary> /// <param name="name">The type of end tag being sought.</param> /// <returns>True if the ending tag was found.</returns> private bool PeekEndTag(IEnumerable<char> name) { int i = 0; // pass any whitespace while ((_source.Peek(i) != -1) && char.IsWhiteSpace((char) _source.Peek(i))) { i++; } // is a tag beginning if (_source.Peek(i) != '<') { return false; } i++; // pass any whitespace while ((_source.Peek(i) != -1) && char.IsWhiteSpace((char) _source.Peek(i))) { i++; } // is it an end tag if (_source.Peek(i) != '/') { return false; } i++; // pass any whitespace while ((_source.Peek(i) != -1) && char.IsWhiteSpace((char) _source.Peek(i))) { i++; } // does the name match foreach (char t in name) { if (char.ToLower((char) _source.Peek(i)) != char .ToLower(t)) { return false; } i++; } return true; } /// <summary> /// Read a single character from the HTML source, if this function returns /// zero(0) then you should call getTag to see what tag was found. Otherwise /// the value returned is simply the next character found. /// </summary> /// <returns>The character read, or zero if there is an HTML tag. If zero is /// returned, then call getTag to get the next tag.</returns> public int Read() { // handle inserting a "virtual" end tag if (_insertEndTag != null) { _tag.Clear(); _tag.Name = _insertEndTag; _tag.TagType = Tag.Type.End; _insertEndTag = null; return 0; } // handle locked end tag if (_lockedEndTag != null) { if (PeekEndTag(_lockedEndTag)) { _lockedEndTag = null; } else { return _source.Read(); } } // look for next tag if (_source.Peek() == '<') { ParseTag(); if ((_tag.TagType == Tag.Type.Begin) && ((StringUtil.EqualsIgnoreCase(_tag.Name, "script")) || (StringUtil.EqualsIgnoreCase(_tag.Name, "style")))) { _lockedEndTag = _tag.Name.ToLower(); } return 0; } if (_source.Peek() == '&') { return ParseSpecialCharacter(); } return (_source.Read()); } /// <summary> /// Read until we reach the next tag. /// </summary> /// <returns>True if a tag was found, false on EOF.</returns> public bool ReadToTag() { int ch; while ((ch = Read()) != -1) { if (ch == 0) { return true; } } return false; } /// <summary> /// Returns this object as a string. /// </summary> /// <returns>This object as a string.</returns> public override string ToString() { var result = new StringBuilder(); result.Append("[ReadTags: currentTag="); if (_tag != null) { result.Append(_tag.ToString()); } result.Append("]"); return result.ToString(); } } }
//------------------------------------------------------------------------------ // <copyright file="Processor.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace System.Xml.Xsl.XsltOld { using Res = System.Xml.Utils.Res; using System.Globalization; using System.Diagnostics; using System.IO; using System.Xml.XPath; using MS.Internal.Xml.XPath; using System.Text; using System.Collections; using System.Collections.Generic; using System.Xml.Xsl.XsltOld.Debugger; using System.Reflection; using System.Security; internal sealed class Processor : IXsltProcessor { // // Static constants // const int StackIncrement = 10; // // Execution result // internal enum ExecResult { Continue, // Continues next iteration immediately Interrupt, // Returns to caller, was processed enough Done // Execution finished } internal enum OutputResult { Continue, Interrupt, Overflow, Error, Ignore } private ExecResult execResult; // // Compiled stylesheet // private Stylesheet stylesheet; // Root of import tree of template managers private RootAction rootAction; private Key[] keyList; private List<TheQuery> queryStore; public PermissionSet permissions; // used by XsltCompiledContext in document and extension functions // // Document Being transformed // private XPathNavigator document; // // Execution action stack // private HWStack actionStack; private HWStack debuggerStack; // // Register for returning value from calling nested action // private StringBuilder sharedStringBuilder; // // Output related member variables // int ignoreLevel; StateMachine xsm; RecordBuilder builder; XsltOutput output; XmlNameTable nameTable = new NameTable(); XmlResolver resolver; #pragma warning disable 618 XsltArgumentList args; #pragma warning restore 618 Hashtable scriptExtensions; ArrayList numberList; // // Template lookup action // TemplateLookupAction templateLookup = new TemplateLookupAction(); private IXsltDebugger debugger; Query[] queryList; private ArrayList sortArray; private Hashtable documentCache; // NOTE: ValueOf() can call Matches() through XsltCompileContext.PreserveWhitespace(), // that's why we use two different contexts here, valueOfContext and matchesContext private XsltCompileContext valueOfContext; private XsltCompileContext matchesContext; internal XPathNavigator Current { get { ActionFrame frame = (ActionFrame) this.actionStack.Peek(); return frame != null ? frame.Node : null; } } internal ExecResult ExecutionResult { get { return this.execResult; } set { Debug.Assert(this.execResult == ExecResult.Continue); this.execResult = value; } } internal Stylesheet Stylesheet { get { return this.stylesheet; } } internal XmlResolver Resolver { get { Debug.Assert(this.resolver != null, "Constructor should create it if null passed"); return this.resolver; } } internal ArrayList SortArray { get { Debug.Assert(this.sortArray != null, "InitSortArray() wasn't called"); return this.sortArray; } } internal Key[] KeyList { get { return this.keyList; } } internal XPathNavigator GetNavigator(Uri ruri) { XPathNavigator result = null; if (documentCache != null) { result = documentCache[ruri] as XPathNavigator; if (result != null) { return result.Clone(); } } else { documentCache = new Hashtable(); } Object input = resolver.GetEntity(ruri, null, null); if (input is Stream) { XmlTextReaderImpl tr = new XmlTextReaderImpl(ruri.ToString(), (Stream) input); { tr.XmlResolver = this.resolver; } // reader is closed by Compiler.LoadDocument() result = ((IXPathNavigable)Compiler.LoadDocument(tr)).CreateNavigator(); } else if (input is XPathNavigator){ result = (XPathNavigator) input; } else { throw XsltException.Create(Res.Xslt_CantResolve, ruri.ToString()); } documentCache[ruri] = result.Clone(); return result; } internal void AddSort(Sort sortinfo) { Debug.Assert(this.sortArray != null, "InitSortArray() wasn't called"); this.sortArray.Add(sortinfo); } [System.Runtime.TargetedPatchingOptOutAttribute("Performance critical to inline across NGen image boundaries")] internal void InitSortArray() { if (this.sortArray == null) { this.sortArray = new ArrayList(); } else { this.sortArray.Clear(); } } internal object GetGlobalParameter(XmlQualifiedName qname) { object parameter = args.GetParam(qname.Name, qname.Namespace); if (parameter == null) { return null; } // if ( parameter is XPathNodeIterator || parameter is XPathNavigator || parameter is Boolean || parameter is Double || parameter is String ) { // doing nothing } else if ( parameter is Int16 || parameter is UInt16 || parameter is Int32 || parameter is UInt32 || parameter is Int64 || parameter is UInt64 || parameter is Single || parameter is Decimal ) { parameter = XmlConvert.ToXPathDouble(parameter); } else { parameter = parameter.ToString(); } return parameter; } internal object GetExtensionObject(string nsUri) { return args.GetExtensionObject(nsUri); } internal object GetScriptObject(string nsUri) { return scriptExtensions[nsUri]; } internal RootAction RootAction { get { return this.rootAction; } } internal XPathNavigator Document { get { return this.document; } } #if DEBUG private bool stringBuilderLocked = false; #endif internal StringBuilder GetSharedStringBuilder() { #if DEBUG Debug.Assert(! stringBuilderLocked); #endif if (sharedStringBuilder == null) { sharedStringBuilder = new StringBuilder(); } else { sharedStringBuilder.Length = 0; } #if DEBUG stringBuilderLocked = true; #endif return sharedStringBuilder; } internal void ReleaseSharedStringBuilder() { // don't clean stringBuilderLocked here. ToString() will happen after this call #if DEBUG stringBuilderLocked = false; #endif } internal ArrayList NumberList { get { if (this.numberList == null) { this.numberList = new ArrayList(); } return this.numberList; } } internal IXsltDebugger Debugger { get { return this.debugger; } } internal HWStack ActionStack { get { return this.actionStack; } } internal RecordBuilder Builder { get { return this.builder; } } internal XsltOutput Output { get { return this.output; } } // // Construction // public Processor( XPathNavigator doc, XsltArgumentList args, XmlResolver resolver, Stylesheet stylesheet, List<TheQuery> queryStore, RootAction rootAction, IXsltDebugger debugger ) { this.stylesheet = stylesheet; this.queryStore = queryStore; this.rootAction = rootAction; this.queryList = new Query[queryStore.Count]; { for(int i = 0; i < queryStore.Count; i ++) { queryList[i] = Query.Clone(queryStore[i].CompiledQuery.QueryTree); } } this.xsm = new StateMachine(); this.document = doc; this.builder = null; this.actionStack = new HWStack(StackIncrement); this.output = this.rootAction.Output; this.permissions = this.rootAction.permissions; this.resolver = resolver ?? XmlNullResolver.Singleton; this.args = args ?? new XsltArgumentList(); this.debugger = debugger; if (this.debugger != null) { this.debuggerStack = new HWStack(StackIncrement, /*limit:*/1000); templateLookup = new TemplateLookupActionDbg(); } // Clone the compile-time KeyList if (this.rootAction.KeyList != null) { this.keyList = new Key[this.rootAction.KeyList.Count]; for (int i = 0; i < this.keyList.Length; i ++) { this.keyList[i] = this.rootAction.KeyList[i].Clone(); } } this.scriptExtensions = new Hashtable(this.stylesheet.ScriptObjectTypes.Count); { foreach(DictionaryEntry entry in this.stylesheet.ScriptObjectTypes) { string namespaceUri = (string)entry.Key; if (GetExtensionObject(namespaceUri) != null) { throw XsltException.Create(Res.Xslt_ScriptDub, namespaceUri); } scriptExtensions.Add(namespaceUri, Activator.CreateInstance((Type)entry.Value, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, null, null)); } } this.PushActionFrame(this.rootAction, /*nodeSet:*/null); } [System.Runtime.TargetedPatchingOptOutAttribute("Performance critical to inline across NGen image boundaries")] public ReaderOutput StartReader() { ReaderOutput output = new ReaderOutput(this); this.builder = new RecordBuilder(output, this.nameTable); return output; } public void Execute(Stream stream) { RecordOutput recOutput = null; switch (this.output.Method) { case XsltOutput.OutputMethod.Text: recOutput = new TextOnlyOutput(this, stream); break; case XsltOutput.OutputMethod.Xml: case XsltOutput.OutputMethod.Html: case XsltOutput.OutputMethod.Other: case XsltOutput.OutputMethod.Unknown: recOutput = new TextOutput(this, stream); break; } this.builder = new RecordBuilder(recOutput, this.nameTable); Execute(); } public void Execute(TextWriter writer) { RecordOutput recOutput = null; switch (this.output.Method) { case XsltOutput.OutputMethod.Text: recOutput = new TextOnlyOutput(this, writer); break; case XsltOutput.OutputMethod.Xml: case XsltOutput.OutputMethod.Html: case XsltOutput.OutputMethod.Other: case XsltOutput.OutputMethod.Unknown: recOutput = new TextOutput(this, writer); break; } this.builder = new RecordBuilder(recOutput, this.nameTable); Execute(); } public void Execute(XmlWriter writer) { this.builder = new RecordBuilder(new WriterOutput(this, writer), this.nameTable); Execute(); } // // Execution part of processor // internal void Execute() { Debug.Assert(this.actionStack != null); while (this.execResult == ExecResult.Continue) { ActionFrame frame = (ActionFrame) this.actionStack.Peek(); if (frame == null) { Debug.Assert(this.builder != null); this.builder.TheEnd(); ExecutionResult = ExecResult.Done; break; } // Execute the action which was on the top of the stack if (frame.Execute(this)) { this.actionStack.Pop(); } } if (this.execResult == ExecResult.Interrupt) { this.execResult = ExecResult.Continue; } } // // Action frame support // internal ActionFrame PushNewFrame() { ActionFrame prent = (ActionFrame) this.actionStack.Peek(); ActionFrame frame = (ActionFrame) this.actionStack.Push(); if (frame == null) { frame = new ActionFrame(); this.actionStack.AddToTop(frame); } Debug.Assert(frame != null); if (prent != null) { frame.Inherit(prent); } return frame; } internal void PushActionFrame(Action action, XPathNodeIterator nodeSet) { ActionFrame frame = PushNewFrame(); frame.Init(action, nodeSet); } internal void PushActionFrame(ActionFrame container) { this.PushActionFrame(container, container.NodeSet); } internal void PushActionFrame(ActionFrame container, XPathNodeIterator nodeSet) { ActionFrame frame = PushNewFrame(); frame.Init(container, nodeSet); } internal void PushTemplateLookup(XPathNodeIterator nodeSet, XmlQualifiedName mode, Stylesheet importsOf) { Debug.Assert(this.templateLookup != null); this.templateLookup.Initialize(mode, importsOf); PushActionFrame(this.templateLookup, nodeSet); } internal string GetQueryExpression(int key) { Debug.Assert(key != Compiler.InvalidQueryKey); return this.queryStore[key].CompiledQuery.Expression; } internal Query GetCompiledQuery(int key) { Debug.Assert(key != Compiler.InvalidQueryKey); TheQuery theQuery = this.queryStore[key]; theQuery.CompiledQuery.CheckErrors(); Query expr = Query.Clone(this.queryList[key]); expr.SetXsltContext(new XsltCompileContext(theQuery._ScopeManager, this)); return expr; } internal Query GetValueQuery(int key) { return GetValueQuery(key, null); } internal Query GetValueQuery(int key, XsltCompileContext context) { Debug.Assert(key != Compiler.InvalidQueryKey); TheQuery theQuery = this.queryStore[key]; theQuery.CompiledQuery.CheckErrors(); Query expr = this.queryList[key]; if (context == null) { context = new XsltCompileContext(theQuery._ScopeManager, this); } else { context.Reinitialize(theQuery._ScopeManager, this); } expr.SetXsltContext(context); return expr; } private XsltCompileContext GetValueOfContext() { if (this.valueOfContext == null) { this.valueOfContext = new XsltCompileContext(); } return this.valueOfContext; } [Conditional("DEBUG")] private void RecycleValueOfContext() { if (this.valueOfContext != null) { this.valueOfContext.Recycle(); } } private XsltCompileContext GetMatchesContext() { if (this.matchesContext == null) { this.matchesContext = new XsltCompileContext(); } return this.matchesContext; } [Conditional("DEBUG")] private void RecycleMatchesContext() { if (this.matchesContext != null) { this.matchesContext.Recycle(); } } internal String ValueOf(ActionFrame context, int key) { string result; Query query = this.GetValueQuery(key, GetValueOfContext()); object value = query.Evaluate(context.NodeSet); if (value is XPathNodeIterator) { XPathNavigator n = query.Advance(); result = n != null ? ValueOf(n) : string.Empty; } else { result = XmlConvert.ToXPathString(value); } RecycleValueOfContext(); return result; } internal String ValueOf(XPathNavigator n) { if (this.stylesheet.Whitespace && n.NodeType == XPathNodeType.Element) { StringBuilder builder = this.GetSharedStringBuilder(); ElementValueWithoutWS(n, builder); this.ReleaseSharedStringBuilder(); return builder.ToString(); } return n.Value; } private void ElementValueWithoutWS(XPathNavigator nav, StringBuilder builder) { Debug.Assert(nav.NodeType == XPathNodeType.Element); bool preserve = this.Stylesheet.PreserveWhiteSpace(this, nav); if (nav.MoveToFirstChild()) { do { switch (nav.NodeType) { case XPathNodeType.Text : case XPathNodeType.SignificantWhitespace : builder.Append(nav.Value); break; case XPathNodeType.Whitespace : if (preserve) { builder.Append(nav.Value); } break; case XPathNodeType.Element : ElementValueWithoutWS(nav, builder); break; } }while (nav.MoveToNext()); nav.MoveToParent(); } } internal XPathNodeIterator StartQuery(XPathNodeIterator context, int key) { Query query = GetCompiledQuery(key); object result = query.Evaluate(context); if (result is XPathNodeIterator) { // ToDo: We create XPathSelectionIterator to count positions, but it's better create special query in this case at compile time. return new XPathSelectionIterator(context.Current, query); } throw XsltException.Create(Res.XPath_NodeSetExpected); } internal object Evaluate(ActionFrame context, int key) { return GetValueQuery(key).Evaluate(context.NodeSet); } internal object RunQuery(ActionFrame context, int key) { Query query = GetCompiledQuery(key); object value = query.Evaluate(context.NodeSet); XPathNodeIterator it = value as XPathNodeIterator; if (it != null) { return new XPathArrayIterator(it); } return value; } internal string EvaluateString(ActionFrame context, int key) { object objValue = Evaluate(context, key); string value = null; if (objValue != null) value = XmlConvert.ToXPathString(objValue); if (value == null) value = string.Empty; return value; } internal bool EvaluateBoolean(ActionFrame context, int key) { object objValue = Evaluate(context, key); if (objValue != null) { XPathNavigator nav = objValue as XPathNavigator; return nav != null ? Convert.ToBoolean(nav.Value, CultureInfo.InvariantCulture) : Convert.ToBoolean(objValue, CultureInfo.InvariantCulture); } else { return false; } } internal bool Matches(XPathNavigator context, int key) { // We don't use XPathNavigator.Matches() to avoid cloning of Query on each call Query query = this.GetValueQuery(key, GetMatchesContext()); try { bool result = query.MatchNode(context) != null; RecycleMatchesContext(); return result; } catch(XPathException) { throw XsltException.Create(Res.Xslt_InvalidPattern, this.GetQueryExpression(key)); } } // // Outputting part of processor // internal XmlNameTable NameTable { get { return this.nameTable; } } internal bool CanContinue { get { return this.execResult == ExecResult.Continue; } } internal bool ExecutionDone { get { return this.execResult == ExecResult.Done; } } internal void ResetOutput() { Debug.Assert(this.builder != null); this.builder.Reset(); } internal bool BeginEvent(XPathNodeType nodeType, string prefix, string name, string nspace, bool empty) { return BeginEvent(nodeType, prefix, name, nspace, empty, null, true); } internal bool BeginEvent(XPathNodeType nodeType, string prefix, string name, string nspace, bool empty, Object htmlProps, bool search) { Debug.Assert(this.xsm != null); int stateOutlook = this.xsm.BeginOutlook(nodeType); if (this.ignoreLevel > 0 || stateOutlook == StateMachine.Error) { this.ignoreLevel ++; return true; // We consumed the event, so pretend it was output. } switch (this.builder.BeginEvent(stateOutlook, nodeType, prefix, name, nspace, empty, htmlProps, search)) { case OutputResult.Continue: this.xsm.Begin(nodeType); Debug.Assert(StateMachine.StateOnly(stateOutlook) == this.xsm.State); Debug.Assert(ExecutionResult == ExecResult.Continue); return true; case OutputResult.Interrupt: this.xsm.Begin(nodeType); Debug.Assert(StateMachine.StateOnly(stateOutlook) == this.xsm.State); ExecutionResult = ExecResult.Interrupt; return true; case OutputResult.Overflow: ExecutionResult = ExecResult.Interrupt; return false; case OutputResult.Error: this.ignoreLevel ++; return true; case OutputResult.Ignore: return true; default: Debug.Fail("Unexpected result of RecordBuilder.BeginEvent()"); return true; } } internal bool TextEvent(string text) { return this.TextEvent(text, false); } internal bool TextEvent(string text, bool disableOutputEscaping) { Debug.Assert(this.xsm != null); if (this.ignoreLevel > 0) { return true; } int stateOutlook = this.xsm.BeginOutlook(XPathNodeType.Text); switch (this.builder.TextEvent(stateOutlook, text, disableOutputEscaping)) { case OutputResult.Continue: this.xsm.Begin(XPathNodeType.Text); Debug.Assert(StateMachine.StateOnly(stateOutlook) == this.xsm.State); Debug.Assert(ExecutionResult == ExecResult.Continue); return true; case OutputResult.Interrupt: this.xsm.Begin(XPathNodeType.Text); Debug.Assert(StateMachine.StateOnly(stateOutlook) == this.xsm.State); ExecutionResult = ExecResult.Interrupt; return true; case OutputResult.Overflow: ExecutionResult = ExecResult.Interrupt; return false; case OutputResult.Error: case OutputResult.Ignore: return true; default: Debug.Fail("Unexpected result of RecordBuilder.TextEvent()"); return true; } } internal bool EndEvent(XPathNodeType nodeType) { Debug.Assert(this.xsm != null); if (this.ignoreLevel > 0) { this.ignoreLevel --; return true; } int stateOutlook = this.xsm.EndOutlook(nodeType); switch (this.builder.EndEvent(stateOutlook, nodeType)) { case OutputResult.Continue: this.xsm.End(nodeType); Debug.Assert(StateMachine.StateOnly(stateOutlook) == this.xsm.State); return true; case OutputResult.Interrupt: this.xsm.End(nodeType); Debug.Assert(StateMachine.StateOnly(stateOutlook) == this.xsm.State, "StateMachine.StateOnly(stateOutlook) == this.xsm.State"); ExecutionResult = ExecResult.Interrupt; return true; case OutputResult.Overflow: ExecutionResult = ExecResult.Interrupt; return false; case OutputResult.Error: case OutputResult.Ignore: default: Debug.Fail("Unexpected result of RecordBuilder.TextEvent()"); return true; } } internal bool CopyBeginEvent(XPathNavigator node, bool emptyflag) { switch (node.NodeType) { case XPathNodeType.Element: case XPathNodeType.Attribute: case XPathNodeType.ProcessingInstruction: case XPathNodeType.Comment: return BeginEvent(node.NodeType, node.Prefix, node.LocalName, node.NamespaceURI, emptyflag); case XPathNodeType.Namespace: // value instead of namespace here! return BeginEvent(XPathNodeType.Namespace, null, node.LocalName, node.Value, false); case XPathNodeType.Text: // Text will be copied in CopyContents(); break; case XPathNodeType.Root: case XPathNodeType.Whitespace: case XPathNodeType.SignificantWhitespace: case XPathNodeType.All: break; default: Debug.Fail("Invalid XPathNodeType in CopyBeginEvent"); break; } return true; } internal bool CopyTextEvent(XPathNavigator node) { switch (node.NodeType) { case XPathNodeType.Element: case XPathNodeType.Namespace: break; case XPathNodeType.Attribute: case XPathNodeType.ProcessingInstruction: case XPathNodeType.Comment: case XPathNodeType.Text: case XPathNodeType.Whitespace: case XPathNodeType.SignificantWhitespace: string text = node.Value; return TextEvent(text); case XPathNodeType.Root: case XPathNodeType.All: break; default: Debug.Fail("Invalid XPathNodeType in CopyTextEvent"); break; } return true; } internal bool CopyEndEvent(XPathNavigator node) { switch (node.NodeType) { case XPathNodeType.Element: case XPathNodeType.Attribute: case XPathNodeType.ProcessingInstruction: case XPathNodeType.Comment: case XPathNodeType.Namespace: return EndEvent(node.NodeType); case XPathNodeType.Text: // Text was copied in CopyContents(); break; case XPathNodeType.Root: case XPathNodeType.Whitespace: case XPathNodeType.SignificantWhitespace: case XPathNodeType.All: break; default: Debug.Fail("Invalid XPathNodeType in CopyEndEvent"); break; } return true; } internal static bool IsRoot(XPathNavigator navigator) { Debug.Assert(navigator != null); if (navigator.NodeType == XPathNodeType.Root) { return true; } else if (navigator.NodeType == XPathNodeType.Element) { XPathNavigator clone = navigator.Clone(); clone.MoveToRoot(); return clone.IsSamePosition(navigator); } else { return false; } } // // Builder stack // internal void PushOutput(RecordOutput output) { Debug.Assert(output != null); this.builder.OutputState = this.xsm.State; RecordBuilder lastBuilder = this.builder; this.builder = new RecordBuilder(output, this.nameTable); this.builder.Next = lastBuilder; this.xsm.Reset(); } internal RecordOutput PopOutput() { Debug.Assert(this.builder != null); RecordBuilder topBuilder = this.builder; this.builder = topBuilder.Next; this.xsm.State = this.builder.OutputState; topBuilder.TheEnd(); return topBuilder.Output; } internal bool SetDefaultOutput(XsltOutput.OutputMethod method) { if(Output.Method != method) { this.output = this.output.CreateDerivedOutput(method); return true; } return false; } internal object GetVariableValue(VariableAction variable) { int variablekey = variable.VarKey; if (variable.IsGlobal) { ActionFrame rootFrame = (ActionFrame) this.actionStack[0]; object result = rootFrame.GetVariable(variablekey); if (result == VariableAction.BeingComputedMark) { throw XsltException.Create(Res.Xslt_CircularReference, variable.NameStr); } if (result != null) { return result; } // Variable wasn't evaluated yet int saveStackSize = this.actionStack.Length; ActionFrame varFrame = PushNewFrame(); varFrame.Inherit(rootFrame); varFrame.Init(variable, rootFrame.NodeSet); do { bool endOfFrame = ((ActionFrame) this.actionStack.Peek()).Execute(this); if (endOfFrame) { this.actionStack.Pop(); } } while (saveStackSize < this.actionStack.Length); Debug.Assert(saveStackSize == this.actionStack.Length); result = rootFrame.GetVariable(variablekey); Debug.Assert(result != null, "Variable was just calculated and result can't be null"); return result; } else { return ((ActionFrame) this.actionStack.Peek()).GetVariable(variablekey); } } internal void SetParameter(XmlQualifiedName name, object value) { Debug.Assert(1 < actionStack.Length); ActionFrame parentFrame = (ActionFrame) this.actionStack[actionStack.Length - 2]; parentFrame.SetParameter(name, value); } internal void ResetParams() { ActionFrame frame = (ActionFrame) this.actionStack[actionStack.Length - 1]; frame.ResetParams(); } internal object GetParameter(XmlQualifiedName name) { Debug.Assert(2 < actionStack.Length); ActionFrame parentFrame = (ActionFrame) this.actionStack[actionStack.Length - 3]; return parentFrame.GetParameter(name); } // ---------------------- Debugger stack ----------------------- internal class DebuggerFrame { internal ActionFrame actionFrame; internal XmlQualifiedName currentMode; } internal void PushDebuggerStack() { Debug.Assert(this.Debugger != null, "We don't generate calls this function if ! debugger"); DebuggerFrame dbgFrame = (DebuggerFrame) this.debuggerStack.Push(); if (dbgFrame == null) { dbgFrame = new DebuggerFrame(); this.debuggerStack.AddToTop(dbgFrame); } dbgFrame.actionFrame = (ActionFrame) this.actionStack.Peek(); // In a case of next builtIn action. } internal void PopDebuggerStack() { Debug.Assert(this.Debugger != null, "We don't generate calls this function if ! debugger"); this.debuggerStack.Pop(); } internal void OnInstructionExecute() { Debug.Assert(this.Debugger != null, "We don't generate calls this function if ! debugger"); DebuggerFrame dbgFrame = (DebuggerFrame) this.debuggerStack.Peek(); Debug.Assert(dbgFrame != null, "PushDebuggerStack() wasn't ever called"); dbgFrame.actionFrame = (ActionFrame) this.actionStack.Peek(); this.Debugger.OnInstructionExecute((IXsltProcessor) this); } internal XmlQualifiedName GetPrevioseMode() { Debug.Assert(this.Debugger != null, "We don't generate calls this function if ! debugger"); Debug.Assert(2 <= this.debuggerStack.Length); return ((DebuggerFrame) this.debuggerStack[this.debuggerStack.Length - 2]).currentMode; } internal void SetCurrentMode(XmlQualifiedName mode) { Debug.Assert(this.Debugger != null, "We don't generate calls this function if ! debugger"); ((DebuggerFrame) this.debuggerStack[this.debuggerStack.Length - 1]).currentMode = mode; } // ----------------------- IXsltProcessor : -------------------- int IXsltProcessor.StackDepth { get {return this.debuggerStack.Length;} } IStackFrame IXsltProcessor.GetStackFrame(int depth) { return ((DebuggerFrame) this.debuggerStack[depth]).actionFrame; } } }
/* ==================================================================== Licensed To the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file To You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed To in writing, software distributed under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ /* ================================================================ * About NPOI * Author: Tony Qu * Author's email: tonyqus (at) gmail.com * Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn) * HomePage: http://www.codeplex.com/npoi * Contributors: * * ==============================================================*/ namespace NPOI.HPSF { using System; using System.Text; using System.Collections; using NPOI.Util; using NPOI.HPSF.Wellknown; /// <summary> /// Represents a section in a {@link PropertySet}. /// @author Rainer Klute /// <a href="mailto:klute@rainer-klute.de">&lt;klute@rainer-klute.de&gt;</a> /// @author Drew Varner (Drew.Varner allUpIn sc.edu) /// @since 2002-02-09 /// </summary> public class Section { /** * Maps property IDs To section-private PID strings. These * strings can be found in the property with ID 0. */ protected IDictionary dictionary; /** * The section's format ID, {@link #GetFormatID}. */ protected ClassID formatID; /// <summary> /// Returns the format ID. The format ID is the "type" of the /// section. For example, if the format ID of the first {@link /// Section} Contains the bytes specified by /// <c>org.apache.poi.hpsf.wellknown.SectionIDMap.SUMMARY_INFORMATION_ID</c> /// the section (and thus the property Set) is a SummaryInformation. /// </summary> /// <value>The format ID.</value> public ClassID FormatID { get { return formatID; } } protected long offset; /// <summary> /// Gets the offset of the section in the stream. /// </summary> /// <value>The offset of the section in the stream</value> public long OffSet { get { return offset; } } protected int size; /// <summary> /// Returns the section's size in bytes. /// </summary> /// <value>The section's size in bytes.</value> public virtual int Size { get { return size; } } /// <summary> /// Returns the number of properties in this section. /// </summary> /// <value>The number of properties in this section.</value> public virtual int PropertyCount { get { return properties.Length; } } protected Property[] properties; /// <summary> /// Returns this section's properties. /// </summary> /// <value>This section's properties.</value> public virtual Property[] Properties { get { return properties; } } /// <summary> /// Creates an empty and uninitialized {@link Section}. /// </summary> protected Section() { } /// <summary> /// Creates a {@link Section} instance from a byte array. /// </summary> /// <param name="src">Contains the complete property Set stream.</param> /// <param name="offset">The position in the stream that points To the /// section's format ID.</param> public Section(byte[] src, int offset) { int o1 = offset; /* * Read the format ID. */ formatID = new ClassID(src, o1); o1 += ClassID.LENGTH; /* * Read the offset from the stream's start and positions To * the section header. */ this.offset = LittleEndian.GetUInt(src, o1); o1 = (int)this.offset; /* * Read the section Length. */ size = (int)LittleEndian.GetUInt(src, o1); o1 += LittleEndianConsts.INT_SIZE; /* * Read the number of properties. */ int propertyCount = (int)LittleEndian.GetUInt(src, o1); o1 += LittleEndianConsts.INT_SIZE; /* * Read the properties. The offset is positioned at the first * entry of the property list. There are two problems: * * 1. For each property we have To Find out its Length. In the * property list we Find each property's ID and its offset relative * To the section's beginning. Unfortunately the properties in the * property list need not To be in ascending order, so it is not * possible To calculate the Length as * (offset of property(i+1) - offset of property(i)). Before we can * that we first have To sort the property list by ascending offsets. * * 2. We have To Read the property with ID 1 before we Read other * properties, at least before other properties containing strings. * The reason is that property 1 specifies the codepage. If it Is * 1200, all strings are in Unicode. In other words: Before we can * Read any strings we have To know whether they are in Unicode or * not. Unfortunately property 1 is not guaranteed To be the first in * a section. * * The algorithm below Reads the properties in two passes: The first * one looks for property ID 1 and extracts the codepage number. The * seconds pass Reads the other properties. */ properties = new Property[propertyCount]; /* Pass 1: Read the property list. */ int pass1OffSet = o1; ArrayList propertyList = new ArrayList(propertyCount); PropertyListEntry ple; for (int i = 0; i < properties.Length; i++) { ple = new PropertyListEntry(); /* Read the property ID. */ ple.id = (int)LittleEndian.GetUInt(src, pass1OffSet); pass1OffSet += LittleEndianConsts.INT_SIZE; /* OffSet from the section's start. */ ple.offset = (int)LittleEndian.GetUInt(src, pass1OffSet); pass1OffSet += LittleEndianConsts.INT_SIZE; /* Add the entry To the property list. */ propertyList.Add(ple); } /* Sort the property list by ascending offsets: */ propertyList.Sort(); /* Calculate the properties' Lengths. */ for (int i = 0; i < propertyCount - 1; i++) { PropertyListEntry ple1 = (PropertyListEntry)propertyList[i]; PropertyListEntry ple2 = (PropertyListEntry)propertyList[i + 1]; ple1.Length = ple2.offset - ple1.offset; } if (propertyCount > 0) { ple = (PropertyListEntry)propertyList[propertyCount - 1]; ple.Length = size - ple.offset; //if (ple.Length <= 0) //{ // StringBuilder b = new StringBuilder(); // b.Append("The property Set claims To have a size of "); // b.Append(size); // b.Append(" bytes. However, it exceeds "); // b.Append(ple.offset); // b.Append(" bytes."); // throw new IllegalPropertySetDataException(b.ToString()); //} } /* Look for the codepage. */ int codepage = -1; for (IEnumerator i = propertyList.GetEnumerator(); codepage == -1 && i.MoveNext(); ) { ple = (PropertyListEntry)i.Current; /* Read the codepage if the property ID is 1. */ if (ple.id == PropertyIDMap.PID_CODEPAGE) { /* Read the property's value type. It must be * VT_I2. */ int o = (int)(this.offset + ple.offset); long type = LittleEndian.GetUInt(src, o); o += LittleEndianConsts.INT_SIZE; if (type != Variant.VT_I2) throw new HPSFRuntimeException ("Value type of property ID 1 is not VT_I2 but " + type + "."); /* Read the codepage number. */ codepage = LittleEndian.GetUShort(src, o); } } /* Pass 2: Read all properties - including the codepage property, * if available. */ int i1 = 0; for (IEnumerator i = propertyList.GetEnumerator(); i.MoveNext(); ) { ple = (PropertyListEntry)i.Current; Property p = new Property(ple.id, src, this.offset + ple.offset, ple.Length, codepage); if (p.ID == PropertyIDMap.PID_CODEPAGE) p = new Property(p.ID, p.Type, codepage); properties[i1++] = p; } /* * Extract the dictionary (if available). * Tony changed the logic */ this.dictionary = (IDictionary)GetProperty(0); } /** * Represents an entry in the property list and holds a property's ID and * its offset from the section's beginning. */ class PropertyListEntry : IComparable { public int id; public int offset; public int Length; /** * Compares this {@link PropertyListEntry} with another one by their * offsets. A {@link PropertyListEntry} is "smaller" than another one if * its offset from the section's begin is smaller. * * @see Comparable#CompareTo(java.lang.Object) */ public int CompareTo(Object o) { if (!(o is PropertyListEntry)) throw new InvalidCastException(o.ToString()); int otherOffSet = ((PropertyListEntry)o).offset; if (offset < otherOffSet) return -1; else if (offset == otherOffSet) return 0; else return 1; } public override int GetHashCode() { int prime = 31; int result = 1; result = prime * result + id; result = prime * result + Length; result = prime * result + offset; return result; } public override bool Equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (GetType() != obj.GetType()) return false; PropertyListEntry other = (PropertyListEntry)obj; if (id != other.id) return false; if (Length != other.Length) return false; if (offset != other.offset) return false; return true; } public override String ToString() { StringBuilder b = new StringBuilder(); b.Append(GetType().Name); b.Append("[id="); b.Append(id); b.Append(", offset="); b.Append(offset); b.Append(", Length="); b.Append(Length); b.Append(']'); return b.ToString(); } } /** * Returns the value of the property with the specified ID. If * the property is not available, <c>null</c> is returned * and a subsequent call To {@link #wasNull} will return * <c>true</c>. * * @param id The property's ID * * @return The property's value */ public virtual Object GetProperty(long id) { wasNull = false; for (int i = 0; i < properties.Length; i++) if (id == properties[i].ID) return properties[i].Value; wasNull = true; return null; } /** * Returns the value of the numeric property with the specified * ID. If the property is not available, 0 is returned. A * subsequent call To {@link #wasNull} will return * <c>true</c> To let the caller distinguish that case from * a real property value of 0. * * @param id The property's ID * * @return The property's value */ public virtual int GetPropertyIntValue(long id) { Object o = GetProperty(id); if (o == null) return 0; if (!(o is long || o is int)) throw new HPSFRuntimeException ("This property is not an integer type, but " + o.GetType().Name + "."); return (int)o; } /** * Returns the value of the bool property with the specified * ID. If the property is not available, <c>false</c> Is * returned. A subsequent call To {@link #wasNull} will return * <c>true</c> To let the caller distinguish that case from * a real property value of <c>false</c>. * * @param id The property's ID * * @return The property's value */ public virtual bool GetPropertyBooleanValue(int id) { object tmp = GetProperty(id); if (tmp != null) { return (bool)GetProperty(id); } else { return false; } } /** * This member is <c>true</c> if the last call To {@link * #GetPropertyIntValue} or {@link #GetProperty} tried To access a * property that was not available, else <c>false</c>. */ private bool wasNull; /// <summary> /// Checks whether the property which the last call To {@link /// #GetPropertyIntValue} or {@link #GetProperty} tried To access /// was available or not. This information might be important for /// callers of {@link #GetPropertyIntValue} since the latter /// returns 0 if the property does not exist. Using {@link /// #wasNull} the caller can distiguish this case from a property's /// real value of 0. /// </summary> /// <value><c>true</c> if the last call To {@link /// #GetPropertyIntValue} or {@link #GetProperty} tried To access a /// property that was not available; otherwise, <c>false</c>.</value> public virtual bool WasNull { get { return wasNull; } } /// <summary> /// Returns the PID string associated with a property ID. The ID /// is first looked up in the {@link Section}'s private /// dictionary. If it is not found there, the method calls {@link /// SectionIDMap#GetPIDString}. /// </summary> /// <param name="pid">The property ID.</param> /// <returns>The property ID's string value</returns> public String GetPIDString(long pid) { String s = null; if (dictionary != null) s = (String)dictionary[pid]; if (s == null) s = SectionIDMap.GetPIDString(FormatID.Bytes, pid); return s; } /** * Checks whether this section is equal To another object. The result Is * <c>false</c> if one of the the following conditions holds: * * <ul> * * <li>The other object is not a {@link Section}.</li> * * <li>The format IDs of the two sections are not equal.</li> * * <li>The sections have a different number of properties. However, * properties with ID 1 (codepage) are not counted.</li> * * <li>The other object is not a {@link Section}.</li> * * <li>The properties have different values. The order of the properties * is irrelevant.</li> * * </ul> * * @param o The object To Compare this section with * @return <c>true</c> if the objects are equal, <c>false</c> if * not */ public override bool Equals(Object o) { if (o == null || !(o is Section)) return false; Section s = (Section)o; if (!s.FormatID.Equals(FormatID)) return false; /* Compare all properties except 0 and 1 as they must be handled * specially. */ Property[] pa1 = new Property[Properties.Length]; Property[] pa2 = new Property[s.Properties.Length]; System.Array.Copy(Properties, 0, pa1, 0, pa1.Length); System.Array.Copy(s.Properties, 0, pa2, 0, pa2.Length); /* Extract properties 0 and 1 and Remove them from the copy of the * arrays. */ Property p10 = null; Property p20 = null; for (int i = 0; i < pa1.Length; i++) { long id = pa1[i].ID; if (id == 0) { p10 = pa1[i]; pa1 = Remove(pa1, i); i--; } if (id == 1) { // p11 = pa1[i]; pa1 = Remove(pa1, i); i--; } } for (int i = 0; i < pa2.Length; i++) { long id = pa2[i].ID; if (id == 0) { p20 = pa2[i]; pa2 = Remove(pa2, i); i--; } if (id == 1) { // p21 = pa2[i]; pa2 = Remove(pa2, i); i--; } } /* If the number of properties (not counting property 1) is unequal the * sections are unequal. */ if (pa1.Length != pa2.Length) return false; /* If the dictionaries are unequal the sections are unequal. */ bool dictionaryEqual = true; if (p10 != null && p20 != null) { //tony qu fixed this issue Hashtable a=(Hashtable)p10.Value; Hashtable b = (Hashtable)p20.Value; dictionaryEqual = a.Count==b.Count; } else if (p10 != null || p20 != null) { dictionaryEqual = false; } if (!dictionaryEqual) return false; else return Util.AreEqual(pa1, pa2); } /// <summary> /// Removes a field from a property array. The resulting array Is /// compactified and returned. /// </summary> /// <param name="pa">The property array.</param> /// <param name="i">The index of the field To be Removed.</param> /// <returns>the compactified array.</returns> private Property[] Remove(Property[] pa, int i) { Property[] h = new Property[pa.Length - 1]; if (i > 0) System.Array.Copy(pa, 0, h, 0, i); System.Array.Copy(pa, i + 1, h, i, h.Length - i); return h; } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { long GetHashCode = 0; GetHashCode += FormatID.GetHashCode(); Property[] pa = Properties; for (int i = 0; i < pa.Length; i++) GetHashCode += pa[i].GetHashCode(); int returnHashCode = (int)(GetHashCode & 0x0ffffffffL); return returnHashCode; } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override String ToString() { StringBuilder b = new StringBuilder(); Property[] pa = Properties; b.Append(GetType().Name); b.Append('['); b.Append("formatID: "); b.Append(FormatID); b.Append(", offset: "); b.Append(OffSet); b.Append(", propertyCount: "); b.Append(PropertyCount); b.Append(", size: "); b.Append(Size); b.Append(", properties: [\n"); for (int i = 0; i < pa.Length; i++) { b.Append(pa[i].ToString()); b.Append(",\n"); } b.Append(']'); b.Append(']'); return b.ToString(); } /// <summary> /// Gets the section's dictionary. A dictionary allows an application To /// use human-Readable property names instead of numeric property IDs. It /// Contains mappings from property IDs To their associated string /// values. The dictionary is stored as the property with ID 0. The codepage /// for the strings in the dictionary is defined by property with ID 1. /// </summary> /// <value>the dictionary or null /// if the section does not have /// a dictionary.</value> public virtual IDictionary Dictionary { get { if (dictionary == null) dictionary = new Hashtable(); return dictionary; } set { dictionary = value; } } /// <summary> /// Gets the section's codepage, if any. /// </summary> /// <value>The section's codepage if one is defined, else -1.</value> public int Codepage { get { if (GetProperty(PropertyIDMap.PID_CODEPAGE) == null) return -1; int codepage = (int)GetProperty(PropertyIDMap.PID_CODEPAGE); return codepage; } } } }
using System; using System.Runtime.InteropServices; using System.Linq; namespace SteamNative { internal struct GID_t { public ulong Value; public static implicit operator GID_t( ulong value ) { return new GID_t(){ Value = value }; } public static implicit operator ulong( GID_t value ) { return value.Value; } } internal struct JobID_t { public ulong Value; public static implicit operator JobID_t( ulong value ) { return new JobID_t(){ Value = value }; } public static implicit operator ulong( JobID_t value ) { return value.Value; } } internal struct TxnID_t { public GID_t Value; public static implicit operator TxnID_t( GID_t value ) { return new TxnID_t(){ Value = value }; } public static implicit operator GID_t( TxnID_t value ) { return value.Value; } } internal struct PackageId_t { public uint Value; public static implicit operator PackageId_t( uint value ) { return new PackageId_t(){ Value = value }; } public static implicit operator uint( PackageId_t value ) { return value.Value; } } internal struct BundleId_t { public uint Value; public static implicit operator BundleId_t( uint value ) { return new BundleId_t(){ Value = value }; } public static implicit operator uint( BundleId_t value ) { return value.Value; } } internal struct AppId_t { public uint Value; public static implicit operator AppId_t( uint value ) { return new AppId_t(){ Value = value }; } public static implicit operator uint( AppId_t value ) { return value.Value; } } internal struct AssetClassId_t { public ulong Value; public static implicit operator AssetClassId_t( ulong value ) { return new AssetClassId_t(){ Value = value }; } public static implicit operator ulong( AssetClassId_t value ) { return value.Value; } } internal struct PhysicalItemId_t { public uint Value; public static implicit operator PhysicalItemId_t( uint value ) { return new PhysicalItemId_t(){ Value = value }; } public static implicit operator uint( PhysicalItemId_t value ) { return value.Value; } } internal struct DepotId_t { public uint Value; public static implicit operator DepotId_t( uint value ) { return new DepotId_t(){ Value = value }; } public static implicit operator uint( DepotId_t value ) { return value.Value; } } internal struct RTime32 { public uint Value; public static implicit operator RTime32( uint value ) { return new RTime32(){ Value = value }; } public static implicit operator uint( RTime32 value ) { return value.Value; } } internal struct CellID_t { public uint Value; public static implicit operator CellID_t( uint value ) { return new CellID_t(){ Value = value }; } public static implicit operator uint( CellID_t value ) { return value.Value; } } internal struct SteamAPICall_t { public ulong Value; public static implicit operator SteamAPICall_t( ulong value ) { return new SteamAPICall_t(){ Value = value }; } public static implicit operator ulong( SteamAPICall_t value ) { return value.Value; } } internal struct AccountID_t { public uint Value; public static implicit operator AccountID_t( uint value ) { return new AccountID_t(){ Value = value }; } public static implicit operator uint( AccountID_t value ) { return value.Value; } } internal struct PartnerId_t { public uint Value; public static implicit operator PartnerId_t( uint value ) { return new PartnerId_t(){ Value = value }; } public static implicit operator uint( PartnerId_t value ) { return value.Value; } } internal struct ManifestId_t { public ulong Value; public static implicit operator ManifestId_t( ulong value ) { return new ManifestId_t(){ Value = value }; } public static implicit operator ulong( ManifestId_t value ) { return value.Value; } } internal struct HAuthTicket { public uint Value; public static implicit operator HAuthTicket( uint value ) { return new HAuthTicket(){ Value = value }; } public static implicit operator uint( HAuthTicket value ) { return value.Value; } } internal struct BREAKPAD_HANDLE { public IntPtr Value; public static implicit operator BREAKPAD_HANDLE( IntPtr value ) { return new BREAKPAD_HANDLE(){ Value = value }; } public static implicit operator IntPtr( BREAKPAD_HANDLE value ) { return value.Value; } } internal struct HSteamPipe { public int Value; public static implicit operator HSteamPipe( int value ) { return new HSteamPipe(){ Value = value }; } public static implicit operator int( HSteamPipe value ) { return value.Value; } } internal struct HSteamUser { public int Value; public static implicit operator HSteamUser( int value ) { return new HSteamUser(){ Value = value }; } public static implicit operator int( HSteamUser value ) { return value.Value; } } internal struct FriendsGroupID_t { public short Value; public static implicit operator FriendsGroupID_t( short value ) { return new FriendsGroupID_t(){ Value = value }; } public static implicit operator short( FriendsGroupID_t value ) { return value.Value; } } internal struct HServerListRequest { public IntPtr Value; public static implicit operator HServerListRequest( IntPtr value ) { return new HServerListRequest(){ Value = value }; } public static implicit operator IntPtr( HServerListRequest value ) { return value.Value; } } internal struct HServerQuery { public int Value; public static implicit operator HServerQuery( int value ) { return new HServerQuery(){ Value = value }; } public static implicit operator int( HServerQuery value ) { return value.Value; } } internal struct UGCHandle_t { public ulong Value; public static implicit operator UGCHandle_t( ulong value ) { return new UGCHandle_t(){ Value = value }; } public static implicit operator ulong( UGCHandle_t value ) { return value.Value; } } internal struct PublishedFileUpdateHandle_t { public ulong Value; public static implicit operator PublishedFileUpdateHandle_t( ulong value ) { return new PublishedFileUpdateHandle_t(){ Value = value }; } public static implicit operator ulong( PublishedFileUpdateHandle_t value ) { return value.Value; } } internal struct PublishedFileId_t { public ulong Value; public static implicit operator PublishedFileId_t( ulong value ) { return new PublishedFileId_t(){ Value = value }; } public static implicit operator ulong( PublishedFileId_t value ) { return value.Value; } } internal struct UGCFileWriteStreamHandle_t { public ulong Value; public static implicit operator UGCFileWriteStreamHandle_t( ulong value ) { return new UGCFileWriteStreamHandle_t(){ Value = value }; } public static implicit operator ulong( UGCFileWriteStreamHandle_t value ) { return value.Value; } } internal struct SteamLeaderboard_t { public ulong Value; public static implicit operator SteamLeaderboard_t( ulong value ) { return new SteamLeaderboard_t(){ Value = value }; } public static implicit operator ulong( SteamLeaderboard_t value ) { return value.Value; } } internal struct SteamLeaderboardEntries_t { public ulong Value; public static implicit operator SteamLeaderboardEntries_t( ulong value ) { return new SteamLeaderboardEntries_t(){ Value = value }; } public static implicit operator ulong( SteamLeaderboardEntries_t value ) { return value.Value; } } internal struct SNetSocket_t { public uint Value; public static implicit operator SNetSocket_t( uint value ) { return new SNetSocket_t(){ Value = value }; } public static implicit operator uint( SNetSocket_t value ) { return value.Value; } } internal struct SNetListenSocket_t { public uint Value; public static implicit operator SNetListenSocket_t( uint value ) { return new SNetListenSocket_t(){ Value = value }; } public static implicit operator uint( SNetListenSocket_t value ) { return value.Value; } } internal struct ScreenshotHandle { public uint Value; public static implicit operator ScreenshotHandle( uint value ) { return new ScreenshotHandle(){ Value = value }; } public static implicit operator uint( ScreenshotHandle value ) { return value.Value; } } internal struct HTTPRequestHandle { public uint Value; public static implicit operator HTTPRequestHandle( uint value ) { return new HTTPRequestHandle(){ Value = value }; } public static implicit operator uint( HTTPRequestHandle value ) { return value.Value; } } internal struct HTTPCookieContainerHandle { public uint Value; public static implicit operator HTTPCookieContainerHandle( uint value ) { return new HTTPCookieContainerHandle(){ Value = value }; } public static implicit operator uint( HTTPCookieContainerHandle value ) { return value.Value; } } internal struct ClientUnifiedMessageHandle { public ulong Value; public static implicit operator ClientUnifiedMessageHandle( ulong value ) { return new ClientUnifiedMessageHandle(){ Value = value }; } public static implicit operator ulong( ClientUnifiedMessageHandle value ) { return value.Value; } } internal struct ControllerHandle_t { public ulong Value; public static implicit operator ControllerHandle_t( ulong value ) { return new ControllerHandle_t(){ Value = value }; } public static implicit operator ulong( ControllerHandle_t value ) { return value.Value; } } internal struct ControllerActionSetHandle_t { public ulong Value; public static implicit operator ControllerActionSetHandle_t( ulong value ) { return new ControllerActionSetHandle_t(){ Value = value }; } public static implicit operator ulong( ControllerActionSetHandle_t value ) { return value.Value; } } internal struct ControllerDigitalActionHandle_t { public ulong Value; public static implicit operator ControllerDigitalActionHandle_t( ulong value ) { return new ControllerDigitalActionHandle_t(){ Value = value }; } public static implicit operator ulong( ControllerDigitalActionHandle_t value ) { return value.Value; } } internal struct ControllerAnalogActionHandle_t { public ulong Value; public static implicit operator ControllerAnalogActionHandle_t( ulong value ) { return new ControllerAnalogActionHandle_t(){ Value = value }; } public static implicit operator ulong( ControllerAnalogActionHandle_t value ) { return value.Value; } } internal struct UGCQueryHandle_t { public ulong Value; public static implicit operator UGCQueryHandle_t( ulong value ) { return new UGCQueryHandle_t(){ Value = value }; } public static implicit operator ulong( UGCQueryHandle_t value ) { return value.Value; } } internal struct UGCUpdateHandle_t { public ulong Value; public static implicit operator UGCUpdateHandle_t( ulong value ) { return new UGCUpdateHandle_t(){ Value = value }; } public static implicit operator ulong( UGCUpdateHandle_t value ) { return value.Value; } } internal struct HHTMLBrowser { public uint Value; public static implicit operator HHTMLBrowser( uint value ) { return new HHTMLBrowser(){ Value = value }; } public static implicit operator uint( HHTMLBrowser value ) { return value.Value; } } internal struct SteamItemInstanceID_t { public ulong Value; public static implicit operator SteamItemInstanceID_t( ulong value ) { return new SteamItemInstanceID_t(){ Value = value }; } public static implicit operator ulong( SteamItemInstanceID_t value ) { return value.Value; } } internal struct SteamItemDef_t { public int Value; public static implicit operator SteamItemDef_t( int value ) { return new SteamItemDef_t(){ Value = value }; } public static implicit operator int( SteamItemDef_t value ) { return value.Value; } } internal struct SteamInventoryResult_t { public int Value; public static implicit operator SteamInventoryResult_t( int value ) { return new SteamInventoryResult_t(){ Value = value }; } public static implicit operator int( SteamInventoryResult_t value ) { return value.Value; } } internal struct CGameID { public ulong Value; public static implicit operator CGameID( ulong value ) { return new CGameID(){ Value = value }; } public static implicit operator ulong( CGameID value ) { return value.Value; } } internal struct CSteamID { public ulong Value; public static implicit operator CSteamID( ulong value ) { return new CSteamID(){ Value = value }; } public static implicit operator ulong( CSteamID value ) { return value.Value; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading; using Android.OS; using Java.Net; using System.Threading.Tasks; using Android.Runtime; namespace MonoCross.Utilities.Networking { /// <summary> /// Represents a network fetch utility that performs asynchronously. /// </summary> public class AndroidFetcher : IFetcher { private const int DefaultTimeout = 180 * 1000; // default to 180 seconds [Preserve] public AndroidFetcher() { } private void DisableConnectionReuseIfNecessary() { // Work around pre-Gingerbread bugs in HTTP connection reuse. if ((int)Build.VERSION.SdkInt < 9) { Java.Lang.JavaSystem.SetProperty("http.keepAlive", "false"); } } /// <summary> /// Fetches the specified URI. /// </summary> /// <param name="uri">The URI of the resource to fetch.</param> public NetworkResponse Fetch(string uri) { return Fetch(uri, null, null, DefaultTimeout); } /// <summary> /// Fetches the specified URI. /// </summary> /// <param name="uri">The URI of the resource to fetch.</param> /// <param name="timeout">The request timeout value in milliseconds.</param> public NetworkResponse Fetch(string uri, int timeout) { return Fetch(uri, null, null, timeout); } /// <summary> /// Fetches the specified URI. /// </summary> /// <param name="uri">The URI of the resource to fetch.</param> /// <param name="headers">The headers to be added to the request.</param> public NetworkResponse Fetch(string uri, IDictionary<string, string> headers) { return Fetch(uri, null, headers, DefaultTimeout); } /// <summary> /// Fetches the specified URI. /// </summary> /// <param name="uri">The URI of the resource to fetch.</param> /// <param name="headers">The headers to be added to the request.</param> /// <param name="timeout">The request timeout value in milliseconds.</param> public NetworkResponse Fetch(string uri, IDictionary<string, string> headers, int timeout) { return Fetch(uri, null, headers, timeout); } /// <summary> /// Fetches the specified URI. /// </summary> /// <param name="uri">The URI of the resource to fetch.</param> /// <param name="filename">The name of the file to be fetched.</param> public NetworkResponse Fetch(string uri, string filename) { return Fetch(uri, filename, null, DefaultTimeout); } /// <summary> /// Fetches the specified URI. /// </summary> /// <param name="uri">The URI of the resource to fetch.</param> /// <param name="filename">The name of the file to be fetched.</param> /// <param name="timeout">The request timeout value in milliseconds.</param> public NetworkResponse Fetch(string uri, string filename, int timeout) { return Fetch(uri, filename, null, timeout); } /// <summary> /// Fetches the specified URI. /// </summary> /// <param name="uri">The URI of the resource to fetch.</param> /// <param name="filename">The name of the file to be fetched.</param> /// <param name="headers">The headers to be added to the request.</param> public NetworkResponse Fetch(string uri, string filename, IDictionary<string, string> headers) { return Fetch(uri, filename, headers, DefaultTimeout); } private DateTime _dtMetric; /// <summary> /// Fetches the specified URI. /// </summary> /// <param name="uri">The URI of the resource to fetch.</param> /// <param name="filename">The name of the file to be fetched.</param> /// <param name="headers">The headers to be added to the request.</param> /// <param name="timeout">The request timeout value in milliseconds.</param> public NetworkResponse Fetch(string uri, string filename, IDictionary<string, string> headers, int timeout) { var fetchParameters = new DroidFetchParameters { NetworkResponse = new NetworkResponse(), Uri = uri.Replace(' ', '+'), Headers = headers, FileName = filename, Timeout = timeout <= 0 ? DefaultTimeout : timeout, }; FetchSync(fetchParameters); return fetchParameters.NetworkResponse; } public void FetchSync(object param) { DisableConnectionReuseIfNecessary(); _dtMetric = DateTime.UtcNow; var fetchParameters = (DroidFetchParameters)param; var state = new DroidRequestState { AbsoluteUri = fetchParameters.Uri, FileName = fetchParameters.FileName, Downloaded = DateTime.UtcNow, Verb = "GET", }; var tokenSource2 = new CancellationTokenSource(); CancellationToken token = tokenSource2.Token; var t = Task.Factory.StartNew(() => { token.ThrowIfCancellationRequested(); var currThread = Thread.CurrentThread; using (token.Register(currThread.Abort)) { var url = new URL(fetchParameters.Uri); state.Connection = (HttpURLConnection)url.OpenConnection(); url.Dispose(); state.Connection.ConnectTimeout = fetchParameters.Timeout; state.Connection.ReadTimeout = fetchParameters.Timeout; if (fetchParameters.Headers != null && fetchParameters.Headers.Any()) { foreach (var key in fetchParameters.Headers.Keys) { state.Connection.SetRequestProperty(key, fetchParameters.Headers[key]); } } // End the Asynchronous response and get the actual response object state.Expiration = state.Connection.GetHeaderField("Expires").TryParseDateTimeUtc(); state.AttemptToRefresh = state.Connection.GetHeaderField("MonoCross-Attempt-Refresh").TryParseDateTimeUtc(); // apply web response headers to data collection. foreach (string key in state.Connection.HeaderFields.Keys.Where(k => k != null)) { state.Data[key] = state.Connection.GetHeaderField(key); } state.StatusCode = (HttpStatusCode)state.Connection.ResponseCode; switch (state.StatusCode) { case HttpStatusCode.OK: case HttpStatusCode.Created: case HttpStatusCode.Accepted: try { // extract response into bytes and string. byte[] bytes; var webResponse = new WebResponse { ResponseBytes = bytes = NetworkUtils.StreamToByteArray(state.Connection.InputStream), ResponseString = NetworkUtils.ByteArrayToStr(bytes), }; if (!string.IsNullOrEmpty(state.FileName)) Device.File.Save(state.FileName, bytes); state.ResponseBytes = bytes; state.ResponseString = webResponse.ResponseString; FetcherAsynch_OnDownloadComplete(state, fetchParameters.NetworkResponse); } catch (Exception ex) { string StatusDescription = string.Empty; ex.Data.Add("Uri", state.Connection.URL.ToString()); ex.Data.Add("Verb", state.Connection.RequestMethod); if (state.Connection != null) { state.StatusCode = (HttpStatusCode)state.Connection.ResponseCode; StatusDescription = state.Connection.ResponseMessage; } else { state.StatusCode = (HttpStatusCode)(-2); } if (string.IsNullOrEmpty(StatusDescription)) { ex.Data.Add("StatusDescription", StatusDescription); state.ErrorMessage = string.Format("Call to {0} had an Exception. {1}", state.Connection.URL, ex.Message); state.WebExceptionStatusCode = (WebExceptionStatus)(-1); } else { state.ErrorMessage = string.Format("Call to {0} had a web exception. {1} Desc: {2}", state.Connection.URL, ex.Message, StatusDescription); state.StatusCode = (HttpStatusCode)(-1); } ex.Data.Add("StatusCode", state.StatusCode); state.Exception = ex; state.Expiration = DateTime.UtcNow; state.AttemptToRefresh = DateTime.UtcNow; Device.Log.Error(state.ErrorMessage); Device.Log.Error(ex); FetcherAsynch_OnError(state, fetchParameters.NetworkResponse); } finally { //if (state.Response != null) // ((IDisposable)state.Response).Dispose(); state.Connection.Disconnect(); state.Connection = null; } break; case HttpStatusCode.NoContent: state.ErrorMessage = string.Format("No Content returned: Result {0} for {1}", state.StatusCode, state.AbsoluteUri); Device.Log.Warn(state.ErrorMessage); state.Expiration = DateTime.UtcNow; state.AttemptToRefresh = DateTime.UtcNow; state.Downloaded = DateTime.UtcNow; FetcherAsynch_OnDownloadComplete(state, fetchParameters.NetworkResponse); break; default: state.Expiration = DateTime.UtcNow; state.AttemptToRefresh = DateTime.UtcNow; state.Downloaded = DateTime.UtcNow; FetcherAsynch_OnError(state, fetchParameters.NetworkResponse); break; } } }, token); try { t.Wait(fetchParameters.Timeout + 5); } catch (Exception e) { state.Exception = e; state.Expiration = DateTime.UtcNow; state.AttemptToRefresh = DateTime.UtcNow; state.Downloaded = DateTime.UtcNow; FetcherAsynch_OnError(state, fetchParameters.NetworkResponse); } finally { if (state.Connection != null) { Task.Factory.StartNew(() => { state.Connection.Disconnect(); state.Connection = null; }); } } if (tokenSource2 != null && !t.IsCompleted) { tokenSource2.Cancel(); state.StatusCode = HttpStatusCode.RequestTimeout; state.Expiration = DateTime.UtcNow; state.AttemptToRefresh = DateTime.UtcNow; state.Downloaded = DateTime.UtcNow; FetcherAsynch_OnError(state, fetchParameters.NetworkResponse); } Device.Log.Metric(string.Format("FetchAsynch Completed: Uri: {0} Time: {1} milliseconds Size: {2} ", state.AbsoluteUri, DateTime.UtcNow.Subtract(_dtMetric).TotalMilliseconds, (fetchParameters.NetworkResponse.ResponseBytes != null ? fetchParameters.NetworkResponse.ResponseBytes.Length : -1))); } private void FetcherAsynch_OnError(DroidRequestState state, NetworkResponse postNetworkResponse) { string message; switch (state.StatusCode) { case HttpStatusCode.RequestTimeout: message = "FetcherAsynch call to FetchAsynch timed out. uri " + state.AbsoluteUri; Device.Log.Metric(string.Format("FetchAsynch timed out: Uri: {0} Time: {1} milliseconds ", state.AbsoluteUri, DateTime.UtcNow.Subtract(_dtMetric).TotalMilliseconds)); postNetworkResponse.URI = state.AbsoluteUri; postNetworkResponse.StatusCode = HttpStatusCode.RequestTimeout; postNetworkResponse.ResponseString = string.Empty; postNetworkResponse.Expiration = DateTime.MinValue.ToUniversalTime(); postNetworkResponse.AttemptToRefresh = DateTime.MinValue.ToUniversalTime(); state.WebExceptionStatusCode = WebExceptionStatus.Timeout; state.Downloaded = DateTime.UtcNow; break; default: message = "FetcherAsynch call to FetchAsynch threw an exception"; state.WebExceptionStatusCode = WebExceptionStatus.ProtocolError; postNetworkResponse.StatusCode = state.StatusCode; postNetworkResponse.Message = message; postNetworkResponse.ResponseString = null; postNetworkResponse.ResponseBytes = null; postNetworkResponse.Verb = state.Verb; break; } var exc = new Exception(message, state.Exception); Device.Log.Error(exc); postNetworkResponse.WebExceptionStatusCode = state.WebExceptionStatusCode; postNetworkResponse.Exception = exc; postNetworkResponse.Downloaded = state.Downloaded; Device.PostNetworkResponse(postNetworkResponse); } private void FetcherAsynch_OnDownloadComplete(DroidRequestState state, NetworkResponse postNetworkResponse) { postNetworkResponse.StatusCode = state.StatusCode; postNetworkResponse.WebExceptionStatusCode = state.WebExceptionStatusCode; postNetworkResponse.URI = state.AbsoluteUri; postNetworkResponse.Verb = state.Verb; postNetworkResponse.ResponseString = state.ResponseString; postNetworkResponse.ResponseBytes = state.ResponseBytes; postNetworkResponse.Expiration = state.Expiration; postNetworkResponse.Downloaded = state.Downloaded; postNetworkResponse.AttemptToRefresh = state.AttemptToRefresh; postNetworkResponse.Message = state.ErrorMessage; switch (postNetworkResponse.StatusCode) { case HttpStatusCode.OK: case HttpStatusCode.Created: case HttpStatusCode.Accepted: // things are ok, no event required break; case HttpStatusCode.NoContent: // return when an object is not found case HttpStatusCode.Unauthorized: // return when session expires case HttpStatusCode.InternalServerError: // return when an exception happens case HttpStatusCode.ServiceUnavailable: // return when the database or siteminder are unavailable postNetworkResponse.Message = string.Format("Network Service responded with status code {0}", state.StatusCode); Device.PostNetworkResponse(postNetworkResponse); break; default: postNetworkResponse.Message = string.Format("FetcherAsynch completed but received HTTP {0}", state.StatusCode); Device.Log.Error(postNetworkResponse.Message); Device.PostNetworkResponse(postNetworkResponse); return; } } /// <summary> /// Represents a collection of parameters for network fetch calls. /// </summary> public class DroidFetchParameters { /// <summary> /// Gets or sets the URI of the resource. /// </summary> public string Uri { get; set; } /// <summary> /// Gets or sets the headers added to the request. /// </summary> public IDictionary<string, string> Headers { get; set; } /// <summary> /// Gets or sets the file name of the resource. /// </summary> public string FileName { get; set; } /// <summary> /// Gets or sets the timeout value in milliseconds. /// </summary> public int Timeout { get; set; } /// <summary> /// Gets or sets the network response. /// </summary> public NetworkResponse NetworkResponse { get; set; } } } /// <summary> /// Represents the state of a network fetch request. /// </summary> public class DroidRequestState { /// <summary> /// Gets or sets the file name of the resource. /// </summary> public string FileName { get; set; } /// <summary> /// Gets or sets the web connection. /// </summary> public HttpURLConnection Connection { get; set; } /// <summary> /// Gets or sets the body of the response from the server as a <see cref="System.String"/>. /// </summary> public string ResponseString { get; set; } /// <summary> /// Gets or sets the body of the response from the server as an array of <see cref="System.Byte"/>s. /// </summary> public byte[] ResponseBytes { get; set; } /// <summary> /// Gets or sets the expiration date and time of the request. /// </summary> public DateTime Expiration { get; set; } /// <summary> /// Gets or sets the date and time that the content of the request was downloaded. /// </summary> public DateTime Downloaded { get; set; } /// <summary> /// Gets or sets the URI of the request. /// </summary> public string AbsoluteUri { get; set; } /// <summary> /// Gets or sets the HTTP verb for the request. /// </summary> public string Verb { get; set; } /// <summary> /// Gets or sets the status of the response. /// </summary> public HttpStatusCode StatusCode { get; set; } /// <summary> /// Gets or sets the status of the response when an exception has occurred during the request. /// </summary> public WebExceptionStatus WebExceptionStatusCode { get; set; } /// <summary> /// Gets or sets the exception that occurred during the request. /// </summary> public Exception Exception { get; set; } /// <summary> /// Gets or sets a message describing the error that occurred during the request. /// </summary> public string ErrorMessage { get; set; } /// <summary> /// Gets or sets the headers that are associated with the response. /// </summary> public Dictionary<string, string> Data { get; set; } /// <summary> /// Initializes a new instance of the <see cref="DroidRequestState"/> class. /// </summary> public DroidRequestState() { Connection = null; //Response = null; Data = new Dictionary<string, string>(); } /// <summary> /// Gets or sets the date and time of the last attempt to refresh. /// </summary> public DateTime AttemptToRefresh { get; set; } } }
using System.Threading; using Content.Server.Body.Components; using Content.Server.Body.Systems; using Content.Server.Chemistry.Components.SolutionManager; using Content.Server.Chemistry.EntitySystems; using Content.Server.DoAfter; using Content.Server.Fluids.EntitySystems; using Content.Server.Nutrition.Components; using Content.Server.Popups; using Content.Shared.ActionBlocker; using Content.Shared.Administration.Logs; using Content.Shared.Body.Components; using Content.Shared.Chemistry.Reagent; using Content.Shared.Database; using Content.Shared.Examine; using Content.Shared.FixedPoint; using Content.Shared.Interaction; using Content.Shared.Interaction.Helpers; using Content.Shared.Nutrition.Components; using Content.Shared.Throwing; using JetBrains.Annotations; using Robust.Shared.Audio; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Player; using Robust.Shared.Random; using Robust.Shared.Utility; namespace Content.Server.Nutrition.EntitySystems { [UsedImplicitly] public sealed class DrinkSystem : EntitySystem { [Dependency] private readonly FoodSystem _foodSystem = default!; [Dependency] private readonly IRobustRandom _random = default!; [Dependency] private readonly SolutionContainerSystem _solutionContainerSystem = default!; [Dependency] private readonly PopupSystem _popupSystem = default!; [Dependency] private readonly BodySystem _bodySystem = default!; [Dependency] private readonly StomachSystem _stomachSystem = default!; [Dependency] private readonly DoAfterSystem _doAfterSystem = default!; [Dependency] private readonly SharedAdminLogSystem _logSystem = default!; [Dependency] private readonly SpillableSystem _spillableSystem = default!; [Dependency] private readonly SharedInteractionSystem _interactionSystem = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<DrinkComponent, SolutionChangedEvent>(OnSolutionChange); SubscribeLocalEvent<DrinkComponent, ComponentInit>(OnDrinkInit); SubscribeLocalEvent<DrinkComponent, LandEvent>(HandleLand); SubscribeLocalEvent<DrinkComponent, UseInHandEvent>(OnUse); SubscribeLocalEvent<DrinkComponent, AfterInteractEvent>(AfterInteract); SubscribeLocalEvent<DrinkComponent, ExaminedEvent>(OnExamined); SubscribeLocalEvent<SharedBodyComponent, DrinkEvent>(OnDrink); SubscribeLocalEvent<DrinkCancelledEvent>(OnDrinkCancelled); } public bool IsEmpty(EntityUid uid, DrinkComponent? component = null) { if(!Resolve(uid, ref component)) return true; return _solutionContainerSystem.DrainAvailable(uid) <= 0; } private void OnExamined(EntityUid uid, DrinkComponent component, ExaminedEvent args) { if (!component.Opened || !args.IsInDetailsRange) return; var color = IsEmpty(uid, component) ? "gray" : "yellow"; var openedText = Loc.GetString(IsEmpty(uid, component) ? "drink-component-on-examine-is-empty" : "drink-component-on-examine-is-opened"); args.Message.AddMarkup($"\n{Loc.GetString("drink-component-on-examine-details-text", ("colorName", color), ("text", openedText))}"); } private void SetOpen(EntityUid uid, bool opened = false, DrinkComponent? component = null) { if(!Resolve(uid, ref component)) return; if (opened == component.Opened) return; component.Opened = opened; if (!_solutionContainerSystem.TryGetSolution(uid, component.SolutionName, out _)) return; if (EntityManager.TryGetComponent<AppearanceComponent>(uid, out var appearance)) { appearance.SetData(DrinkCanStateVisual.Opened, opened); } if (opened) { EntityManager.EnsureComponent<RefillableSolutionComponent>(uid).Solution= component.SolutionName; EntityManager.EnsureComponent<DrainableSolutionComponent>(uid).Solution= component.SolutionName; } else { EntityManager.RemoveComponent<RefillableSolutionComponent>(uid); EntityManager.RemoveComponent<DrainableSolutionComponent>(uid); } } private void AfterInteract(EntityUid uid, DrinkComponent component, AfterInteractEvent args) { if (args.Handled || args.Target == null || !args.CanReach) return; args.Handled = TryDrink(args.User, args.Target.Value, component); } private void OnUse(EntityUid uid, DrinkComponent component, UseInHandEvent args) { if (args.Handled) return; if (!component.Opened) { //Do the opening stuff like playing the sounds. SoundSystem.Play(Filter.Pvs(args.User), component.OpenSounds.GetSound(), args.User, AudioParams.Default); SetOpen(uid, true, component); return; } args.Handled = TryDrink(args.User, args.User, component); } private void HandleLand(EntityUid uid, DrinkComponent component, LandEvent args) { if (component.Pressurized && !component.Opened && _random.Prob(0.25f) && _solutionContainerSystem.TryGetDrainableSolution(uid, out var interactions)) { component.Opened = true; UpdateAppearance(component); var solution = _solutionContainerSystem.Drain(uid, interactions, interactions.DrainAvailable); _spillableSystem.SpillAt(uid, solution, "PuddleSmear"); SoundSystem.Play(Filter.Pvs(uid), component.BurstSound.GetSound(), uid, AudioParams.Default.WithVolume(-4)); } } private void OnDrinkInit(EntityUid uid, DrinkComponent component, ComponentInit args) { SetOpen(uid, component.DefaultToOpened, component); if (EntityManager.TryGetComponent(uid, out DrainableSolutionComponent? existingDrainable)) { // Beakers have Drink component but they should use the existing Drainable component.SolutionName = existingDrainable.Solution; } else { _solutionContainerSystem.EnsureSolution(uid, component.SolutionName); } UpdateAppearance(component); } private void OnSolutionChange(EntityUid uid, DrinkComponent component, SolutionChangedEvent args) { UpdateAppearance(component); } public void UpdateAppearance(DrinkComponent component) { if (!EntityManager.TryGetComponent((component).Owner, out AppearanceComponent? appearance) || !EntityManager.HasComponent<SolutionContainerManagerComponent>((component).Owner)) { return; } var drainAvailable = _solutionContainerSystem.DrainAvailable((component).Owner); appearance.SetData(FoodVisuals.Visual, drainAvailable.Float()); appearance.SetData(DrinkCanStateVisual.Opened, component.Opened); } private bool TryDrink(EntityUid user, EntityUid target, DrinkComponent drink) { // cannot stack do-afters if (drink.CancelToken != null) { drink.CancelToken.Cancel(); drink.CancelToken = null; return true; } if (!EntityManager.HasComponent<SharedBodyComponent>(target)) return false; if (!drink.Opened) { _popupSystem.PopupEntity(Loc.GetString("drink-component-try-use-drink-not-open", ("owner", EntityManager.GetComponent<MetaDataComponent>(drink.Owner).EntityName)), drink.Owner, Filter.Entities(user)); return true; } if (!_solutionContainerSystem.TryGetDrainableSolution(drink.Owner, out var drinkSolution) || drinkSolution.DrainAvailable <= 0) { _popupSystem.PopupEntity(Loc.GetString("drink-component-try-use-drink-is-empty", ("entity", EntityManager.GetComponent<MetaDataComponent>(drink.Owner).EntityName)), drink.Owner, Filter.Entities(user)); return true; } if (_foodSystem.IsMouthBlocked(target, user)) return true; if (!_interactionSystem.InRangeUnobstructed(user, drink.Owner, popup: true)) return true; var forceDrink = user != target; if (forceDrink) { EntityManager.TryGetComponent(user, out MetaDataComponent? meta); var userName = meta?.EntityName ?? string.Empty; _popupSystem.PopupEntity(Loc.GetString("drink-component-force-feed", ("user", userName)), user, Filter.Entities(target)); // logging _logSystem.Add(LogType.ForceFeed, LogImpact.Medium, $"{ToPrettyString(user):user} is forcing {ToPrettyString(target):target} to drink {ToPrettyString(drink.Owner):drink} {SolutionContainerSystem.ToPrettyString(drinkSolution)}"); } drink.CancelToken = new CancellationTokenSource(); _doAfterSystem.DoAfter(new DoAfterEventArgs(user, forceDrink ? drink.ForceFeedDelay : drink.Delay, drink.CancelToken.Token, target) { BreakOnUserMove = true, BreakOnDamage = true, BreakOnStun = true, BreakOnTargetMove = true, MovementThreshold = 0.01f, TargetFinishedEvent = new DrinkEvent(user, drink, drinkSolution), BroadcastCancelledEvent = new DrinkCancelledEvent(drink), NeedHand = true, }); return true; } /// <summary> /// Raised directed at a victim when someone has force fed them a drink. /// </summary> private void OnDrink(EntityUid uid, SharedBodyComponent body, DrinkEvent args) { if (args.Drink.Deleted) return; args.Drink.CancelToken = null; var transferAmount = FixedPoint2.Min(args.Drink.TransferAmount, args.DrinkSolution.DrainAvailable); var drained = _solutionContainerSystem.Drain(args.Drink.Owner, args.DrinkSolution, transferAmount); var forceDrink = uid != args.User; if (!_bodySystem.TryGetComponentsOnMechanisms<StomachComponent>(uid, out var stomachs, body)) { _popupSystem.PopupEntity( forceDrink ? Loc.GetString("drink-component-try-use-drink-cannot-drink-other") : Loc.GetString("drink-component-try-use-drink-had-enough"), uid, Filter.Entities(args.User)); if (EntityManager.HasComponent<RefillableSolutionComponent>(uid)) { _spillableSystem.SpillAt(args.User, drained, "PuddleSmear"); return; } _solutionContainerSystem.Refill(uid, args.DrinkSolution, drained); return; } var firstStomach = stomachs.FirstOrNull( stomach => _stomachSystem.CanTransferSolution((stomach.Comp).Owner, drained)); // All stomach are full or can't handle whatever solution we have. if (firstStomach == null) { _popupSystem.PopupEntity(Loc.GetString("drink-component-try-use-drink-had-enough-other"), uid, Filter.Entities(args.User)); _spillableSystem.SpillAt(uid, drained, "PuddleSmear"); return; } if (forceDrink) { EntityManager.TryGetComponent(uid, out MetaDataComponent? targetMeta); var targetName = targetMeta?.EntityName ?? string.Empty; EntityManager.TryGetComponent(args.User, out MetaDataComponent? userMeta); var userName = userMeta?.EntityName ?? string.Empty; _popupSystem.PopupEntity( Loc.GetString("drink-component-force-feed-success", ("user", userName)), uid, Filter.Entities(uid)); _popupSystem.PopupEntity( Loc.GetString("drink-component-force-feed-success-user", ("target", targetName)), args.User, Filter.Entities(args.User)); } else { _popupSystem.PopupEntity( Loc.GetString("drink-component-try-use-drink-success-slurp"), args.User, Filter.Pvs(args.User)); } SoundSystem.Play(Filter.Pvs(uid), args.Drink.UseSound.GetSound(), uid, AudioParams.Default.WithVolume(-2f)); drained.DoEntityReaction(uid, ReactionMethod.Ingestion); _stomachSystem.TryTransferSolution(firstStomach.Value.Comp.Owner, drained, firstStomach.Value.Comp); } private static void OnDrinkCancelled(DrinkCancelledEvent args) { args.Drink.CancelToken = null; } } }
namespace FSSHTTPandWOPIInspector.Parsers { using System.Xml.Serialization; using System.Xml; using System.Xml.Schema; using System.ComponentModel; using System; using System.Collections.Generic; using System.Collections.ObjectModel; /// <summary> /// Envelope message for request, defined in section 2.2.2.1 /// </summary> [XmlRoot("Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")] public class RequestEnvelope { public RequestEnvelopeBody Body { get; set; } } /// <summary> /// Envelope body for request, defined in section 2.2.2.1 /// </summary> [XmlRoot("Body")] public class RequestEnvelopeBody { [XmlElementAttribute("RequestVersion", Namespace = "http://schemas.microsoft.com/sharepoint/soap/")] public VersionType RequestVersion { get; set; } [XmlElementAttribute("RequestCollection", Namespace = "http://schemas.microsoft.com/sharepoint/soap/")] public RequestCollection RequestCollection { get; set; } } /// <summary> /// Request collection type defined in section 2.2.3.3 /// </summary> public class RequestCollection { [XmlElement()] public Request[] Request { get; set; } [XmlAttribute()] public string CorrelationId { get; set; } } /// <summary> /// Request element that is part of a cell storage service request, defined in section 2.2.3.2 /// </summary> public class Request { [XmlElementAttribute()] GenericPropertiesType GenericProperties { get; set; } [XmlElementAttribute()] public SubRequestElementGenericType[] SubRequest { get; set; } [XmlAttribute()] public string Url { get; set; } [XmlAttribute(DataType = "nonNegativeInteger")] public string Interval { get; set; } [XmlAttribute(DataType = "integer")] public string MetaData { get; set; } [XmlAttribute(DataType = "nonNegativeInteger")] public string RequestToken { get; set; } [XmlAttribute()] public string UserAgent { get; set; } [XmlAttribute()] public string UserAgentClient { get; set; } [XmlAttribute()] public string UserAgentPlatform { get; set; } [XmlAttribute()] public string Build { get; set; } [XmlAttribute()] public string ParentFolderResourceID { get; set; } [XmlAttribute()] public bool ShouldReturnDisambiguatedFileName { get; set; } [XmlIgnore] public bool ShouldReturnDisambiguatedFileNameSpecified { get; set; } [XmlAttribute()] public string ResourceID { get; set; } [XmlAttribute()] public string UseResourceID { get; set; } } /// <summary> /// Subrequest type, defined in section 2.2.4.5 /// </summary> public class SubRequestType { [XmlAttribute(DataType = "nonNegativeInteger")] public string SubRequestToken { get; set; } [XmlAttribute(DataType = "nonNegativeInteger")] public string DependsOn { get; set; } [XmlAttribute()] public DependencyTypes DependencyType { get; set; } } /// <summary> /// A generic subrequest type, defined in section 2.2.4.4 /// </summary> public class SubRequestElementGenericType : SubRequestType { public SubRequestDataGenericType SubRequestData { get; set; } [XmlTextAttribute()] public string[] Text { get; set; } [XmlAttribute()] public SubRequestAttributeType Type { get; set; } } /// <summary> /// A generic subrequest data type, defined in section 2.2.4.3 /// </summary> public class SubRequestDataGenericType { #region 2.3.1.1 CellSubRequestDataType [XmlElement(Namespace = "http://www.w3.org/2004/08/xop/include")] public Include Include { get; set; } [XmlElementAttribute()] public object IncludeObject { get; set; } #endregion [XmlElementAttribute()] public PropertyIdsType PropertyIds { get; set; } [XmlTextAttribute()] public string[] Text { get; set; } [XmlElementAttribute()] public object TextObject { get; set; } #region 2.2.8.1 SubRequestDataOptionalAttributes [XmlAttribute()] public string ClientID { get; set; } [XmlAttribute()] public bool ReleaseLockOnConversionToExclusiveFailure { get; set; } [XmlIgnore] public bool ReleaseLockOnConversionToExclusiveFailureSpecified { get; set; } [XmlAttribute()] public string SchemaLockID { get; set; } [XmlAttribute(DataType = "integer")] public string Timeout { get; set; } [XmlAttribute()] public string AllowFallbackToExclusive { get; set; } [XmlIgnore] public bool AllowFallbackToExclusiveSpecified { get; set; } [XmlAttribute()] public string ExclusiveLockID { get; set; } [XmlAttribute()] public long BinaryDataSize { get; set; } [XmlAttribute()] public bool AsEditor { get; set; } [XmlIgnore] public bool AsEditorSpecified { get; set; } [XmlAttribute()] public string Key { get; set; } [XmlAttribute()] public string Value { get; set; } [XmlAttribute()] public string NewFileName { get; set; } [XmlAttribute()] public string Version { get; set; } //FileVersionNumberType #endregion #region 2.3.3.1 CellSubRequestDataOptionalAttributes [XmlAttribute] public bool Coalesce { get; set; } [XmlIgnore] public bool CoalesceSpecified { get; set; } [XmlAttribute()] public bool GetFileProps { get; set; } [XmlIgnore()] public bool GetFilePropsSpecified { get; set; } [XmlAttribute()] public bool CoauthVersioning { get; set; } [XmlIgnoreAttribute()] public bool CoauthVersioningSpecified { get; set; } [XmlAttribute()] public string Etag { get; set; } [XmlAttribute()] public string ContentChangeUnit { get; set; } [XmlAttribute()] public string ClientFileID { get; set; } [XmlAttribute()] public string PartitionID { get; set; } [XmlAttribute()] public bool ExpectNoFileExists { get; set; } [XmlIgnoreAttribute()] public bool ExpectNoFileExistsSpecified { get; set; } [XmlAttribute()] public string BypassLockID { get; set; } [XmlAttribute(DataType = "integer")] public string LastModifiedTime { get; set; } #endregion #region 2.3.3.3 CoauthSubRequestDataOptionalAttributes [XmlAttribute()] public CoauthRequestTypes CoauthRequestType { get; set; } [XmlIgnoreAttribute()] public bool CoauthRequestTypeSpecified { get; set; } #endregion #region 2.3.3.5 SchemaLockSubRequestDataOptionalAttributes [XmlAttribute()] public SchemaLockRequestTypes SchemaLockRequestType { get; set; } [XmlIgnoreAttribute()] public bool SchemaLockRequestTypeSpecified { get; set; } #endregion #region 2.3.3.4 ExclusiveLockSubRequestDataOptionalAttributes [XmlAttribute()] public ExclusiveLockRequestTypes ExclusiveLockRequestType { get; set; } [XmlIgnoreAttribute()] public bool ExclusiveLockRequestTypeSpecified { get; set; } #endregion #region 2.3.3.7 EditorsTableSubRequestDataOptionalAttributes [XmlAttribute()] public EditorsTableRequestTypes EditorsTableRequestType { get; set; } [XmlIgnoreAttribute()] public bool EditorsTableRequestTypeSpecified { get; set; } #endregion #region 2.3.3.8 FileOperationSubRequestDataOptionalAttributes [XmlAttribute()] public FileOperationRequestTypes FileOperation { get; set; } [XmlIgnoreAttribute()] public bool FileOperationSpecified { get; set; } #endregion #region 2.3.3.9 VersioningSubRequestDataOptionalAttributes [XmlAttribute()] public VersioningRequestTypes VersioningRequestType { get; set; } [XmlIgnoreAttribute()] public bool VersioningRequestTypeSpecified { get; set; } #endregion #region 2.3.3.10 PropertiesSubRequestDataOptionalAttributes [XmlAttribute()] public PropertiesRequestTypes Properties { get; set; } [XmlIgnoreAttribute()] public bool PropertiesSpecified { get; set; } #endregion #region 2.3.1.45 AmIAloneSubRequestDataType [XmlAttribute()] public string TransitionID { get; set; } #endregion } /// <summary> /// A GenericPropertiesType, defined in section 2.2.4.1 /// </summary> public class GenericPropertiesType { public PropertyType[] Property { get; set; } } /// <summary> /// PropertyType, defined in section 2.2.4.2 /// </summary> public class PropertyType { [XmlAttribute()] public ushort Id { get; set; } [XmlAttribute()] public ushort Value { get; set; } } /// <summary> /// XOP10 section 2.1 /// </summary> public class Include { [XmlAnyElement()] public System.Xml.XmlElement[] Any { get; set; } [XmlAttribute(DataType = "anyURI")] public string href { get; set; } [XmlAnyAttribute()] public System.Xml.XmlAttribute[] AnyAttr { get; set; } } /// <summary> /// The VersionType complex type contains information about the version of the cell storage service message. /// Defined in section 2.2.4.9 /// </summary> public class VersionType { [XmlAttributeAttribute("Version")] public ushort Version { get; set; } [XmlAttributeAttribute("MinorVersion")] public ushort MinorVersion { get; set; } } /// <summary> /// The ResponseVersion element contains version-specific information for this cell storage service response message. /// Defined in section 2.2.3.7 /// </summary> public class ResponseVersion : VersionType { [XmlAttribute] public GenericErrorCodeTypes ErrorCode { get; set; } [XmlAttribute] public string ErrorMessage { get; set; } [XmlIgnore] public bool ErrorCodeSpecified { get; set; } } /// <summary> /// The GenericErrorCodeTypes simple type is used to represent generic error code types that occur during cell storage service subrequest processing. /// Defined in section 2.2.5.6 /// </summary> public enum GenericErrorCodeTypes { Success, IncompatibleVersion, InvalidUrl, FileNotExistsOrCannotBeCreated, FileUnauthorizedAccess, PathNotFound, ResourceIdDoesNotExist, ResourceIdDoesNotMatch, InvalidSubRequest, SubRequestFail, BlockedFileType, DocumentCheckoutRequired, InvalidArgument, RequestNotSupported, InvalidWebUrl, WebServiceTurnedOff, ColdStoreConcurrencyViolation, HighLevelExceptionThrown, Unknown, } /// <summary> /// Envelope message for response, defined in section 2.2.2.2 /// </summary> [XmlRoot("Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")] public class ResponseEnvelope { public ResponseEnvelopeBody Body { get; set; } } /// <summary> /// Envelope body for response, defined in section 2.2.2.2 /// </summary> [XmlRoot("Body")] public class ResponseEnvelopeBody { [XmlElementAttribute("ResponseVersion", Namespace = "http://schemas.microsoft.com/sharepoint/soap/")] public ResponseVersion ResponseVersion { get; set; } [XmlElementAttribute("ResponseCollection", Namespace = "http://schemas.microsoft.com/sharepoint/soap/")] public ResponseCollection ResponseCollection { get; set; } } /// <summary> /// Response collection type defined in section 2.2.3.6 /// </summary> public class ResponseCollection { [XmlElement()] public Response[] Response { get; set; } [XmlAttribute()] public string WebUrl { get; set; } [XmlAttribute()] public string WebUrlIsEncoded { get; set; } } /// <summary> /// Response element that is part of a cell storage service response, defined in section 2.2.3.5 /// </summary> public class Response { [XmlElement()] public SubResponseElementGenericType[] SubResponse { get; set; } [XmlTextAttribute()] public string[] Text { get; set; } [XmlAttribute()] public string Url { get; set; } [XmlAttribute()] public string UrlIsEncoded { get; set; } [XmlAttribute(DataType = "nonNegativeInteger")] public string RequestToken { get; set; } [XmlAttribute(DataType = "integer")] public string HealthScore { get; set; } [XmlAttribute()] public GenericErrorCodeTypes ErrorCode { get; set; } [XmlIgnore()] public bool ErrorCodeSpecified { get; set; } [XmlAttribute()] public string ErrorMessage { get; set; } [XmlAttribute()] public string SuggestedFileName { get; set; } [XmlAttribute()] public string ResourceID { get; set; } [XmlAttribute(DataType = "nonNegativeInteger")] public string IntervalOverride { get; set; } } /// <summary> /// Subresponse type, defined in section 2.2.4.8 /// </summary> public class SubResponseType { [XmlAttribute(DataType = "nonNegativeInteger")] public string SubRequestToken { get; set; } [XmlAttribute()] public string ServerCorrelationId { get; set; } [XmlAttribute()] public string ErrorCode { get; set; } [XmlAttribute(DataType = "integer")] public string HResult { get; set; } [XmlAttribute()] public string ErrorMessage { get; set; } } /// <summary> /// A generic subresponse type, defined in section 2.2.4.7 /// </summary> public class SubResponseElementGenericType : SubResponseType { public SubResponseDataGenericType SubResponseData { get; set; } public object SubResponseStreamInvalid { get; set; } public GetVersionsResponseType GetVersionsResponse { get; set; } } /// <summary> /// A generic subresponse data type, defined in section 2.2.4.6 /// </summary> public class SubResponseDataGenericType { #region 2.3.1.27 GetDocMetaInfoSubResponseDataType [XmlElementAttribute()] public GetDocMetaInfoPropertySetType DocProps { get; set; } [XmlElementAttribute()] public GetDocMetaInfoPropertySetType FolderProps { get; set; } #endregion [XmlElementAttribute()] public VersioningUserTableType UserTable { get; set; } [XmlElementAttribute()] public VersioningVersionListType Versions { get; set; } [XmlElementAttribute()] public PropertyIdsType PropertyIds { get; set; } [XmlElementAttribute()] public PropertyValuesType PropertyValues {get;set;} [XmlTextAttribute()] public string[] Text { get; set; } [XmlElementAttribute()] public object TextObject { get; set; } #region 2.3.1.3 CellSubResponseDataType [XmlElement(Namespace = "http://www.w3.org/2004/08/xop/include")] public Include Include { get; set; } [XmlElementAttribute()] public object IncludeObject { get; set; } #region 2.3.3.2 CellSubResponseDataOptionalAttributes [XmlAttribute()] public string Etag { get; set; } [XmlAttribute(DataType = "integer")] public string CreateTime { get; set; } [XmlAttribute(DataType = "integer")] public string LastModifiedTime { get; set; } [XmlAttribute(DataType = "NCName")] public string ModifiedBy { get; set; } [XmlAttribute()] public string CoalesceErrorMessage { get; set; } [XmlAttribute(DataType = "integer")] public string CoalesceHResult { get; set; } [XmlAttribute()] public string ContainsHotboxData { get; set; } [XmlAttribute()] public string HaveOnlyDemotionChanges { get; set; } #endregion #endregion #region 2.3.1.21 WhoAmISubResponseDataType #region 2.3.3.6 WhoAmISubResponseDataOptionalAttributes [XmlAttribute(DataType = "NCName")] public string UserName { get; set; } [XmlAttribute()] public string UserEmailAddress { get; set; } [XmlAttribute()] public string UserSIPAddress { get; set; } [XmlAttribute()] public bool UserIsAnonymous { get; set; } [XmlIgnore()] public bool UserIsAnonymousSpecified { get; set; } [XmlAttribute()] public string UserLogin { get; set; } #endregion #endregion #region 2.3.1.18 ServerTimeSubResponseDataType [XmlAttribute(DataType = "positiveInteger")] public string ServerTime { get; set; } #endregion #region 2.3.1.50 LockStatusSubResponseDataType [XmlAttribute()] public string LockType; [XmlIgnore()] public bool LockTypeSpecified { get; set; } #endregion #region 2.3.1.7 CoauthSubResponseDataType #region 2.3.1.11 ExclusiveLockSubResponseDataType [XmlAttribute()] public CoauthStatusType CoauthStatus { get; set; } [XmlIgnore()] public bool CoauthStatusSpecified { get; set; } [XmlAttribute()] public string TransitionID { get; set; } #endregion [XmlAttribute()] public ExclusiveLockReturnReasonTypes ExclusiveLockReturnReason { get; set; } [XmlIgnore()] public bool ExclusiveLockReturnReasonSpecified { get; set; } #endregion #region 2.2.8.2 SubResponseDataOptionalAttributes #region 2.3.1.47 AmIAloneSubResponseDataType [XmlAttribute()] public string AmIAlone{ get; set; } #endregion [XmlAttribute()] public string LockID { get; set; } [XmlAttribute()] public string LockedBy { get; set; } #endregion } /// <summary> /// The GetDocMetaInfoPropertySetType complex type contains a sequence of Property elements to describe the set of metainfo related to the file. /// Defined in section 2.3.1.28 /// </summary> public class GetDocMetaInfoPropertySetType { [XmlElement()] public GetDocMetaInfoPropertyType[] Property { get; set; } } /// <summary> /// The GetDocMetaInfoProperty complex type contains a metainfo key/value pair that is related either to the file against which /// the request is made or its parent directory as part of the corresponding GetDocMetaInfo subrequest. Defined in 2.3.1.29 /// </summary> public class GetDocMetaInfoPropertyType { [XmlAttribute()] public string Key { get; set; } [XmlAttribute()] public string Value { get; set; } } /// <summary> /// VersioningUserTableType section 2.3.1.40 /// </summary> public class VersioningUserTableType { [XmlElementAttribute()] public UserDataType[] User { get; set; } } /// <summary> /// VersioningVersionListType 2.3.1.41 /// </summary> public class VersioningVersionListType { [XmlElementAttribute()] public FileVersionDataType[] Version { get; set; } } /// <summary> /// UserDataType 2.3.1.42 /// </summary> public class UserDataType { [XmlAttribute(DataType = "integer")] public string UserId { get; set; } [XmlAttribute()] public string UserLogin { get; set; } [XmlAttribute()] public string UserName { get; set; } [XmlAttribute()] public string UserEmailAddress { get; set; } } /// <summary> /// FileVersionDataType 2.3.1.43 /// </summary> public class FileVersionDataType { [XmlAttribute()] public string IsCurrent { get; set; } [XmlAttribute()] public string Number { get; set; } [XmlAttribute()] public string LastModifiedTime { get; set; } [XmlAttribute()] public string UserId { get; set; } [XmlElementAttribute()] public EventType Events { get; set; } } /// <summary> /// EventType subelement type defined in 2.3.1.43 /// </summary> public class EventType { [XmlElementAttribute()] public FileVersionEventDataType[] Event { get; set; } } /// <summary> /// FileVersionEventDataType 2.3.1.44 /// </summary> public class FileVersionEventDataType { [XmlAttribute()] public string Id { get; set; } [XmlAttribute()] public string Type { get; set; } [XmlAttribute()] public string CreateTime { get; set; } [XmlAttribute()] public string UserId { get; set; } } /// <summary> /// PropertyIdsType 2.3.1.56 /// </summary> public class PropertyIdsType { [XmlElementAttribute()] public PropertyIdType[] PropertyId { get; set; } } /// <summary> /// PropertyIdType 2.3.1.57 /// </summary> public class PropertyIdType { [XmlAttribute()] public string id { get; set; } } /// <summary> /// PropertyValuesType defined in 2.3.1.58 /// </summary> public class PropertyValuesType { [XmlElementAttribute()] public PropertyValueType[] PropertyValue { get; set; } } /// <summary> /// PropertyValueType defined in 2.3.1.59 /// </summary> public class PropertyValueType { [XmlAttribute()] public string id { get; set; } [XmlAttribute()] public string value { get; set; } } /// <summary> /// The LockTypes simple type is used to represent the type of file lock. Defined in 2.2.5.9 /// </summary> public enum LockTypes { None, SchemaLock, ExclusiveLock, } /// <summary> /// The CoauthStatusType simple type is used to represent the coauthoring status of a targeted URL for the file. Defined in 2.2.5.1 /// </summary> public enum CoauthStatusType { None, Alone, Coauthoring, } /// <summary> /// The ExclusiveLockReturnReasonTypes simple type is used to represent string values that indicate the reason why /// an exclusive lock is granted on a file in a cell storage service response message. Defined in 2.2.5.5 /// </summary> public enum ExclusiveLockReturnReasonTypes { CoauthoringDisabled, CheckedOutByCurrentUser, CurrentUserHasExclusiveLock, } /// <summary> /// GetVersionsSubResponseType defined in section 2.3.1.32 /// </summary> public class GetVersionsSubResponseType : SubResponseType { public GetVersionsResponseType GetVersionsResponse { get; set; } } /// <summary> /// GetVersionsResponseType defined in MS-VERSS section 3.1.4.3.2.2 /// </summary> public class GetVersionsResponseType { public GetVersionsResult GetVersionsResult { get; set; } } /// <summary> /// GetVersionsResult defined in MS-VERSS section 3.1.4.3.2.2 /// </summary> public class GetVersionsResult { public Results results { get; set; } } /// <summary> /// The Result complex type, defined in MS-VERSS section 2.2.4.1 /// </summary> public class Results { public ResultsList list { get; set; } public ResultsVersioning versioning { get; set; } public ResultsSettings settings { get; set; } [XmlElement()] public VersionData[] result { get; set; } } /// <summary> /// The ResultsList type, defined in MS-VERSS section 2.2.4.1 /// </summary> public class ResultsList { [XmlAttribute()] public string id { get; set; } } /// <summary> /// The ResultsVersioning type, defined in MS-VERSS section 2.2.4.1 /// </summary> public class ResultsVersioning { [XmlAttribute()] public byte enabled { get; set; } } /// <summary> /// The ResultsSettings type, defined in MS-VERSS section 2.2.4.1 /// </summary> public class ResultsSettings { [XmlAttribute()] public string url { get; set; } } /// <summary> /// The VersionData type, defined in MS-VERSS section 2.2.4.1 /// </summary> public class VersionData { [XmlAttribute()] public string version { get; set; } [XmlAttribute()] public string url { get; set; } [XmlAttribute()] public string created { get; set; } [XmlAttribute()] public string createdRaw { get; set; } [XmlAttribute()] public string createdBy { get; set; } [XmlAttribute()] public string createdByName { get; set; } [XmlAttribute()] public ulong size { get; set; } [XmlAttribute()] public string comments { get; set; } } /// <summary> /// The CoauthRequestTypes is used to represent the type of coauthoring subrequest. Defined in 2.3.2.2 /// </summary> public enum CoauthRequestTypes { JoinCoauthoring, ExitCoauthoring, RefreshCoauthoring, ConvertToExclusive, CheckLockAvailability, MarkTransitionComplete, GetCoauthoringStatus, } /// <summary> /// The ExclusiveLockRequestTypes is used to represent the type of exclusive lock subrequest. Define in 2.3.2.3 /// </summary> public enum ExclusiveLockRequestTypes { GetLock, ReleaseLock, RefreshLock, ConvertToSchemaJoinCoauth, ConvertToSchema, CheckLockAvailability, } /// <summary> /// The SchemaLockRequestTypes is used to represent the type of schema lock subrequest. Defined in 2.3.2.4 /// </summary> public enum SchemaLockRequestTypes { GetLock, ReleaseLock, RefreshLock, ConvertToExclusive, CheckLockAvailability, } /// <summary> /// The EditorsTableRequestType is used to represent the type of editors table subrequest. Defined in 2.3.2.5 /// </summary> public enum EditorsTableRequestTypes { JoinEditingSession, LeaveEditingSession, RefreshEditingSession, UpdateEditorMetadata, RemoveEditorMetadata, } /// <summary> /// The FileOperationRequestTypes is used to represent the type of file operation subrequest. Defined in 2.3.2.8 /// </summary> public enum FileOperationRequestTypes { Rename, } /// <summary> /// The VersioningRequestTypes is used to represent the type of Versioning subrequest. Defined in 2.3.2.9 /// </summary> public enum VersioningRequestTypes { GetVersionList, RestoreVersion, } /// <summary> /// The PropertiesRequestTypes simple type is used to represent the type of Properties subrequest. Defined in 2.3.2.10 /// </summary> public enum PropertiesRequestTypes { PropertyEnumerate, PropertyGet, } /// <summary> /// Represent the type of cell storage service subrequest.Defined in 2.2.5.11 /// </summary> public enum SubRequestAttributeType { Cell, Coauth, SchemaLock, WhoAmI, ServerTime, ExclusiveLock, GetDocMetaInfo, GetVersions, EditorsTable, AmIAlone, LockStatus, FileOperation, Versioning, Properties, } /// <summary> /// Represent the type of dependency that a cell storage service subrequest has on another cell storage service subrequest. Defined in 2.2.5.3 /// </summary> public enum DependencyTypes { OnExecute, OnSuccess, OnFail, OnNotSupported, OnSuccessOrNotSupported, Invalid, //MSFSSHTTP2010 #531 } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace AnimatGuiCtrls.Controls { #region DataGridTextBoxColumn //********************************************************************************************** // DataGridTextBoxColumn //********************************************************************************************** public class DataGridComboBoxColumn : DataGridColumnStyle { //DataGridTextBoxColumn { private DataGridComboBox combobox; private bool edit; //------------------------------------------------------------------------------------------- // Constructors and destructors //------------------------------------------------------------------------------------------- public DataGridComboBoxColumn() { combobox = new DataGridComboBox(); combobox.Visible = false; combobox.DropDownStyle = ComboBoxStyle.DropDownList; combobox.Leave += new EventHandler(ComboHide); combobox.SelectionChangeCommitted += new EventHandler(ComboStartEditing); edit = false; } // DataGridComboBoxColumn //------------------------------------------------------------------------------------------- // Properties //------------------------------------------------------------------------------------------- public ComboBox comboBox { get { return combobox; } } // comboBox //------------------------------------------------------------------------------------------- // ComboBox event handlers //------------------------------------------------------------------------------------------- private void ComboHide(object sender, EventArgs e) { // When the ComboBox looses focus, then simply hide it. combobox.Hide(); } // ComboHide private void ComboStartEditing(object sender, EventArgs e) { // Enter edit mode. edit = true; base.ColumnStartedEditing((Control)sender); } // ComboStartEditing //------------------------------------------------------------------------------------------- // Override DataGridColumnStyle //------------------------------------------------------------------------------------------- protected override void SetDataGridInColumn(DataGrid value) { // Add the ComboBox to the DataGrids controls collection. // This ensures correct DataGrid scrolling. value.Controls.Add(combobox); base.SetDataGridInColumn(value); } // SetDataGridInColumn protected override void Abort(int rowNum) { // Abort edit mode, discard changes and hide the ComboBox. edit = false; Invalidate(); combobox.Hide(); } // Abort protected override void Edit(System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Rectangle bounds, bool readOnly, string instantText, bool cellIsVisible) { // Setup the ComboBox for action. // This includes positioning the ComboBox and showing it. // Also select the correct item in the ComboBox before it is shown. combobox.Parent = this.DataGridTableStyle.DataGrid; combobox.Bounds = bounds; combobox.Size = new Size(this.Width, this.comboBox.Height); comboBox.SelectedValue = base.GetColumnValueAtRow(source, rowNum).ToString(); combobox.Visible = (cellIsVisible == true) && (readOnly == false); combobox.BringToFront(); combobox.Focus(); } // Edit protected override bool Commit(System.Windows.Forms.CurrencyManager source, int rowNum) { // Commit the selected value from the ComboBox to the DataGrid. if (edit == true) { edit = false; this.SetColumnValueAtRow(source, rowNum, combobox.SelectedValue); } return true; } // Commit protected override object GetColumnValueAtRow(System.Windows.Forms.CurrencyManager source, int rowNum) { // Return the display text associated with the data, insted of the // data from the DataGrid datasource. return combobox.GetDisplayText(base.GetColumnValueAtRow(source, rowNum)); } // GetColumnValueAtRow protected override void SetColumnValueAtRow(CurrencyManager source, int rowNum, object value) { // Save the data (value) to the DataGrid datasource. // I try a few different types, because I often uses GUIDs as keys in my // data. // String. try { base.SetColumnValueAtRow(source, rowNum, value.ToString()); return; } catch {} // Guid. try { base.SetColumnValueAtRow(source, rowNum, new Guid(value.ToString())); return; } catch {} // Object (default). base.SetColumnValueAtRow(source, rowNum, value); } // SetColumnValueAtRow protected override int GetMinimumHeight() { // Return the ComboBox preferred height, plus a few pixels. return combobox.PreferredHeight + 2; } // GetMinimumHeight protected override int GetPreferredHeight(Graphics g, object val) { // Return the font height, plus a few pixels. return FontHeight + 2; } // GetPreferredHeight protected override Size GetPreferredSize(Graphics g, object val) { // Return the preferred width. // Iterate through all display texts in the dropdown, and measure each // text width. int widest = 0; SizeF stringSize = new SizeF(0, 0); foreach (string text in combobox.GetDisplayText()) { stringSize = g.MeasureString(text, base.DataGridTableStyle.DataGrid.Font); if (stringSize.Width > widest) { widest = (int)Math.Ceiling(stringSize.Width); } } return new Size(widest + 25, combobox.PreferredHeight + 2); } // GetPreferredSize protected override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum) { Paint(g, bounds, source, rowNum, false); } // Paint protected override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, bool alignToRight) { string text = GetColumnValueAtRow(source, rowNum).ToString(); Brush backBrush = new SolidBrush(base.DataGridTableStyle.BackColor); Brush foreBrush = new SolidBrush(base.DataGridTableStyle.ForeColor); Rectangle rect = bounds; StringFormat format = new StringFormat(); // Handle that the row can be selected. if (base.DataGridTableStyle.DataGrid.IsSelected(rowNum) == true) { backBrush = new SolidBrush(base.DataGridTableStyle.SelectionBackColor); foreBrush = new SolidBrush(base.DataGridTableStyle.SelectionForeColor); } // Handle align to right. if (alignToRight == true) { format.FormatFlags = StringFormatFlags.DirectionRightToLeft; } // Handle alignment. switch (this.Alignment) { case HorizontalAlignment.Left: format.Alignment = StringAlignment.Near; break; case HorizontalAlignment.Right: format.Alignment = StringAlignment.Far; break; case HorizontalAlignment.Center: format.Alignment = StringAlignment.Center; break; } // Paint. format.FormatFlags = StringFormatFlags.NoWrap; g.FillRectangle(backBrush, rect); rect.Offset(0, 2); rect.Height -= 2; g.DrawString(text, this.DataGridTableStyle.DataGrid.Font, foreBrush, rect, format); format.Dispose(); } // PaintText } // DataGridComboBoxColumn #endregion #region DataGridComboBox //********************************************************************************************** // DataGridComboBox //********************************************************************************************** public class DataGridComboBox : ComboBox { private const int WM_KEYUP = 0x101; protected override void WndProc(ref System.Windows.Forms.Message message) { // Ignore keyup to avoid problem with tabbing and dropdown list. if (message.Msg == WM_KEYUP) { return; } base.WndProc(ref message); } // WndProc public string GetValueText(int index) { // Validate the index. if ((index < 0) && (index >= base.Items.Count)) throw new IndexOutOfRangeException("Invalid index."); // Get the text. string text = string.Empty; int memIndex = -1; try { base.BeginUpdate(); memIndex = base.SelectedIndex; base.SelectedIndex = index; text = base.SelectedValue.ToString(); base.SelectedIndex = memIndex; } catch { } finally { base.EndUpdate(); } return text; } // GetValueText public string GetDisplayText(int index) { // Validate the index. if ((index < 0) && (index >= base.Items.Count)) throw new IndexOutOfRangeException("Invalid index."); // Get the text. string text = string.Empty; int memIndex = -1; try { base.BeginUpdate(); memIndex = base.SelectedIndex; base.SelectedIndex = index; text = base.SelectedItem.ToString(); base.SelectedIndex = memIndex; } catch { } finally { base.EndUpdate(); } return text; } // GetDisplayText public string GetDisplayText(object value) { // Get the text. string text = string.Empty; int memIndex = -1; try { base.BeginUpdate(); memIndex = base.SelectedIndex; base.SelectedValue = value.ToString(); text = base.SelectedItem.ToString(); base.SelectedIndex = memIndex; } catch { } finally { base.EndUpdate(); } return text; } // GetDisplayText public string[] GetDisplayText() { // Get the text. string[] text = new string[base.Items.Count]; int memIndex = -1; try { base.BeginUpdate(); memIndex = base.SelectedIndex; for (int index = 0; index < base.Items.Count; index++) { base.SelectedIndex = index; text[index] = base.SelectedItem.ToString(); } base.SelectedIndex = memIndex; } catch { } finally { base.EndUpdate(); } return text; } // GetDisplayText } // DataGridComboBox #endregion } // DataGridCombo
// Copyright 2007-2008 The Apache Software Foundation. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Tests { using System; using System.Reflection; using System.Threading; using Configuration; using Magnum.InterfaceExtensions; using MassTransit.Serialization; using MassTransit.Transports; using Messages; using NUnit.Framework; using Rhino.Mocks; [TestFixture] public class When_a_message_fault_occurs : Specification { private IEndpointFactory _endpointFactory; private IServiceBus _bus; private IObjectBuilder _builder; protected override void Before_each() { _builder = MockRepository.GenerateMock<IObjectBuilder>(); _endpointFactory = EndpointFactoryConfigurator.New(x => { x.SetObjectBuilder(_builder); x.SetDefaultSerializer<XmlMessageSerializer>(); x.RegisterTransport<LoopbackEndpoint>(); }); _builder.Stub(x => x.GetInstance<IEndpointFactory>()).Return(_endpointFactory); _bus = ServiceBusConfigurator.New(x => { x.SetObjectBuilder(_builder); x.ReceiveFrom("loopback://localhost/servicebus"); }); } protected override void After_each() { _bus.Dispose(); _endpointFactory.Dispose(); } public class SmartConsumer : Consumes<Fault<Hello>>.All { private readonly ManualResetEvent _gotFault = new ManualResetEvent(false); public ManualResetEvent GotFault { get { return _gotFault; } } public void Consume(Fault<Hello> message) { _gotFault.Set(); } } [Serializable] public class Hello { } [Serializable] public class Hi { } [Test] public void Test_this() { Type faultType = typeof (Fault<>); ConstructorInfo[] constructorInfos = faultType.GetConstructors(); foreach (ConstructorInfo info in constructorInfos) { ParameterInfo[] parameters = info.GetParameters(); } Type customFaultType = typeof (Fault<PingMessage>); constructorInfos = customFaultType.GetConstructors(); foreach (ConstructorInfo info in constructorInfos) { ParameterInfo[] parameters = info.GetParameters(); } } [Test] public void I_should_receive_a_fault_message() { SmartConsumer sc = new SmartConsumer(); _bus.Subscribe<Hello>(delegate { throw new AccessViolationException("Crap!"); }); _bus.Subscribe(sc); _bus.Publish(new Hello()); Assert.IsTrue(sc.GotFault.WaitOne(TimeSpan.FromSeconds(500), true)); } } [TestFixture] public class When_a_correlated_message_fault_is_received : Specification { private IEndpointFactory _resolver; private IEndpoint _endpoint; private ServiceBus _bus; private IObjectBuilder _builder; protected override void Before_each() { _builder = MockRepository.GenerateMock<IObjectBuilder>(); _resolver = EndpointFactoryConfigurator.New(x => { x.SetObjectBuilder(_builder); x.SetDefaultSerializer<XmlMessageSerializer>(); x.RegisterTransport<LoopbackEndpoint>(); }); _endpoint = _resolver.GetEndpoint(new Uri("loopback://localhost/servicebus")); _bus = new ServiceBus(_endpoint, _builder, _resolver); _bus.Start(); } protected override void After_each() { _bus.Dispose(); _endpoint.Dispose(); _resolver.Dispose(); } public class SmartConsumer : Consumes<Fault<Hello, Guid>>.For<Guid> { private readonly ManualResetEvent _gotFault = new ManualResetEvent(false); private readonly Guid _id = Guid.NewGuid(); public ManualResetEvent GotFault { get { return _gotFault; } } public void Consume(Fault<Hello, Guid> message) { _gotFault.Set(); } public Guid CorrelationId { get { return _id; } } } [Serializable] public class Hello : CorrelatedBy<Guid> { private Guid _id; protected Hello() { } public Hello(Guid id) { _id = id; } public Guid CorrelationId { get { return _id; } set { _id = value; } } } [Serializable] public class Hi { } [Test] public void Open_generics_should_match_properly() { Assert.IsTrue(new Hello(Guid.NewGuid()).Implements(typeof (CorrelatedBy<>))); } [Test] public void I_should_receive_a_fault_message() { SmartConsumer sc = new SmartConsumer(); _bus.Subscribe<Hello>(delegate { throw new AccessViolationException("Crap!"); }); _bus.Subscribe(sc); _bus.Publish(new Hello(sc.CorrelationId)); Assert.IsTrue(sc.GotFault.WaitOne(TimeSpan.FromSeconds(5), true)); } } }
/* * CP20284.cs - IBM EBCDIC (Latin America/Spain) code page. * * Copyright (c) 2002 Southern Storm Software, Pty Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Generated from "ibm-284.ucm". namespace I18N.Rare { using System; using I18N.Common; public class CP20284 : ByteEncoding { public CP20284() : base(20284, ToChars, "IBM EBCDIC (Latin America/Spain)", "IBM284", "IBM284", "IBM284", false, false, false, false, 1252) {} private static readonly char[] ToChars = { '\u0000', '\u0001', '\u0002', '\u0003', '\u009C', '\u0009', '\u0086', '\u007F', '\u0097', '\u008D', '\u008E', '\u000B', '\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011', '\u0012', '\u0013', '\u009D', '\u0085', '\u0008', '\u0087', '\u0018', '\u0019', '\u0092', '\u008F', '\u001C', '\u001D', '\u001E', '\u001F', '\u0080', '\u0081', '\u0082', '\u0083', '\u0084', '\u000A', '\u0017', '\u001B', '\u0088', '\u0089', '\u008A', '\u008B', '\u008C', '\u0005', '\u0006', '\u0007', '\u0090', '\u0091', '\u0016', '\u0093', '\u0094', '\u0095', '\u0096', '\u0004', '\u0098', '\u0099', '\u009A', '\u009B', '\u0014', '\u0015', '\u009E', '\u001A', '\u0020', '\u00A0', '\u00E2', '\u00E4', '\u00E0', '\u00E1', '\u00E3', '\u00E5', '\u00E7', '\u00A6', '\u005B', '\u002E', '\u003C', '\u0028', '\u002B', '\u007C', '\u0026', '\u00E9', '\u00EA', '\u00EB', '\u00E8', '\u00ED', '\u00EE', '\u00EF', '\u00EC', '\u00DF', '\u005D', '\u0024', '\u002A', '\u0029', '\u003B', '\u00AC', '\u002D', '\u002F', '\u00C2', '\u00C4', '\u00C0', '\u00C1', '\u00C3', '\u00C5', '\u00C7', '\u0023', '\u00F1', '\u002C', '\u0025', '\u005F', '\u003E', '\u003F', '\u00F8', '\u00C9', '\u00CA', '\u00CB', '\u00C8', '\u00CD', '\u00CE', '\u00CF', '\u00CC', '\u0060', '\u003A', '\u00D1', '\u0040', '\u0027', '\u003D', '\u0022', '\u00D8', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069', '\u00AB', '\u00BB', '\u00F0', '\u00FD', '\u00FE', '\u00B1', '\u00B0', '\u006A', '\u006B', '\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071', '\u0072', '\u00AA', '\u00BA', '\u00E6', '\u00B8', '\u00C6', '\u00A4', '\u00B5', '\u00A8', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077', '\u0078', '\u0079', '\u007A', '\u00A1', '\u00BF', '\u00D0', '\u00DD', '\u00DE', '\u00AE', '\u00A2', '\u00A3', '\u00A5', '\u00B7', '\u00A9', '\u00A7', '\u00B6', '\u00BC', '\u00BD', '\u00BE', '\u005E', '\u0021', '\u00AF', '\u007E', '\u00B4', '\u00D7', '\u007B', '\u0041', '\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047', '\u0048', '\u0049', '\u00AD', '\u00F4', '\u00F6', '\u00F2', '\u00F3', '\u00F5', '\u007D', '\u004A', '\u004B', '\u004C', '\u004D', '\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u00B9', '\u00FB', '\u00FC', '\u00F9', '\u00FA', '\u00FF', '\u005C', '\u00F7', '\u0053', '\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059', '\u005A', '\u00B2', '\u00D4', '\u00D6', '\u00D2', '\u00D3', '\u00D5', '\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035', '\u0036', '\u0037', '\u0038', '\u0039', '\u00B3', '\u00DB', '\u00DC', '\u00D9', '\u00DA', '\u009F', }; protected override void ToBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(chars[charIndex++]); if(ch >= 4) switch(ch) { case 0x000B: case 0x000C: case 0x000D: case 0x000E: case 0x000F: case 0x0010: case 0x0011: case 0x0012: case 0x0013: case 0x0018: case 0x0019: case 0x001C: case 0x001D: case 0x001E: case 0x001F: case 0x00B6: break; case 0x0004: ch = 0x37; break; case 0x0005: ch = 0x2D; break; case 0x0006: ch = 0x2E; break; case 0x0007: ch = 0x2F; break; case 0x0008: ch = 0x16; break; case 0x0009: ch = 0x05; break; case 0x000A: ch = 0x25; break; case 0x0014: ch = 0x3C; break; case 0x0015: ch = 0x3D; break; case 0x0016: ch = 0x32; break; case 0x0017: ch = 0x26; break; case 0x001A: ch = 0x3F; break; case 0x001B: ch = 0x27; break; case 0x0020: ch = 0x40; break; case 0x0021: ch = 0xBB; break; case 0x0022: ch = 0x7F; break; case 0x0023: ch = 0x69; break; case 0x0024: ch = 0x5B; break; case 0x0025: ch = 0x6C; break; case 0x0026: ch = 0x50; break; case 0x0027: ch = 0x7D; break; case 0x0028: ch = 0x4D; break; case 0x0029: ch = 0x5D; break; case 0x002A: ch = 0x5C; break; case 0x002B: ch = 0x4E; break; case 0x002C: ch = 0x6B; break; case 0x002D: ch = 0x60; break; case 0x002E: ch = 0x4B; break; case 0x002F: ch = 0x61; break; case 0x0030: case 0x0031: case 0x0032: case 0x0033: case 0x0034: case 0x0035: case 0x0036: case 0x0037: case 0x0038: case 0x0039: ch += 0x00C0; break; case 0x003A: ch = 0x7A; break; case 0x003B: ch = 0x5E; break; case 0x003C: ch = 0x4C; break; case 0x003D: ch = 0x7E; break; case 0x003E: ch = 0x6E; break; case 0x003F: ch = 0x6F; break; case 0x0040: ch = 0x7C; break; case 0x0041: case 0x0042: case 0x0043: case 0x0044: case 0x0045: case 0x0046: case 0x0047: case 0x0048: case 0x0049: ch += 0x0080; break; case 0x004A: case 0x004B: case 0x004C: case 0x004D: case 0x004E: case 0x004F: case 0x0050: case 0x0051: case 0x0052: ch += 0x0087; break; case 0x0053: case 0x0054: case 0x0055: case 0x0056: case 0x0057: case 0x0058: case 0x0059: case 0x005A: ch += 0x008F; break; case 0x005B: ch = 0x4A; break; case 0x005C: ch = 0xE0; break; case 0x005D: ch = 0x5A; break; case 0x005E: ch = 0xBA; break; case 0x005F: ch = 0x6D; break; case 0x0060: ch = 0x79; break; case 0x0061: case 0x0062: case 0x0063: case 0x0064: case 0x0065: case 0x0066: case 0x0067: case 0x0068: case 0x0069: ch += 0x0020; break; case 0x006A: case 0x006B: case 0x006C: case 0x006D: case 0x006E: case 0x006F: case 0x0070: case 0x0071: case 0x0072: ch += 0x0027; break; case 0x0073: case 0x0074: case 0x0075: case 0x0076: case 0x0077: case 0x0078: case 0x0079: case 0x007A: ch += 0x002F; break; case 0x007B: ch = 0xC0; break; case 0x007C: ch = 0x4F; break; case 0x007D: ch = 0xD0; break; case 0x007E: ch = 0xBD; break; case 0x007F: ch = 0x07; break; case 0x0080: case 0x0081: case 0x0082: case 0x0083: case 0x0084: ch -= 0x0060; break; case 0x0085: ch = 0x15; break; case 0x0086: ch = 0x06; break; case 0x0087: ch = 0x17; break; case 0x0088: case 0x0089: case 0x008A: case 0x008B: case 0x008C: ch -= 0x0060; break; case 0x008D: ch = 0x09; break; case 0x008E: ch = 0x0A; break; case 0x008F: ch = 0x1B; break; case 0x0090: ch = 0x30; break; case 0x0091: ch = 0x31; break; case 0x0092: ch = 0x1A; break; case 0x0093: case 0x0094: case 0x0095: case 0x0096: ch -= 0x0060; break; case 0x0097: ch = 0x08; break; case 0x0098: case 0x0099: case 0x009A: case 0x009B: ch -= 0x0060; break; case 0x009C: ch = 0x04; break; case 0x009D: ch = 0x14; break; case 0x009E: ch = 0x3E; break; case 0x009F: ch = 0xFF; break; case 0x00A0: ch = 0x41; break; case 0x00A1: ch = 0xAA; break; case 0x00A2: ch = 0xB0; break; case 0x00A3: ch = 0xB1; break; case 0x00A4: ch = 0x9F; break; case 0x00A5: ch = 0xB2; break; case 0x00A6: ch = 0x49; break; case 0x00A7: ch = 0xB5; break; case 0x00A8: ch = 0xA1; break; case 0x00A9: ch = 0xB4; break; case 0x00AA: ch = 0x9A; break; case 0x00AB: ch = 0x8A; break; case 0x00AC: ch = 0x5F; break; case 0x00AD: ch = 0xCA; break; case 0x00AE: ch = 0xAF; break; case 0x00AF: ch = 0xBC; break; case 0x00B0: ch = 0x90; break; case 0x00B1: ch = 0x8F; break; case 0x00B2: ch = 0xEA; break; case 0x00B3: ch = 0xFA; break; case 0x00B4: ch = 0xBE; break; case 0x00B5: ch = 0xA0; break; case 0x00B7: ch = 0xB3; break; case 0x00B8: ch = 0x9D; break; case 0x00B9: ch = 0xDA; break; case 0x00BA: ch = 0x9B; break; case 0x00BB: ch = 0x8B; break; case 0x00BC: ch = 0xB7; break; case 0x00BD: ch = 0xB8; break; case 0x00BE: ch = 0xB9; break; case 0x00BF: ch = 0xAB; break; case 0x00C0: ch = 0x64; break; case 0x00C1: ch = 0x65; break; case 0x00C2: ch = 0x62; break; case 0x00C3: ch = 0x66; break; case 0x00C4: ch = 0x63; break; case 0x00C5: ch = 0x67; break; case 0x00C6: ch = 0x9E; break; case 0x00C7: ch = 0x68; break; case 0x00C8: ch = 0x74; break; case 0x00C9: ch = 0x71; break; case 0x00CA: ch = 0x72; break; case 0x00CB: ch = 0x73; break; case 0x00CC: ch = 0x78; break; case 0x00CD: ch = 0x75; break; case 0x00CE: ch = 0x76; break; case 0x00CF: ch = 0x77; break; case 0x00D0: ch = 0xAC; break; case 0x00D1: ch = 0x7B; break; case 0x00D2: ch = 0xED; break; case 0x00D3: ch = 0xEE; break; case 0x00D4: ch = 0xEB; break; case 0x00D5: ch = 0xEF; break; case 0x00D6: ch = 0xEC; break; case 0x00D7: ch = 0xBF; break; case 0x00D8: ch = 0x80; break; case 0x00D9: ch = 0xFD; break; case 0x00DA: ch = 0xFE; break; case 0x00DB: ch = 0xFB; break; case 0x00DC: ch = 0xFC; break; case 0x00DD: ch = 0xAD; break; case 0x00DE: ch = 0xAE; break; case 0x00DF: ch = 0x59; break; case 0x00E0: ch = 0x44; break; case 0x00E1: ch = 0x45; break; case 0x00E2: ch = 0x42; break; case 0x00E3: ch = 0x46; break; case 0x00E4: ch = 0x43; break; case 0x00E5: ch = 0x47; break; case 0x00E6: ch = 0x9C; break; case 0x00E7: ch = 0x48; break; case 0x00E8: ch = 0x54; break; case 0x00E9: ch = 0x51; break; case 0x00EA: ch = 0x52; break; case 0x00EB: ch = 0x53; break; case 0x00EC: ch = 0x58; break; case 0x00ED: ch = 0x55; break; case 0x00EE: ch = 0x56; break; case 0x00EF: ch = 0x57; break; case 0x00F0: ch = 0x8C; break; case 0x00F1: ch = 0x6A; break; case 0x00F2: ch = 0xCD; break; case 0x00F3: ch = 0xCE; break; case 0x00F4: ch = 0xCB; break; case 0x00F5: ch = 0xCF; break; case 0x00F6: ch = 0xCC; break; case 0x00F7: ch = 0xE1; break; case 0x00F8: ch = 0x70; break; case 0x00F9: ch = 0xDD; break; case 0x00FA: ch = 0xDE; break; case 0x00FB: ch = 0xDB; break; case 0x00FC: ch = 0xDC; break; case 0x00FD: ch = 0x8D; break; case 0x00FE: ch = 0x8E; break; case 0x00FF: ch = 0xDF; break; case 0x0110: ch = 0xAC; break; case 0x203E: ch = 0xBC; break; case 0xFF01: ch = 0xBB; break; case 0xFF02: ch = 0x7F; break; case 0xFF03: ch = 0x69; break; case 0xFF04: ch = 0x5B; break; case 0xFF05: ch = 0x6C; break; case 0xFF06: ch = 0x50; break; case 0xFF07: ch = 0x7D; break; case 0xFF08: ch = 0x4D; break; case 0xFF09: ch = 0x5D; break; case 0xFF0A: ch = 0x5C; break; case 0xFF0B: ch = 0x4E; break; case 0xFF0C: ch = 0x6B; break; case 0xFF0D: ch = 0x60; break; case 0xFF0E: ch = 0x4B; break; case 0xFF0F: ch = 0x61; break; case 0xFF10: case 0xFF11: case 0xFF12: case 0xFF13: case 0xFF14: case 0xFF15: case 0xFF16: case 0xFF17: case 0xFF18: case 0xFF19: ch -= 0xFE20; break; case 0xFF1A: ch = 0x7A; break; case 0xFF1B: ch = 0x5E; break; case 0xFF1C: ch = 0x4C; break; case 0xFF1D: ch = 0x7E; break; case 0xFF1E: ch = 0x6E; break; case 0xFF1F: ch = 0x6F; break; case 0xFF20: ch = 0x7C; break; case 0xFF21: case 0xFF22: case 0xFF23: case 0xFF24: case 0xFF25: case 0xFF26: case 0xFF27: case 0xFF28: case 0xFF29: ch -= 0xFE60; break; case 0xFF2A: case 0xFF2B: case 0xFF2C: case 0xFF2D: case 0xFF2E: case 0xFF2F: case 0xFF30: case 0xFF31: case 0xFF32: ch -= 0xFE59; break; case 0xFF33: case 0xFF34: case 0xFF35: case 0xFF36: case 0xFF37: case 0xFF38: case 0xFF39: case 0xFF3A: ch -= 0xFE51; break; case 0xFF3B: ch = 0x4A; break; case 0xFF3C: ch = 0xE0; break; case 0xFF3D: ch = 0x5A; break; case 0xFF3E: ch = 0xBA; break; case 0xFF3F: ch = 0x6D; break; case 0xFF40: ch = 0x79; break; case 0xFF41: case 0xFF42: case 0xFF43: case 0xFF44: case 0xFF45: case 0xFF46: case 0xFF47: case 0xFF48: case 0xFF49: ch -= 0xFEC0; break; case 0xFF4A: case 0xFF4B: case 0xFF4C: case 0xFF4D: case 0xFF4E: case 0xFF4F: case 0xFF50: case 0xFF51: case 0xFF52: ch -= 0xFEB9; break; case 0xFF53: case 0xFF54: case 0xFF55: case 0xFF56: case 0xFF57: case 0xFF58: case 0xFF59: case 0xFF5A: ch -= 0xFEB1; break; case 0xFF5B: ch = 0xC0; break; case 0xFF5C: ch = 0x4F; break; case 0xFF5D: ch = 0xD0; break; case 0xFF5E: ch = 0xBD; break; default: ch = 0x3F; break; } bytes[byteIndex++] = (byte)ch; --charCount; } } protected override void ToBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(s[charIndex++]); if(ch >= 4) switch(ch) { case 0x000B: case 0x000C: case 0x000D: case 0x000E: case 0x000F: case 0x0010: case 0x0011: case 0x0012: case 0x0013: case 0x0018: case 0x0019: case 0x001C: case 0x001D: case 0x001E: case 0x001F: case 0x00B6: break; case 0x0004: ch = 0x37; break; case 0x0005: ch = 0x2D; break; case 0x0006: ch = 0x2E; break; case 0x0007: ch = 0x2F; break; case 0x0008: ch = 0x16; break; case 0x0009: ch = 0x05; break; case 0x000A: ch = 0x25; break; case 0x0014: ch = 0x3C; break; case 0x0015: ch = 0x3D; break; case 0x0016: ch = 0x32; break; case 0x0017: ch = 0x26; break; case 0x001A: ch = 0x3F; break; case 0x001B: ch = 0x27; break; case 0x0020: ch = 0x40; break; case 0x0021: ch = 0xBB; break; case 0x0022: ch = 0x7F; break; case 0x0023: ch = 0x69; break; case 0x0024: ch = 0x5B; break; case 0x0025: ch = 0x6C; break; case 0x0026: ch = 0x50; break; case 0x0027: ch = 0x7D; break; case 0x0028: ch = 0x4D; break; case 0x0029: ch = 0x5D; break; case 0x002A: ch = 0x5C; break; case 0x002B: ch = 0x4E; break; case 0x002C: ch = 0x6B; break; case 0x002D: ch = 0x60; break; case 0x002E: ch = 0x4B; break; case 0x002F: ch = 0x61; break; case 0x0030: case 0x0031: case 0x0032: case 0x0033: case 0x0034: case 0x0035: case 0x0036: case 0x0037: case 0x0038: case 0x0039: ch += 0x00C0; break; case 0x003A: ch = 0x7A; break; case 0x003B: ch = 0x5E; break; case 0x003C: ch = 0x4C; break; case 0x003D: ch = 0x7E; break; case 0x003E: ch = 0x6E; break; case 0x003F: ch = 0x6F; break; case 0x0040: ch = 0x7C; break; case 0x0041: case 0x0042: case 0x0043: case 0x0044: case 0x0045: case 0x0046: case 0x0047: case 0x0048: case 0x0049: ch += 0x0080; break; case 0x004A: case 0x004B: case 0x004C: case 0x004D: case 0x004E: case 0x004F: case 0x0050: case 0x0051: case 0x0052: ch += 0x0087; break; case 0x0053: case 0x0054: case 0x0055: case 0x0056: case 0x0057: case 0x0058: case 0x0059: case 0x005A: ch += 0x008F; break; case 0x005B: ch = 0x4A; break; case 0x005C: ch = 0xE0; break; case 0x005D: ch = 0x5A; break; case 0x005E: ch = 0xBA; break; case 0x005F: ch = 0x6D; break; case 0x0060: ch = 0x79; break; case 0x0061: case 0x0062: case 0x0063: case 0x0064: case 0x0065: case 0x0066: case 0x0067: case 0x0068: case 0x0069: ch += 0x0020; break; case 0x006A: case 0x006B: case 0x006C: case 0x006D: case 0x006E: case 0x006F: case 0x0070: case 0x0071: case 0x0072: ch += 0x0027; break; case 0x0073: case 0x0074: case 0x0075: case 0x0076: case 0x0077: case 0x0078: case 0x0079: case 0x007A: ch += 0x002F; break; case 0x007B: ch = 0xC0; break; case 0x007C: ch = 0x4F; break; case 0x007D: ch = 0xD0; break; case 0x007E: ch = 0xBD; break; case 0x007F: ch = 0x07; break; case 0x0080: case 0x0081: case 0x0082: case 0x0083: case 0x0084: ch -= 0x0060; break; case 0x0085: ch = 0x15; break; case 0x0086: ch = 0x06; break; case 0x0087: ch = 0x17; break; case 0x0088: case 0x0089: case 0x008A: case 0x008B: case 0x008C: ch -= 0x0060; break; case 0x008D: ch = 0x09; break; case 0x008E: ch = 0x0A; break; case 0x008F: ch = 0x1B; break; case 0x0090: ch = 0x30; break; case 0x0091: ch = 0x31; break; case 0x0092: ch = 0x1A; break; case 0x0093: case 0x0094: case 0x0095: case 0x0096: ch -= 0x0060; break; case 0x0097: ch = 0x08; break; case 0x0098: case 0x0099: case 0x009A: case 0x009B: ch -= 0x0060; break; case 0x009C: ch = 0x04; break; case 0x009D: ch = 0x14; break; case 0x009E: ch = 0x3E; break; case 0x009F: ch = 0xFF; break; case 0x00A0: ch = 0x41; break; case 0x00A1: ch = 0xAA; break; case 0x00A2: ch = 0xB0; break; case 0x00A3: ch = 0xB1; break; case 0x00A4: ch = 0x9F; break; case 0x00A5: ch = 0xB2; break; case 0x00A6: ch = 0x49; break; case 0x00A7: ch = 0xB5; break; case 0x00A8: ch = 0xA1; break; case 0x00A9: ch = 0xB4; break; case 0x00AA: ch = 0x9A; break; case 0x00AB: ch = 0x8A; break; case 0x00AC: ch = 0x5F; break; case 0x00AD: ch = 0xCA; break; case 0x00AE: ch = 0xAF; break; case 0x00AF: ch = 0xBC; break; case 0x00B0: ch = 0x90; break; case 0x00B1: ch = 0x8F; break; case 0x00B2: ch = 0xEA; break; case 0x00B3: ch = 0xFA; break; case 0x00B4: ch = 0xBE; break; case 0x00B5: ch = 0xA0; break; case 0x00B7: ch = 0xB3; break; case 0x00B8: ch = 0x9D; break; case 0x00B9: ch = 0xDA; break; case 0x00BA: ch = 0x9B; break; case 0x00BB: ch = 0x8B; break; case 0x00BC: ch = 0xB7; break; case 0x00BD: ch = 0xB8; break; case 0x00BE: ch = 0xB9; break; case 0x00BF: ch = 0xAB; break; case 0x00C0: ch = 0x64; break; case 0x00C1: ch = 0x65; break; case 0x00C2: ch = 0x62; break; case 0x00C3: ch = 0x66; break; case 0x00C4: ch = 0x63; break; case 0x00C5: ch = 0x67; break; case 0x00C6: ch = 0x9E; break; case 0x00C7: ch = 0x68; break; case 0x00C8: ch = 0x74; break; case 0x00C9: ch = 0x71; break; case 0x00CA: ch = 0x72; break; case 0x00CB: ch = 0x73; break; case 0x00CC: ch = 0x78; break; case 0x00CD: ch = 0x75; break; case 0x00CE: ch = 0x76; break; case 0x00CF: ch = 0x77; break; case 0x00D0: ch = 0xAC; break; case 0x00D1: ch = 0x7B; break; case 0x00D2: ch = 0xED; break; case 0x00D3: ch = 0xEE; break; case 0x00D4: ch = 0xEB; break; case 0x00D5: ch = 0xEF; break; case 0x00D6: ch = 0xEC; break; case 0x00D7: ch = 0xBF; break; case 0x00D8: ch = 0x80; break; case 0x00D9: ch = 0xFD; break; case 0x00DA: ch = 0xFE; break; case 0x00DB: ch = 0xFB; break; case 0x00DC: ch = 0xFC; break; case 0x00DD: ch = 0xAD; break; case 0x00DE: ch = 0xAE; break; case 0x00DF: ch = 0x59; break; case 0x00E0: ch = 0x44; break; case 0x00E1: ch = 0x45; break; case 0x00E2: ch = 0x42; break; case 0x00E3: ch = 0x46; break; case 0x00E4: ch = 0x43; break; case 0x00E5: ch = 0x47; break; case 0x00E6: ch = 0x9C; break; case 0x00E7: ch = 0x48; break; case 0x00E8: ch = 0x54; break; case 0x00E9: ch = 0x51; break; case 0x00EA: ch = 0x52; break; case 0x00EB: ch = 0x53; break; case 0x00EC: ch = 0x58; break; case 0x00ED: ch = 0x55; break; case 0x00EE: ch = 0x56; break; case 0x00EF: ch = 0x57; break; case 0x00F0: ch = 0x8C; break; case 0x00F1: ch = 0x6A; break; case 0x00F2: ch = 0xCD; break; case 0x00F3: ch = 0xCE; break; case 0x00F4: ch = 0xCB; break; case 0x00F5: ch = 0xCF; break; case 0x00F6: ch = 0xCC; break; case 0x00F7: ch = 0xE1; break; case 0x00F8: ch = 0x70; break; case 0x00F9: ch = 0xDD; break; case 0x00FA: ch = 0xDE; break; case 0x00FB: ch = 0xDB; break; case 0x00FC: ch = 0xDC; break; case 0x00FD: ch = 0x8D; break; case 0x00FE: ch = 0x8E; break; case 0x00FF: ch = 0xDF; break; case 0x0110: ch = 0xAC; break; case 0x203E: ch = 0xBC; break; case 0xFF01: ch = 0xBB; break; case 0xFF02: ch = 0x7F; break; case 0xFF03: ch = 0x69; break; case 0xFF04: ch = 0x5B; break; case 0xFF05: ch = 0x6C; break; case 0xFF06: ch = 0x50; break; case 0xFF07: ch = 0x7D; break; case 0xFF08: ch = 0x4D; break; case 0xFF09: ch = 0x5D; break; case 0xFF0A: ch = 0x5C; break; case 0xFF0B: ch = 0x4E; break; case 0xFF0C: ch = 0x6B; break; case 0xFF0D: ch = 0x60; break; case 0xFF0E: ch = 0x4B; break; case 0xFF0F: ch = 0x61; break; case 0xFF10: case 0xFF11: case 0xFF12: case 0xFF13: case 0xFF14: case 0xFF15: case 0xFF16: case 0xFF17: case 0xFF18: case 0xFF19: ch -= 0xFE20; break; case 0xFF1A: ch = 0x7A; break; case 0xFF1B: ch = 0x5E; break; case 0xFF1C: ch = 0x4C; break; case 0xFF1D: ch = 0x7E; break; case 0xFF1E: ch = 0x6E; break; case 0xFF1F: ch = 0x6F; break; case 0xFF20: ch = 0x7C; break; case 0xFF21: case 0xFF22: case 0xFF23: case 0xFF24: case 0xFF25: case 0xFF26: case 0xFF27: case 0xFF28: case 0xFF29: ch -= 0xFE60; break; case 0xFF2A: case 0xFF2B: case 0xFF2C: case 0xFF2D: case 0xFF2E: case 0xFF2F: case 0xFF30: case 0xFF31: case 0xFF32: ch -= 0xFE59; break; case 0xFF33: case 0xFF34: case 0xFF35: case 0xFF36: case 0xFF37: case 0xFF38: case 0xFF39: case 0xFF3A: ch -= 0xFE51; break; case 0xFF3B: ch = 0x4A; break; case 0xFF3C: ch = 0xE0; break; case 0xFF3D: ch = 0x5A; break; case 0xFF3E: ch = 0xBA; break; case 0xFF3F: ch = 0x6D; break; case 0xFF40: ch = 0x79; break; case 0xFF41: case 0xFF42: case 0xFF43: case 0xFF44: case 0xFF45: case 0xFF46: case 0xFF47: case 0xFF48: case 0xFF49: ch -= 0xFEC0; break; case 0xFF4A: case 0xFF4B: case 0xFF4C: case 0xFF4D: case 0xFF4E: case 0xFF4F: case 0xFF50: case 0xFF51: case 0xFF52: ch -= 0xFEB9; break; case 0xFF53: case 0xFF54: case 0xFF55: case 0xFF56: case 0xFF57: case 0xFF58: case 0xFF59: case 0xFF5A: ch -= 0xFEB1; break; case 0xFF5B: ch = 0xC0; break; case 0xFF5C: ch = 0x4F; break; case 0xFF5D: ch = 0xD0; break; case 0xFF5E: ch = 0xBD; break; default: ch = 0x3F; break; } bytes[byteIndex++] = (byte)ch; --charCount; } } }; // class CP20284 public class ENCibm284 : CP20284 { public ENCibm284() : base() {} }; // class ENCibm284 }; // namespace I18N.Rare
// <developer>niklas@protocol7.com</developer> // <completed>100</completed> using System; using System.Xml; using System.Globalization; using System.Text.RegularExpressions; namespace SharpVectors.Dom.Css { /// <summary> /// The CSSPrimitiveValue interface represents a single CSS value. /// </summary> /// <remarks> /// <para> /// This interface may be used to determine the value of a specific style /// property currently set in a block or to set a specific style property /// explicitly within the block. An instance of this interface might be /// obtained from the getPropertyCSSValue method of the CSSStyleDeclaration /// interface. A CSSPrimitiveValue object only occurs in a context of a CSS property. /// </para> /// <para> /// Conversions are allowed between absolute values (from millimeters to centimeters, /// from degrees to radians, and so on) but not between relative values. (For example, /// a pixel value cannot be converted to a centimeter value.) Percentage values can't /// be converted since they are relative to the parent value (or another property value). /// There is one exception for color percentage values: since a color percentage value /// is relative to the range 0-255, a color percentage value can be converted to a number; /// (see also the RGBColor interface). /// </para> /// </remarks> public class CssPrimitiveValue : CssValue, ICssPrimitiveValue { #region Private Fields private CssPrimitiveType _primitiveType; protected double floatValue; private string stringValue; private CssRect rectValue; protected CssColor colorValue; #endregion #region Constructors and Destructor /// <summary> /// Constructor called by CssValue.GetCssValue() /// </summary> /// <param name="match">A Regex that matches a CssPrimitiveValue</param> /// <param name="readOnly">Specifiec if this instance is read-only</param> private CssPrimitiveValue(Match match, bool readOnly) : this(match.Value, readOnly) { if (match.Groups["func"].Success) { switch (match.Groups["funcname"].Value) { case "rect": _primitiveType = CssPrimitiveType.Rect; rectValue = new CssRect(match.Groups["funcvalue"].Value, ReadOnly); break; case "attr": _primitiveType = CssPrimitiveType.Attr; stringValue = match.Groups["funcvalue"].Value; break; case "url": stringValue = match.Groups["funcvalue"].Value; _primitiveType = CssPrimitiveType.Uri; break; case "counter": throw new NotImplementedException("Counters are not implemented"); //_primitiveType = CssPrimitiveType.CSS_COUNTER; } } else if (match.Groups["freqTimeNumber"].Success) { floatValue = Single.Parse(match.Groups["numberValue2"].Value, CssNumber.Format); switch (match.Groups["unit2"].Value) { case "Hz": _primitiveType = CssPrimitiveType.Hz; break; case "kHz": _primitiveType = CssPrimitiveType.KHz; break; case "in": _primitiveType = CssPrimitiveType.In; break; case "s": _primitiveType = CssPrimitiveType.S; break; case "ms": _primitiveType = CssPrimitiveType.Ms; break; case "%": _primitiveType = CssPrimitiveType.Percentage; break; default: _primitiveType = CssPrimitiveType.Number; break; } } else if (match.Groups["string"].Success) { stringValue = match.Groups["stringvalue"].Value; _primitiveType = CssPrimitiveType.String; } else if (match.Groups["colorIdent"].Success) { string val = match.Value; stringValue = match.Value; _primitiveType = CssPrimitiveType.Ident; } else { _primitiveType = CssPrimitiveType.Unknown; } } protected CssPrimitiveValue(string cssText, bool readOnly) : base(CssValueType.PrimitiveValue, cssText, readOnly) { _primitiveType = CssPrimitiveType.Unknown; floatValue = Double.NaN; } /// <summary> /// Only for internal use /// </summary> protected CssPrimitiveValue() : base() { _primitiveType = CssPrimitiveType.Unknown; _cssValueType = CssValueType.PrimitiveValue; floatValue = Double.NaN; } #endregion #region Public Properties public string PrimitiveTypeAsString { get { switch (PrimitiveType) { case CssPrimitiveType.Percentage: return "%"; case CssPrimitiveType.Ems: return "em"; case CssPrimitiveType.Exs: return "ex"; case CssPrimitiveType.Px: return "px"; case CssPrimitiveType.Cm: return "cm"; case CssPrimitiveType.Mm: return "mm"; case CssPrimitiveType.In: return "in"; case CssPrimitiveType.Pt: return "pt"; case CssPrimitiveType.Pc: return "pc"; case CssPrimitiveType.Deg: return "deg"; case CssPrimitiveType.Rad: return "rad"; case CssPrimitiveType.Grad: return "grad"; case CssPrimitiveType.Ms: return "ms"; case CssPrimitiveType.S: return "s"; case CssPrimitiveType.Hz: return "hz"; case CssPrimitiveType.KHz: return "khz"; default: return String.Empty; } } } public override string CssText { get { if (PrimitiveType == CssPrimitiveType.String) { return "\"" + GetStringValue() + "\""; } else { return base.CssText; } } set { if (ReadOnly) { throw new DomException(DomExceptionType.InvalidModificationErr, "CssPrimitiveValue is read-only"); } else { OnSetCssText(value); } } } #endregion #region Public Methods public static CssPrimitiveValue Create(Match match, bool readOnly) { if (match.Groups["length"].Success) { return new CssPrimitiveLengthValue(match.Groups["lengthNumber"].Value, match.Groups["lengthUnit"].Value, readOnly); } else if (match.Groups["angle"].Success) { return new CssPrimitiveAngleValue(match.Groups["angleNumber"].Value, match.Groups["angleUnit"].Value, readOnly); } else if (match.Groups["funcname"].Success && match.Groups["funcname"].Value == "rgb") { return new CssPrimitiveRgbValue(match.Groups["func"].Value, readOnly); } else if (match.Groups["colorIdent"].Success && CssPrimitiveRgbValue.IsColorName(match.Groups["colorIdent"].Value)) { return new CssPrimitiveRgbValue(match.Groups["colorIdent"].Value, readOnly); } else { return new CssPrimitiveValue(match, readOnly); } } public override CssValue GetAbsoluteValue(string propertyName, XmlElement elm) { if (propertyName == "font-size") { return new CssAbsPrimitiveLengthValue(this, propertyName, elm); } else { return new CssAbsPrimitiveValue(this, propertyName, elm); } } #endregion #region Protected Methods protected virtual void OnSetCssText(string cssText) { } #endregion #region ICssPrimitiveValue Members /// <summary> /// A method to set the float value with a specified unit. If the property attached with this value can not accept the specified unit or the float value, the value will be unchanged and a DOMException will be raised. /// </summary> /// <param name="unitType">A unit code as defined above. The unit code can only be a float unit type (i.e. CSS_NUMBER, CSS_PERCENTAGE, CSS_EMS, CSS_EXS, CSS_PX, CSS_CM, CSS_MM, CSS_IN, CSS_PT, CSS_PC, CSS_DEG, CSS_RAD, CSS_GRAD, CSS_MS, CSS_S, CSS_HZ, CSS_KHZ, CSS_DIMENSION).</param> /// <param name="floatValue">The new float value.</param> /// <exception cref="DomException">INVALID_ACCESS_ERR: Raised if the CSS value doesn't contain a float value.</exception> /// <exception cref="DomException">NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.</exception> public virtual void SetFloatValue(CssPrimitiveType unitType, double floatValue) { if (this.ReadOnly) { throw new DomException(DomExceptionType.NoModificationAllowedErr); } else { _primitiveType = unitType; SetFloatValue(floatValue); } } protected void SetFloatValue(string floatValue) { SetFloatValue(Double.Parse(floatValue, CssNumber.Format)); } protected void SetFloatValue(double floatValue) { this.floatValue = floatValue; } /// <summary> /// This method is used to get a float value in a specified unit. If this CSS value doesn't contain a float value or can't be converted into the specified unit, a DOMException is raised /// </summary> /// <param name="unitType">A unit code to get the float value. The unit code can only be a float unit type (i.e. CSS_NUMBER, CSS_PERCENTAGE, CSS_EMS, CSS_EXS, CSS_PX, CSS_CM, CSS_MM, CSS_IN, CSS_PT, CSS_PC, CSS_DEG, CSS_RAD, CSS_GRAD, CSS_MS, CSS_S, CSS_HZ, CSS_KHZ, CSS_DIMENSION).</param> /// <returns>The float value in the specified unit.</returns> /// <exception cref="DomException">INVALID_ACCESS_ERR: Raised if the CSS value doesn't contain a float value.</exception> public virtual double GetFloatValue(CssPrimitiveType unitType) { if (Double.IsNaN(floatValue)) { throw new DomException(DomExceptionType.InvalidAccessErr); } else { double ret = Double.NaN; switch (PrimitiveType) { case CssPrimitiveType.Percentage: if (unitType == CssPrimitiveType.Percentage) ret = floatValue; break; case CssPrimitiveType.Ms: if (unitType == CssPrimitiveType.Ms) ret = floatValue; else if (unitType == CssPrimitiveType.S) ret = floatValue / 1000; break; case CssPrimitiveType.S: if (unitType == CssPrimitiveType.Ms) ret = floatValue * 1000; else if (unitType == CssPrimitiveType.S) ret = floatValue; break; case CssPrimitiveType.Hz: if (unitType == CssPrimitiveType.Hz) ret = floatValue; else if (unitType == CssPrimitiveType.KHz) ret = floatValue / 1000; break; case CssPrimitiveType.KHz: if (unitType == CssPrimitiveType.Hz) ret = floatValue * 1000; else if (unitType == CssPrimitiveType.KHz) ret = floatValue; break; case CssPrimitiveType.Dimension: if (unitType == CssPrimitiveType.Dimension) ret = floatValue; break; } if (Double.IsNaN(ret)) { throw new DomException(DomExceptionType.InvalidAccessErr); } else { return ret; } } } /// <summary> /// A method to set the string value with the specified unit. If the property attached to this value can't accept the specified unit or the string value, the value will be unchanged and a DOMException will be raised. /// </summary> /// <param name="stringType">A string code as defined above. The string code can only be a string unit type (i.e. CSS_STRING, CSS_URI, CSS_IDENT, and CSS_ATTR).</param> /// <param name="stringValue">The new string value</param> /// <exception cref="DomException">INVALID_ACCESS_ERR: Raised if the CSS value doesn't contain a string value.</exception> /// <exception cref="DomException">NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.</exception> public virtual void SetStringValue(CssPrimitiveType stringType, string stringValue) { throw new NotImplementedException("SetStringValue"); } /// <summary> /// This method is used to get the string value. If the CSS value doesn't contain a string value, a DOMException is raised. /// Note: Some properties (like 'font-family' or 'voice-family') convert a whitespace separated list of idents to a string. /// </summary> /// <returns>The string value in the current unit. The current primitiveType can only be a string unit type (i.e. CSS_STRING, CSS_URI, CSS_IDENT and CSS_ATTR).</returns> /// <exception cref="DomException">INVALID_ACCESS_ERR: Raised if the CSS value doesn't contain a string value.</exception> public virtual string GetStringValue() { string ret = null; switch (PrimitiveType) { case CssPrimitiveType.String: case CssPrimitiveType.Uri: case CssPrimitiveType.Ident: case CssPrimitiveType.Attr: ret = stringValue; break; } if (ret != null) return ret; else throw new DomException(DomExceptionType.InvalidAccessErr); } /// <summary> /// This method is used to get the Counter value. If this CSS value doesn't contain a counter value, a DOMException is raised. Modification to the corresponding style property can be achieved using the Counter interface /// </summary> /// <returns>The Counter value.</returns> /// <exception cref="DomException">INVALID_ACCESS_ERR: Raised if the CSS value doesn't contain a Counter value (e.g. this is not CSS_COUNTER).</exception> public virtual ICssCounter GetCounterValue() { throw new NotImplementedException("GetCounterValue"); } /// <summary> /// This method is used to get the Rect value. If this CSS value doesn't contain a rect value, a DOMException is raised. Modification to the corresponding style property can be achieved using the Rect interface. /// </summary> /// <returns>The Rect value.</returns> /// <exception cref="DomException">INVALID_ACCESS_ERR: Raised if the CSS value doesn't contain a rect value.</exception> public virtual ICssRect GetRectValue() { if (PrimitiveType == CssPrimitiveType.Rect) return rectValue; else throw new DomException(DomExceptionType.InvalidAccessErr); } /// <summary> /// This method is used to get the RGB color. If this CSS value doesn't contain a RGB color value, a DOMException is raised. Modification to the corresponding style property can be achieved using the RGBColor interface. /// </summary> /// <returns>the RGB color value.</returns> /// <exception cref="DomException">INVALID_ACCESS_ERR: Raised if the CSS value doesn't contain a rgb value.</exception> public virtual ICssColor GetRgbColorValue() { if (PrimitiveType == CssPrimitiveType.RgbColor) return colorValue; else throw new DomException(DomExceptionType.InvalidAccessErr); } protected void SetPrimitiveType(CssPrimitiveType type) { _primitiveType = type; } /// <summary> /// The type of the value as defined by the constants specified above. /// </summary> public virtual CssPrimitiveType PrimitiveType { get { return _primitiveType; } protected set { _primitiveType = value; } } #endregion } }
// // MRMapChit.cs // // Author: // Steve Jakab <> // // Copyright (c) 2014 Steve Jakab // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using AssemblyCSharp; namespace PortableRealm { public class MRMapChit : MRChit { #region Sort Class public class MRMapChitSorter : IComparer { int IComparer.Compare(object x, object y) { return ((MRMapChit)x).SummonSortIndex - ((MRMapChit)y).SummonSortIndex; } } #endregion #region Constants public enum eMapChitType { Sound, Warning, Site, SuperSite, Dwelling } public enum eSoundChitType { Flutter, Howl, Patter, Roar, Slither } public enum eWarningChitType { Bones, Dank, Ruins, Smoke, Stink } public enum eSiteChitType { Altar, Cairns, Hoard, Lair, Pool, Shrine, Statue, Vault } public enum eSuperSiteChitType { LostCastle, LostCity, } public static Dictionary<string, eMapChitType> ChitTypeMap = new Dictionary<string, eMapChitType>() { {"so", eMapChitType.Sound}, {"wa", eMapChitType.Warning}, {"si", eMapChitType.Site}, {"su", eMapChitType.SuperSite}, {"dw", eMapChitType.Dwelling} }; public static Dictionary<string, eSoundChitType> ChitSoundMap = new Dictionary<string, eSoundChitType>() { {"fl", eSoundChitType.Flutter}, {"ho", eSoundChitType.Howl}, {"pa", eSoundChitType.Patter}, {"ro", eSoundChitType.Roar}, {"sl", eSoundChitType.Slither} }; public static Dictionary<string, eWarningChitType> ChitWarningMap = new Dictionary<string, eWarningChitType>() { {"bo", eWarningChitType.Bones}, {"da", eWarningChitType.Dank}, {"ru", eWarningChitType.Ruins}, {"sm", eWarningChitType.Smoke}, {"st", eWarningChitType.Stink} }; public static Dictionary<string, eSiteChitType> ChitSiteMap = new Dictionary<string, eSiteChitType>() { {"al", eSiteChitType.Altar}, {"ca", eSiteChitType.Cairns}, {"ho", eSiteChitType.Hoard}, {"la", eSiteChitType.Lair}, {"po", eSiteChitType.Pool}, {"sh", eSiteChitType.Shrine}, {"st", eSiteChitType.Statue}, {"va", eSiteChitType.Vault} }; private const int BIG_FONT_SIZE = 180; private const int SMALL_FONT_SIZE = 70; #endregion #region Properties public static IDictionary<eMapChitType, Type> MapChitTypes { get { return msMapChitTypes; } } public eMapChitType ChitType { get{ return mChitType; } } public MRTile Tile { get{ return mTile; } set{ mTile = value; } } public GameObject Counter { get{ return mCounter; } } public string LongName { get{ return mLongName; } protected set{ mLongName = value; Id = MRUtility.IdForName(mLongName); } } public string ShortName { get{ return mShortName; } protected set{ mShortName = value; } } public override string Name { get{ return mLongName; } } public bool SummonedMonsters { get{ return mSummonedMonsters; } set{ mSummonedMonsters = false; } } public virtual int SummonSortIndex { get{ return 100; } } public override Transform Parent { get{ return base.Parent; } set { base.Parent = value; transform.localScale = Vector3.one; } } #endregion #region Methods static MRMapChit() { msMapChitTypes = new Dictionary<eMapChitType, Type>(); } // Called when the script instance is being loaded void Awake() { mCounter = (GameObject)Instantiate(MRGame.TheGame.smallChitPrototype); mCounter.transform.parent = transform; SideUp = eSide.Back; mLongName = "XX"; mShortName = "X"; } // Use this for initialization public override void Start () { base.Start(); SpriteRenderer[] sprites = mCounter.GetComponentsInChildren<SpriteRenderer>(); foreach (SpriteRenderer sprite in sprites) { if (sprite.gameObject.name == "FrontSide") { switch (mChitType) { case eMapChitType.Site: sprite.color = MRGame.gold; break; case eMapChitType.SuperSite: case eMapChitType.Sound: sprite.color = MRGame.red; break; case eMapChitType.Warning: sprite.color = MRGame.yellow; break; } } } } // Update is called once per frame public override void Update () { base.Update(); TextMesh[] components = mCounter.GetComponentsInChildren<TextMesh>(); foreach (TextMesh text in components) { if (text.gameObject.name == "FrontText") { if (MRGame.TheGame.TheMap.MapZoomed || (Stack != null && Stack.Inspecting)) { text.fontSize = SMALL_FONT_SIZE; text.text = mLongName; } else { text.fontSize = BIG_FONT_SIZE; text.text = mShortName; } break; } } } public static MRMapChit Create(eMapChitType chitType) { GameObject root = new GameObject(); MRMapChit chit = (MRMapChit)root.AddComponent(chitType.ClazzType()); return chit; } public static MRMapChit Create(JSONObject root) { eMapChitType chitType; if (root["type"] is JSONNumber) { chitType = (eMapChitType)((JSONNumber)root["type"]).IntValue; } else if (root["type"] is JSONString) { if (!ChitTypeMap.TryGetValue(((JSONString)root["type"]).Value, out chitType)) { return null; } } else { return null; } MRMapChit chit = Create(chitType); chit.Load(root); return chit; } public override bool Load(JSONObject root) { if (!base.Load(root)) return false; if (root["type"] is JSONNumber) { mChitType = (eMapChitType)((JSONNumber)root["type"]).IntValue; } else if (root["type"] is JSONString) { if (!ChitTypeMap.TryGetValue(((JSONString)root["type"]).Value, out mChitType)) { return false; } } return true; } public override void Save(JSONObject root) { base.Save(root); root["type"] = new JSONNumber((int)mChitType); root["set"] = new JSONNumber(1); // this is in anticipation of multi-set boards } #endregion #region Members protected eMapChitType mChitType; protected MRTile mTile; protected bool mSummonedMonsters; private string mLongName; private string mShortName; private static IDictionary<eMapChitType, Type> msMapChitTypes; #endregion } }
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Alphaleonis.Win32.Filesystem; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.NetworkInformation; using System.Security; namespace Alphaleonis.Win32.Network { partial class Host { #region EnumerateDfsLinks /// <summary>Enumerates the DFS Links from a DFS namespace.</summary> /// <returns><see cref="IEnumerable{DfsInfo}"/> of DFS namespaces.</returns> /// <exception cref="ArgumentNullException"/> /// <exception cref="NetworkInformationException"/> /// <exception cref="PlatformNotSupportedException"/> /// <param name="dfsName">The Universal Naming Convention (UNC) path of a DFS root or link.</param> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "dfs")] [SecurityCritical] public static IEnumerable<DfsInfo> EnumerateDfsLinks(string dfsName) { if (!Filesystem.NativeMethods.IsAtLeastWindowsVista) throw new PlatformNotSupportedException(Resources.Requires_Windows_Vista_Or_Higher); if (Utils.IsNullOrWhiteSpace(dfsName)) throw new ArgumentNullException("dfsName"); var fd = new FunctionData(); return EnumerateNetworkObjectCore(fd, (NativeMethods.DFS_INFO_9 structure, SafeGlobalMemoryBufferHandle buffer) => new DfsInfo(structure), (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle1) => { totalEntries = 0; return NativeMethods.NetDfsEnum(dfsName, 9, prefMaxLen, out buffer, out entriesRead, out resumeHandle1); }, false); } #endregion // EnumerateDfsLinks #region EnumerateDfsRoot /// <summary>Enumerates the DFS namespaces from the local host.</summary> /// <returns><see cref="IEnumerable{String}"/> of DFS Root namespaces from the local host.</returns> /// <exception cref="NetworkInformationException"/> /// <exception cref="PlatformNotSupportedException"/> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")] [SecurityCritical] public static IEnumerable<string> EnumerateDfsRoot() { return EnumerateDfsRootCore(null, false); } /// <summary>Enumerates the DFS namespaces from a host.</summary> /// <returns><see cref="IEnumerable{String}"/> of DFS Root namespaces from a host.</returns> /// <exception cref="NetworkInformationException"/> /// <exception cref="PlatformNotSupportedException"/> /// <param name="host">The DNS or NetBIOS name of a host.</param> /// <param name="continueOnException"><see langword="true"/> suppress any Exception that might be thrown a result from a failure, such as unavailable resources.</param> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")] [SecurityCritical] public static IEnumerable<string> EnumerateDfsRoot(string host, bool continueOnException) { return EnumerateDfsRootCore(host, continueOnException); } #endregion // EnumerateDfsRoot #region EnumerateDomainDfsRoot /// <summary>Enumerates the DFS namespaces from the domain.</summary> /// <returns><see cref="IEnumerable{String}"/> of DFS Root namespaces from the domain.</returns> /// <exception cref="NetworkInformationException"/> /// <exception cref="PlatformNotSupportedException"/> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")] [SecurityCritical] public static IEnumerable<string> EnumerateDomainDfsRoot() { return EnumerateDomainDfsRootCore(null, false); } /// <summary>Enumerates the DFS namespaces from a domain.</summary> /// <returns><see cref="IEnumerable{String}"/> of DFS Root namespaces from a domain.</returns> /// <exception cref="NetworkInformationException"/> /// <exception cref="PlatformNotSupportedException"/> /// <param name="domain">A domain name.</param> /// <param name="continueOnException"><see langword="true"/> suppress any Exception that might be thrown a result from a failure, such as unavailable resources.</param> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")] [SecurityCritical] public static IEnumerable<string> EnumerateDomainDfsRoot(string domain, bool continueOnException) { return EnumerateDomainDfsRootCore(domain, continueOnException); } #endregion // EnumerateDomainDfsRoot #region GetDfsClientInfo /// <summary>Gets information about a DFS root or link from the cache maintained by the DFS client.</summary> /// <returns>A <see cref="DfsInfo"/> instance.</returns> /// <exception cref="NetworkInformationException"/> /// <exception cref="PlatformNotSupportedException"/> /// <param name="dfsName">The Universal Naming Convention (UNC) path of a DFS root or link.</param> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "dfs")] [SecurityCritical] public static DfsInfo GetDfsClientInfo(string dfsName) { return GetDfsInfoCore(true, dfsName, null, null); } /// <summary>Gets information about a DFS root or link from the cache maintained by the DFS client.</summary> /// <returns>A <see cref="DfsInfo"/> instance.</returns> /// <exception cref="NetworkInformationException"/> /// <exception cref="PlatformNotSupportedException"/> /// <param name="dfsName">The Universal Naming Convention (UNC) path of a DFS root or link.</param> /// <param name="serverName">The name of the DFS root target or link target server.</param> /// <param name="shareName">The name of the share corresponding to the DFS root target or link target.</param> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "dfs")] [SecurityCritical] public static DfsInfo GetDfsClientInfo(string dfsName, string serverName, string shareName) { return GetDfsInfoCore(true, dfsName, serverName, shareName); } #endregion // GetDfsClientInfo #region GetDfsInfo /// <summary>Gets information about a specified DFS root or link in a DFS namespace.</summary> /// <returns>A <see cref="DfsInfo"/> instance.</returns> /// <exception cref="NetworkInformationException"/> /// <exception cref="PlatformNotSupportedException"/> /// <param name="dfsName">The Universal Naming Convention (UNC) path of a DFS root or link.</param> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "dfs")] [SecurityCritical] public static DfsInfo GetDfsInfo(string dfsName) { return GetDfsInfoCore(false, dfsName, null, null); } #endregion // GetDfsInfo #region Internal Methods /// <summary>Enumerates the DFS namespaces from a host.</summary> /// <returns><see cref="IEnumerable{String}"/> of DFS Root namespaces from a host.</returns> /// <exception cref="ArgumentNullException"/> /// <exception cref="NetworkInformationException"/> /// <exception cref="PlatformNotSupportedException"/> /// <param name="host">The DNS or NetBIOS name of a host.</param> /// <param name="continueOnException"><see langword="true"/> suppress any Exception that might be thrown a result from a failure, such as unavailable resources.</param> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")] [SecurityCritical] private static IEnumerable<string> EnumerateDfsRootCore(string host, bool continueOnException) { if (!Filesystem.NativeMethods.IsAtLeastWindowsVista) throw new PlatformNotSupportedException(Resources.Requires_Windows_Vista_Or_Higher); return EnumerateNetworkObjectCore(new FunctionData(), (NativeMethods.DFS_INFO_300 structure, SafeGlobalMemoryBufferHandle buffer) => new DfsInfo { EntryPath = structure.DfsName }, (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) => { totalEntries = 0; // When host == null, the local computer is used. // However, the resulting OpenResourceInfo.Host property will be empty. // So, explicitly state Environment.MachineName to prevent this. // Furthermore, the UNC prefix: \\ is not required and always removed. string stripUnc = Utils.IsNullOrWhiteSpace(host) ? Environment.MachineName : Path.GetRegularPathCore(host, GetFullPathOptions.CheckInvalidPathChars).Replace(Path.UncPrefix, string.Empty); return NativeMethods.NetDfsEnum(stripUnc, 300, prefMaxLen, out buffer, out entriesRead, out resumeHandle); }, continueOnException).Select(dfs => dfs.EntryPath); } /// <summary>Enumerates the DFS namespaces from a domain.</summary> /// <returns><see cref="IEnumerable{String}"/> of DFS Root namespaces from a domain.</returns> /// <exception cref="ArgumentNullException"/> /// <exception cref="NetworkInformationException"/> /// <exception cref="PlatformNotSupportedException"/> /// <param name="domain">A domain name.</param> /// <param name="continueOnException"><see langword="true"/> suppress any Exception that might be thrown a result from a failure, such as unavailable resources.</param> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")] [SecurityCritical] private static IEnumerable<string> EnumerateDomainDfsRootCore(string domain, bool continueOnException) { if (!Filesystem.NativeMethods.IsAtLeastWindowsVista) throw new PlatformNotSupportedException(Resources.Requires_Windows_Vista_Or_Higher); return EnumerateNetworkObjectCore(new FunctionData(), (NativeMethods.DFS_INFO_200 structure, SafeGlobalMemoryBufferHandle buffer) => new DfsInfo { EntryPath = string.Format(CultureInfo.CurrentCulture, "{0}{1}{2}{3}", Path.UncPrefix, NativeMethods.ComputerDomain, Path.DirectorySeparatorChar, structure.FtDfsName) }, (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) => { totalEntries = 0; // When host == null, the local computer is used. // However, the resulting OpenResourceInfo.Host property will be empty. // So, explicitly state Environment.MachineName to prevent this. // Furthermore, the UNC prefix: \\ is not required and always removed. string stripUnc = Utils.IsNullOrWhiteSpace(domain) ? NativeMethods.ComputerDomain : Path.GetRegularPathCore(domain, GetFullPathOptions.CheckInvalidPathChars).Replace(Path.UncPrefix, string.Empty); return NativeMethods.NetDfsEnum(stripUnc, 200, prefMaxLen, out buffer, out entriesRead, out resumeHandle); }, continueOnException).Select(dfs => dfs.EntryPath); } /// <summary>Retrieves information about a specified DFS root or link in a DFS namespace.</summary> /// <returns>A <see cref="DfsInfo"/> instance.</returns> /// <exception cref="ArgumentNullException"/> /// <exception cref="NetworkInformationException"/> /// <exception cref="PlatformNotSupportedException"/> /// <param name="getFromClient"> /// <see langword="true"/> retrieves information about a Distributed File System (DFS) root or link from the cache maintained by the /// DFS client. When <see langword="false"/> retrieves information about a specified Distributed File System (DFS) root or link in a /// DFS namespace. /// </param> /// <param name="dfsName">The Universal Naming Convention (UNC) path of a DFS root or link.</param> /// <param name="serverName"> /// The name of the DFS root target or link target server. If <paramref name="getFromClient"/> is <see langword="false"/>, this /// parameter is always <see langword="null"/>. /// </param> /// <param name="shareName"> /// The name of the share corresponding to the DFS root target or link target. If <paramref name="getFromClient"/> is /// <see langword="false"/>, this parameter is always <see langword="null"/>. /// </param> [SecurityCritical] private static DfsInfo GetDfsInfoCore(bool getFromClient, string dfsName, string serverName, string shareName) { if (!Filesystem.NativeMethods.IsAtLeastWindowsVista) throw new PlatformNotSupportedException(Resources.Requires_Windows_Vista_Or_Higher); if (Utils.IsNullOrWhiteSpace(dfsName)) throw new ArgumentNullException("dfsName"); serverName = Utils.IsNullOrWhiteSpace(serverName) ? null : serverName; shareName = Utils.IsNullOrWhiteSpace(shareName) ? null : shareName; SafeGlobalMemoryBufferHandle safeBuffer; // Level 9 = DFS_INFO_9 uint lastError = getFromClient ? NativeMethods.NetDfsGetClientInfo(dfsName, serverName, shareName, 9, out safeBuffer) : NativeMethods.NetDfsGetInfo(dfsName, null, null, 9, out safeBuffer); if (lastError == Win32Errors.NERR_Success) return new DfsInfo(safeBuffer.PtrToStructure<NativeMethods.DFS_INFO_9>(0)); throw new NetworkInformationException((int) lastError); } #endregion // Internal Methods } }
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 SE.DSP.Pop.Web.WebHost.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(long), "integer" }, { typeof(ushort), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(ulong), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(float), "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 file="OutputStreamSourceSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Concurrent; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Akka.Actor; using Akka.IO; using Akka.Streams.Dsl; using Akka.Streams.Implementation; using Akka.Streams.Implementation.IO; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using Akka.TestKit; using Akka.Util.Internal; using FluentAssertions; using Xunit; using Xunit.Abstractions; namespace Akka.Streams.Tests.IO { public class OutputStreamSourceSpec : AkkaSpec { private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(3); private readonly ActorMaterializer _materializer; private readonly byte[] _bytesArray; private readonly ByteString _byteString; public OutputStreamSourceSpec(ITestOutputHelper helper) : base(Utils.UnboundedMailboxConfig, helper) { Sys.Settings.InjectTopLevelFallback(ActorMaterializer.DefaultConfig()); var settings = ActorMaterializerSettings.Create(Sys).WithDispatcher("akka.actor.default-dispatcher"); _materializer = Sys.Materializer(settings); _bytesArray = new[] { Convert.ToByte(new Random().Next(256)), Convert.ToByte(new Random().Next(256)), Convert.ToByte(new Random().Next(256)) }; _byteString = ByteString.FromBytes(_bytesArray); } private void ExpectTimeout(Task f, TimeSpan duration) => f.Wait(duration).Should().BeFalse(); private void ExpectSuccess<T>(Task<T> f, T value) { f.Wait(RemainingOrDefault).Should().BeTrue(); f.Result.Should().Be(value); } [Fact] public void OutputStreamSource_must_read_bytes_from_OutputStream() { this.AssertAllStagesStopped(() => { var t = StreamConverters.AsOutputStream() .ToMaterialized(this.SinkProbe<ByteString>(), Keep.Both) .Run(_materializer); var outputStream = t.Item1; var probe = t.Item2; var s = probe.ExpectSubscription(); outputStream.Write(_bytesArray, 0, _bytesArray.Length); s.Request(1); probe.ExpectNext(_byteString); outputStream.Dispose(); probe.ExpectComplete(); }, _materializer); } [Fact] public void OutputStreamSource_must_block_flush_call_until_send_all_buffer_to_downstream() { this.AssertAllStagesStopped(() => { var t = StreamConverters.AsOutputStream() .ToMaterialized(this.SinkProbe<ByteString>(), Keep.Both) .Run(_materializer); var outputStream = t.Item1; var probe = t.Item2; var s = probe.ExpectSubscription(); outputStream.Write(_bytesArray, 0, _bytesArray.Length); var f = Task.Run(() => { outputStream.Flush(); return NotUsed.Instance; }); ExpectTimeout(f, Timeout); probe.ExpectNoMsg(TimeSpan.MinValue); s.Request(1); ExpectSuccess(f, NotUsed.Instance); probe.ExpectNext(_byteString); outputStream.Dispose(); probe.ExpectComplete(); }, _materializer); } [Fact] public void OutputStreamSource_must_not_block_flushes_when_buffer_is_empty() { this.AssertAllStagesStopped(() => { var t = StreamConverters.AsOutputStream() .ToMaterialized(this.SinkProbe<ByteString>(), Keep.Both) .Run(_materializer); var outputStream = t.Item1; var probe = t.Item2; var s = probe.ExpectSubscription(); outputStream.Write(_bytesArray, 0, _byteString.Count); var f = Task.Run(() => { outputStream.Flush(); return NotUsed.Instance; }); s.Request(1); ExpectSuccess(f, NotUsed.Instance); probe.ExpectNext(_byteString); var f2 = Task.Run(() => { outputStream.Flush(); return NotUsed.Instance; }); ExpectSuccess(f2, NotUsed.Instance); outputStream.Dispose(); probe.ExpectComplete(); }, _materializer); } [Fact] public void OutputStreamSource_must_block_writes_when_buffer_is_full() { this.AssertAllStagesStopped(() => { var t = StreamConverters.AsOutputStream() .WithAttributes(Attributes.CreateInputBuffer(16, 16)) .ToMaterialized(this.SinkProbe<ByteString>(), Keep.Both) .Run(_materializer); var outputStream = t.Item1; var probe = t.Item2; var s = probe.ExpectSubscription(); for (var i = 1; i <= 16; i++) outputStream.Write(_bytesArray, 0, _byteString.Count); //blocked call var f = Task.Run(() => { outputStream.Write(_bytesArray, 0, _byteString.Count); return NotUsed.Instance; }); ExpectTimeout(f, Timeout); probe.ExpectNoMsg(TimeSpan.MinValue); s.Request(17); ExpectSuccess(f, NotUsed.Instance); probe.ExpectNextN(Enumerable.Repeat(_byteString, 17).ToList()); outputStream.Dispose(); probe.ExpectComplete(); }, _materializer); } [Fact] public void OutputStreamSource_must_throw_error_when_writer_after_stream_is_closed() { this.AssertAllStagesStopped(() => { var t = StreamConverters.AsOutputStream() .ToMaterialized(this.SinkProbe<ByteString>(), Keep.Both) .Run(_materializer); var outputStream = t.Item1; var probe = t.Item2; probe.ExpectSubscription(); outputStream.Dispose(); probe.ExpectComplete(); outputStream.Invoking(s => s.Write(_bytesArray, 0, _byteString.Count)).ShouldThrow<IOException>(); }, _materializer); } [Fact] public void OutputStreamSource_must_use_dedicated_default_blocking_io_dispatcher_by_default() { this.AssertAllStagesStopped(() => { var sys = ActorSystem.Create("dispatcher-testing", Utils.UnboundedMailboxConfig); var materializer = sys.Materializer(); try { StreamConverters.AsOutputStream().RunWith(this.SinkProbe<ByteString>(), materializer); ((ActorMaterializerImpl) materializer).Supervisor.Tell(StreamSupervisor.GetChildren.Instance, TestActor); var actorRef = ExpectMsg<StreamSupervisor.Children>() .Refs.First(c => c.Path.ToString().Contains("outputStreamSource")); Utils.AssertDispatcher(actorRef, "akka.stream.default-blocking-io-dispatcher"); } finally { Shutdown(sys); } }, _materializer); } [Fact] public void OutputStreamSource_must_throw_IOException_when_writing_to_the_stream_after_the_subscriber_has_cancelled_the_reactive_stream() { this.AssertAllStagesStopped(() => { var sourceProbe = CreateTestProbe(); var t = TestSourceStage<ByteString, Stream>.Create(new OutputStreamSourceStage(Timeout), sourceProbe) .ToMaterialized(this.SinkProbe<ByteString>(), Keep.Both) .Run(_materializer); var outputStream = t.Item1; var probe = t.Item2; var s = probe.ExpectSubscription(); outputStream.Write(_bytesArray, 0, _bytesArray.Length); s.Request(1); sourceProbe.ExpectMsg<GraphStageMessages.Pull>(); probe.ExpectNext(_byteString); s.Cancel(); sourceProbe.ExpectMsg<GraphStageMessages.DownstreamFinish>(); Thread.Sleep(500); outputStream.Invoking(os => os.Write(_bytesArray, 0, _bytesArray.Length)).ShouldThrow<IOException>(); }, _materializer); } [Fact] public void OutputStreamSource_must_fail_to_materialize_with_zero_sized_input_buffer() { new Action( () => StreamConverters.AsOutputStream(Timeout) .WithAttributes(Attributes.CreateInputBuffer(0, 0)) .RunWith(Sink.First<ByteString>(), _materializer)).ShouldThrow<ArgumentException>(); /* With Sink.First we test the code path in which the source itself throws an exception when being materialized. If Sink.Ignore is used, the same exception is thrown by Materializer. */ } [Fact] public void OutputStreamSource_must_not_leave_blocked_threads() { var tuple = StreamConverters.AsOutputStream(Timeout) .ToMaterialized(this.SinkProbe<ByteString>(), Keep.Both) .Run(_materializer); var outputStream = tuple.Item1; var probe = tuple.Item2; var sub = probe.ExpectSubscription(); // triggers a blocking read on the queue // and then cancel the stage before we got anything sub.Request(1); sub.Cancel(); //we need to make sure that the underling BlockingCollection isn't blocked after the stream has finished, //the jvm way isn't working so we need to use reflection and check the collection directly //def threadsBlocked = //ManagementFactory.getThreadMXBean.dumpAllThreads(true, true).toSeq // .filter(t => t.getThreadName.startsWith("OutputStreamSourceSpec") && //t.getLockName != null && //t.getLockName.startsWith("java.util.concurrent.locks.AbstractQueuedSynchronizer")) //awaitAssert(threadsBlocked should === (Seq()), 3.seconds) var bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static; var field = typeof(OutputStreamAdapter).GetField("_dataQueue", bindFlags); var blockingCollection = field.GetValue(outputStream) as BlockingCollection<ByteString>; //give the stage enough time to finish, otherwise it may take the hello message Thread.Sleep(1000); // if a take operation is pending inside the stage it will steal this one and the next take will not succeed blockingCollection.Add(ByteString.FromString("hello")); ByteString result; blockingCollection.TryTake(out result, TimeSpan.FromSeconds(3)).Should().BeTrue(); result.ToString().Should().Be("hello"); } [Fact] public void OutputStreamSource_must_correctly_complete_the_stage_after_close() { // actually this was a race, so it only happened in at least one of 20 runs const int bufferSize = 4; var t = StreamConverters.AsOutputStream(Timeout) .AddAttributes(Attributes.CreateInputBuffer(bufferSize, bufferSize)) .ToMaterialized(this.SinkProbe<ByteString>(), Keep.Both) .Run(_materializer); var outputStream = t.Item1; var probe = t.Item2; // fill the buffer up Enumerable.Range(1, bufferSize - 1).ForEach(i => outputStream.WriteByte((byte)i)); Task.Run(() => outputStream.Dispose()); // here is the race, has the elements reached the stage buffer yet? Thread.Sleep(500); probe.Request(bufferSize - 1); probe.ExpectNextN(bufferSize - 1); probe.ExpectComplete(); } } }
namespace MasterDetailDemo { partial class MainForm { /// <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(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); this.dataGridView = new System.Windows.Forms.DataGridView(); this.companyDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Program = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.idDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.contactNameDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.contactTitleDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.phoneDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.faxDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.addressDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.cityDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.regionDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.zipCodeDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.countryDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.bindingSource = new System.Windows.Forms.BindingSource(this.components); this.bindingNavigator = new System.Windows.Forms.BindingNavigator(this.components); this.bindingNavigatorAddNewItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorCountItem = new System.Windows.Forms.ToolStripLabel(); this.bindingNavigatorDeleteItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorMoveFirstItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorMovePreviousItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorSeparator = new System.Windows.Forms.ToolStripSeparator(); this.bindingNavigatorPositionItem = new System.Windows.Forms.ToolStripTextBox(); this.bindingNavigatorSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.bindingNavigatorMoveNextItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorMoveLastItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.splitContainer = new System.Windows.Forms.SplitContainer(); this.comboBoxProgram = new System.Windows.Forms.ComboBox(); this.label11 = new System.Windows.Forms.Label(); this.textBoxZip = new System.Windows.Forms.TextBox(); this.label10 = new System.Windows.Forms.Label(); this.textBoxState = new System.Windows.Forms.TextBox(); this.label9 = new System.Windows.Forms.Label(); this.textBoxCity = new System.Windows.Forms.TextBox(); this.label8 = new System.Windows.Forms.Label(); this.textBoxAddress = new System.Windows.Forms.TextBox(); this.label7 = new System.Windows.Forms.Label(); this.textBoxFax = new System.Windows.Forms.TextBox(); this.label6 = new System.Windows.Forms.Label(); this.textBoxPhone = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.buttonNew = new System.Windows.Forms.Button(); this.textBoxTitle = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.textBoxContact = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.textBoxId = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.textBoxCompany = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.mainMenuStrip = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.loadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.programSortToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.byRankToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.alphabeticallyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.byValueToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.programFilterToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.filterAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.filterNoneToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.filterSilverToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.filterGoldToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.filterPlatinumToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.useNewRowToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.dataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn2 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn3 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn4 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn5 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn6 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn7 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn8 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn9 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn10 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn11 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn12 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn13 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn14 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn15 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn16 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn17 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.buttonShowVisualizer = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.bindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.bindingNavigator)).BeginInit(); this.bindingNavigator.SuspendLayout(); this.splitContainer.Panel1.SuspendLayout(); this.splitContainer.Panel2.SuspendLayout(); this.splitContainer.SuspendLayout(); this.mainMenuStrip.SuspendLayout(); this.SuspendLayout(); // // dataGridView // this.dataGridView.AllowUserToAddRows = false; this.dataGridView.AutoGenerateColumns = false; this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.companyDataGridViewTextBoxColumn, this.Program, this.idDataGridViewTextBoxColumn, this.contactNameDataGridViewTextBoxColumn, this.contactTitleDataGridViewTextBoxColumn, this.phoneDataGridViewTextBoxColumn, this.faxDataGridViewTextBoxColumn, this.addressDataGridViewTextBoxColumn, this.cityDataGridViewTextBoxColumn, this.regionDataGridViewTextBoxColumn, this.zipCodeDataGridViewTextBoxColumn, this.countryDataGridViewTextBoxColumn}); this.dataGridView.DataSource = this.bindingSource; this.dataGridView.Dock = System.Windows.Forms.DockStyle.Fill; this.dataGridView.Location = new System.Drawing.Point(0, 0); this.dataGridView.Name = "dataGridView"; this.dataGridView.RowHeadersWidth = 25; this.dataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dataGridView.Size = new System.Drawing.Size(914, 276); this.dataGridView.TabIndex = 0; this.dataGridView.ColumnHeaderMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dataGridView_ColumnHeaderMouseClick); // // companyDataGridViewTextBoxColumn // this.companyDataGridViewTextBoxColumn.DataPropertyName = "Company"; this.companyDataGridViewTextBoxColumn.HeaderText = "Company"; this.companyDataGridViewTextBoxColumn.Name = "companyDataGridViewTextBoxColumn"; this.companyDataGridViewTextBoxColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; // // Program // this.Program.DataPropertyName = "Program"; this.Program.HeaderText = "Program"; this.Program.Name = "Program"; this.Program.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.Program.Width = 75; // // idDataGridViewTextBoxColumn // this.idDataGridViewTextBoxColumn.DataPropertyName = "Id"; this.idDataGridViewTextBoxColumn.HeaderText = "Id"; this.idDataGridViewTextBoxColumn.Name = "idDataGridViewTextBoxColumn"; this.idDataGridViewTextBoxColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.idDataGridViewTextBoxColumn.Width = 25; // // contactNameDataGridViewTextBoxColumn // this.contactNameDataGridViewTextBoxColumn.DataPropertyName = "ContactName"; this.contactNameDataGridViewTextBoxColumn.HeaderText = "Contact"; this.contactNameDataGridViewTextBoxColumn.Name = "contactNameDataGridViewTextBoxColumn"; this.contactNameDataGridViewTextBoxColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; // // contactTitleDataGridViewTextBoxColumn // this.contactTitleDataGridViewTextBoxColumn.DataPropertyName = "ContactTitle"; this.contactTitleDataGridViewTextBoxColumn.HeaderText = "Title"; this.contactTitleDataGridViewTextBoxColumn.Name = "contactTitleDataGridViewTextBoxColumn"; this.contactTitleDataGridViewTextBoxColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; // // phoneDataGridViewTextBoxColumn // this.phoneDataGridViewTextBoxColumn.DataPropertyName = "Phone"; this.phoneDataGridViewTextBoxColumn.HeaderText = "Phone"; this.phoneDataGridViewTextBoxColumn.Name = "phoneDataGridViewTextBoxColumn"; this.phoneDataGridViewTextBoxColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; // // faxDataGridViewTextBoxColumn // this.faxDataGridViewTextBoxColumn.DataPropertyName = "Fax"; this.faxDataGridViewTextBoxColumn.HeaderText = "Fax"; this.faxDataGridViewTextBoxColumn.Name = "faxDataGridViewTextBoxColumn"; this.faxDataGridViewTextBoxColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; // // addressDataGridViewTextBoxColumn // this.addressDataGridViewTextBoxColumn.DataPropertyName = "Address"; this.addressDataGridViewTextBoxColumn.HeaderText = "Address"; this.addressDataGridViewTextBoxColumn.Name = "addressDataGridViewTextBoxColumn"; this.addressDataGridViewTextBoxColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; // // cityDataGridViewTextBoxColumn // this.cityDataGridViewTextBoxColumn.DataPropertyName = "City"; this.cityDataGridViewTextBoxColumn.HeaderText = "City"; this.cityDataGridViewTextBoxColumn.Name = "cityDataGridViewTextBoxColumn"; this.cityDataGridViewTextBoxColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; // // regionDataGridViewTextBoxColumn // this.regionDataGridViewTextBoxColumn.DataPropertyName = "Region"; this.regionDataGridViewTextBoxColumn.HeaderText = "State"; this.regionDataGridViewTextBoxColumn.Name = "regionDataGridViewTextBoxColumn"; this.regionDataGridViewTextBoxColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.regionDataGridViewTextBoxColumn.Width = 50; // // zipCodeDataGridViewTextBoxColumn // this.zipCodeDataGridViewTextBoxColumn.DataPropertyName = "ZipCode"; this.zipCodeDataGridViewTextBoxColumn.HeaderText = "Zip"; this.zipCodeDataGridViewTextBoxColumn.Name = "zipCodeDataGridViewTextBoxColumn"; this.zipCodeDataGridViewTextBoxColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.zipCodeDataGridViewTextBoxColumn.Width = 70; // // countryDataGridViewTextBoxColumn // this.countryDataGridViewTextBoxColumn.DataPropertyName = "Country"; this.countryDataGridViewTextBoxColumn.HeaderText = "Country"; this.countryDataGridViewTextBoxColumn.Name = "countryDataGridViewTextBoxColumn"; this.countryDataGridViewTextBoxColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; // // bindingSource // this.bindingSource.DataSource = typeof(MasterDetailDemo.Customer); this.bindingSource.PositionChanged += new System.EventHandler(this.bindingSource_PositionChanged); // // bindingNavigator // this.bindingNavigator.AddNewItem = this.bindingNavigatorAddNewItem; this.bindingNavigator.BindingSource = this.bindingSource; this.bindingNavigator.CountItem = this.bindingNavigatorCountItem; this.bindingNavigator.DeleteItem = this.bindingNavigatorDeleteItem; this.bindingNavigator.Dock = System.Windows.Forms.DockStyle.Bottom; this.bindingNavigator.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.bindingNavigatorMoveFirstItem, this.bindingNavigatorMovePreviousItem, this.bindingNavigatorSeparator, this.bindingNavigatorPositionItem, this.bindingNavigatorCountItem, this.bindingNavigatorSeparator1, this.bindingNavigatorMoveNextItem, this.bindingNavigatorMoveLastItem, this.bindingNavigatorSeparator2, this.bindingNavigatorAddNewItem, this.bindingNavigatorDeleteItem}); this.bindingNavigator.Location = new System.Drawing.Point(0, 276); this.bindingNavigator.MoveFirstItem = this.bindingNavigatorMoveFirstItem; this.bindingNavigator.MoveLastItem = this.bindingNavigatorMoveLastItem; this.bindingNavigator.MoveNextItem = this.bindingNavigatorMoveNextItem; this.bindingNavigator.MovePreviousItem = this.bindingNavigatorMovePreviousItem; this.bindingNavigator.Name = "bindingNavigator"; this.bindingNavigator.PositionItem = this.bindingNavigatorPositionItem; this.bindingNavigator.Size = new System.Drawing.Size(914, 25); this.bindingNavigator.TabIndex = 1; this.bindingNavigator.Text = "bindingNavigator1"; // // bindingNavigatorAddNewItem // this.bindingNavigatorAddNewItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorAddNewItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorAddNewItem.Image"))); this.bindingNavigatorAddNewItem.Name = "bindingNavigatorAddNewItem"; this.bindingNavigatorAddNewItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorAddNewItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorAddNewItem.Text = "Add new"; // // bindingNavigatorCountItem // this.bindingNavigatorCountItem.Name = "bindingNavigatorCountItem"; this.bindingNavigatorCountItem.Size = new System.Drawing.Size(35, 22); this.bindingNavigatorCountItem.Text = "of {0}"; this.bindingNavigatorCountItem.ToolTipText = "Total number of items"; // // bindingNavigatorDeleteItem // this.bindingNavigatorDeleteItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorDeleteItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorDeleteItem.Image"))); this.bindingNavigatorDeleteItem.Name = "bindingNavigatorDeleteItem"; this.bindingNavigatorDeleteItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorDeleteItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorDeleteItem.Text = "Delete"; // // bindingNavigatorMoveFirstItem // this.bindingNavigatorMoveFirstItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorMoveFirstItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveFirstItem.Image"))); this.bindingNavigatorMoveFirstItem.Name = "bindingNavigatorMoveFirstItem"; this.bindingNavigatorMoveFirstItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorMoveFirstItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorMoveFirstItem.Text = "Move first"; // // bindingNavigatorMovePreviousItem // this.bindingNavigatorMovePreviousItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorMovePreviousItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMovePreviousItem.Image"))); this.bindingNavigatorMovePreviousItem.Name = "bindingNavigatorMovePreviousItem"; this.bindingNavigatorMovePreviousItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorMovePreviousItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorMovePreviousItem.Text = "Move previous"; // // bindingNavigatorSeparator // this.bindingNavigatorSeparator.Name = "bindingNavigatorSeparator"; this.bindingNavigatorSeparator.Size = new System.Drawing.Size(6, 25); // // bindingNavigatorPositionItem // this.bindingNavigatorPositionItem.AccessibleName = "Position"; this.bindingNavigatorPositionItem.AutoSize = false; this.bindingNavigatorPositionItem.Name = "bindingNavigatorPositionItem"; this.bindingNavigatorPositionItem.Size = new System.Drawing.Size(50, 23); this.bindingNavigatorPositionItem.Text = "0"; this.bindingNavigatorPositionItem.ToolTipText = "Current position"; // // bindingNavigatorSeparator1 // this.bindingNavigatorSeparator1.Name = "bindingNavigatorSeparator1"; this.bindingNavigatorSeparator1.Size = new System.Drawing.Size(6, 25); // // bindingNavigatorMoveNextItem // this.bindingNavigatorMoveNextItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorMoveNextItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveNextItem.Image"))); this.bindingNavigatorMoveNextItem.Name = "bindingNavigatorMoveNextItem"; this.bindingNavigatorMoveNextItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorMoveNextItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorMoveNextItem.Text = "Move next"; // // bindingNavigatorMoveLastItem // this.bindingNavigatorMoveLastItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorMoveLastItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveLastItem.Image"))); this.bindingNavigatorMoveLastItem.Name = "bindingNavigatorMoveLastItem"; this.bindingNavigatorMoveLastItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorMoveLastItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorMoveLastItem.Text = "Move last"; // // bindingNavigatorSeparator2 // this.bindingNavigatorSeparator2.Name = "bindingNavigatorSeparator2"; this.bindingNavigatorSeparator2.Size = new System.Drawing.Size(6, 25); // // splitContainer // this.splitContainer.BackColor = System.Drawing.Color.CornflowerBlue; this.splitContainer.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer.FixedPanel = System.Windows.Forms.FixedPanel.Panel1; this.splitContainer.Location = new System.Drawing.Point(0, 24); this.splitContainer.Name = "splitContainer"; this.splitContainer.Orientation = System.Windows.Forms.Orientation.Horizontal; // // splitContainer.Panel1 // this.splitContainer.Panel1.BackColor = System.Drawing.SystemColors.Control; this.splitContainer.Panel1.Controls.Add(this.buttonShowVisualizer); this.splitContainer.Panel1.Controls.Add(this.comboBoxProgram); this.splitContainer.Panel1.Controls.Add(this.label11); this.splitContainer.Panel1.Controls.Add(this.textBoxZip); this.splitContainer.Panel1.Controls.Add(this.label10); this.splitContainer.Panel1.Controls.Add(this.textBoxState); this.splitContainer.Panel1.Controls.Add(this.label9); this.splitContainer.Panel1.Controls.Add(this.textBoxCity); this.splitContainer.Panel1.Controls.Add(this.label8); this.splitContainer.Panel1.Controls.Add(this.textBoxAddress); this.splitContainer.Panel1.Controls.Add(this.label7); this.splitContainer.Panel1.Controls.Add(this.textBoxFax); this.splitContainer.Panel1.Controls.Add(this.label6); this.splitContainer.Panel1.Controls.Add(this.textBoxPhone); this.splitContainer.Panel1.Controls.Add(this.label5); this.splitContainer.Panel1.Controls.Add(this.buttonNew); this.splitContainer.Panel1.Controls.Add(this.textBoxTitle); this.splitContainer.Panel1.Controls.Add(this.label4); this.splitContainer.Panel1.Controls.Add(this.textBoxContact); this.splitContainer.Panel1.Controls.Add(this.label3); this.splitContainer.Panel1.Controls.Add(this.textBoxId); this.splitContainer.Panel1.Controls.Add(this.label2); this.splitContainer.Panel1.Controls.Add(this.textBoxCompany); this.splitContainer.Panel1.Controls.Add(this.label1); this.splitContainer.Panel1MinSize = 150; // // splitContainer.Panel2 // this.splitContainer.Panel2.BackColor = System.Drawing.SystemColors.Control; this.splitContainer.Panel2.Controls.Add(this.dataGridView); this.splitContainer.Panel2.Controls.Add(this.bindingNavigator); this.splitContainer.Size = new System.Drawing.Size(914, 477); this.splitContainer.SplitterDistance = 170; this.splitContainer.SplitterWidth = 6; this.splitContainer.TabIndex = 1; // // comboBoxProgram // this.comboBoxProgram.DataBindings.Add(new System.Windows.Forms.Binding("SelectedItem", this.bindingSource, "Program", true)); this.comboBoxProgram.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBoxProgram.FormattingEnabled = true; this.comboBoxProgram.Location = new System.Drawing.Point(384, 45); this.comboBoxProgram.Name = "comboBoxProgram"; this.comboBoxProgram.Size = new System.Drawing.Size(100, 21); this.comboBoxProgram.TabIndex = 14; // // label11 // this.label11.AutoSize = true; this.label11.Location = new System.Drawing.Point(332, 48); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(46, 13); this.label11.TabIndex = 13; this.label11.Text = "Program"; // // textBoxZip // this.textBoxZip.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bindingSource, "ZipCode", true)); this.textBoxZip.Location = new System.Drawing.Point(534, 123); this.textBoxZip.Name = "textBoxZip"; this.textBoxZip.Size = new System.Drawing.Size(100, 20); this.textBoxZip.TabIndex = 22; // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(506, 126); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(22, 13); this.label10.TabIndex = 21; this.label10.Text = "Zip"; // // textBoxState // this.textBoxState.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bindingSource, "Region", true)); this.textBoxState.Location = new System.Drawing.Point(384, 123); this.textBoxState.Name = "textBoxState"; this.textBoxState.Size = new System.Drawing.Size(100, 20); this.textBoxState.TabIndex = 20; // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(346, 126); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(32, 13); this.label9.TabIndex = 19; this.label9.Text = "State"; // // textBoxCity // this.textBoxCity.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bindingSource, "City", true)); this.textBoxCity.Location = new System.Drawing.Point(384, 97); this.textBoxCity.Name = "textBoxCity"; this.textBoxCity.Size = new System.Drawing.Size(250, 20); this.textBoxCity.TabIndex = 18; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(354, 100); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(24, 13); this.label8.TabIndex = 17; this.label8.Text = "City"; // // textBoxAddress // this.textBoxAddress.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bindingSource, "Address", true)); this.textBoxAddress.Location = new System.Drawing.Point(384, 71); this.textBoxAddress.Name = "textBoxAddress"; this.textBoxAddress.Size = new System.Drawing.Size(250, 20); this.textBoxAddress.TabIndex = 16; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(333, 74); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(45, 13); this.label7.TabIndex = 15; this.label7.Text = "Address"; // // textBoxFax // this.textBoxFax.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bindingSource, "Phone", true)); this.textBoxFax.Location = new System.Drawing.Point(219, 123); this.textBoxFax.Name = "textBoxFax"; this.textBoxFax.Size = new System.Drawing.Size(100, 20); this.textBoxFax.TabIndex = 12; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(186, 126); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(27, 13); this.label6.TabIndex = 11; this.label6.Text = "FAX"; // // textBoxPhone // this.textBoxPhone.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bindingSource, "Phone", true)); this.textBoxPhone.Location = new System.Drawing.Point(69, 123); this.textBoxPhone.Name = "textBoxPhone"; this.textBoxPhone.Size = new System.Drawing.Size(100, 20); this.textBoxPhone.TabIndex = 10; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(25, 126); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(38, 13); this.label5.TabIndex = 9; this.label5.Text = "Phone"; // // buttonNew // this.buttonNew.Location = new System.Drawing.Point(12, 9); this.buttonNew.Name = "buttonNew"; this.buttonNew.Size = new System.Drawing.Size(75, 23); this.buttonNew.TabIndex = 0; this.buttonNew.Text = "New"; this.buttonNew.UseVisualStyleBackColor = true; this.buttonNew.Click += new System.EventHandler(this.buttonNew_Click); // // textBoxTitle // this.textBoxTitle.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bindingSource, "ContactTitle", true)); this.textBoxTitle.Location = new System.Drawing.Point(69, 97); this.textBoxTitle.Name = "textBoxTitle"; this.textBoxTitle.Size = new System.Drawing.Size(250, 20); this.textBoxTitle.TabIndex = 8; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(36, 100); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(27, 13); this.label4.TabIndex = 7; this.label4.Text = "Title"; // // textBoxContact // this.textBoxContact.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bindingSource, "ContactName", true)); this.textBoxContact.Location = new System.Drawing.Point(69, 71); this.textBoxContact.Name = "textBoxContact"; this.textBoxContact.Size = new System.Drawing.Size(250, 20); this.textBoxContact.TabIndex = 6; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(19, 74); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(44, 13); this.label3.TabIndex = 5; this.label3.Text = "Contact"; // // textBoxId // this.textBoxId.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bindingSource, "Id", true)); this.textBoxId.Location = new System.Drawing.Point(270, 45); this.textBoxId.Name = "textBoxId"; this.textBoxId.Size = new System.Drawing.Size(49, 20); this.textBoxId.TabIndex = 4; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(248, 48); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(16, 13); this.label2.TabIndex = 3; this.label2.Text = "Id"; // // textBoxCompany // this.textBoxCompany.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bindingSource, "Company", true)); this.textBoxCompany.Location = new System.Drawing.Point(69, 45); this.textBoxCompany.Name = "textBoxCompany"; this.textBoxCompany.Size = new System.Drawing.Size(154, 20); this.textBoxCompany.TabIndex = 2; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(12, 48); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(51, 13); this.label1.TabIndex = 1; this.label1.Text = "Company"; // // mainMenuStrip // this.mainMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.optionsToolStripMenuItem}); this.mainMenuStrip.Location = new System.Drawing.Point(0, 0); this.mainMenuStrip.Name = "mainMenuStrip"; this.mainMenuStrip.RenderMode = System.Windows.Forms.ToolStripRenderMode.System; this.mainMenuStrip.Size = new System.Drawing.Size(914, 24); this.mainMenuStrip.TabIndex = 0; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.saveToolStripMenuItem, this.loadToolStripMenuItem, this.toolStripSeparator1, this.exitToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20); this.fileToolStripMenuItem.Text = "File"; // // saveToolStripMenuItem // this.saveToolStripMenuItem.Name = "saveToolStripMenuItem"; this.saveToolStripMenuItem.Size = new System.Drawing.Size(100, 22); this.saveToolStripMenuItem.Text = "Save"; this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click); // // loadToolStripMenuItem // this.loadToolStripMenuItem.Name = "loadToolStripMenuItem"; this.loadToolStripMenuItem.Size = new System.Drawing.Size(100, 22); this.loadToolStripMenuItem.Text = "Load"; this.loadToolStripMenuItem.Click += new System.EventHandler(this.loadToolStripMenuItem_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(97, 6); // // exitToolStripMenuItem // this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.Size = new System.Drawing.Size(100, 22); this.exitToolStripMenuItem.Text = "Exit"; this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click); // // optionsToolStripMenuItem // this.optionsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.programSortToolStripMenuItem, this.programFilterToolStripMenuItem, this.useNewRowToolStripMenuItem}); this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem"; this.optionsToolStripMenuItem.Size = new System.Drawing.Size(61, 20); this.optionsToolStripMenuItem.Text = "Options"; // // programSortToolStripMenuItem // this.programSortToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.byRankToolStripMenuItem, this.alphabeticallyToolStripMenuItem, this.byValueToolStripMenuItem}); this.programSortToolStripMenuItem.Name = "programSortToolStripMenuItem"; this.programSortToolStripMenuItem.Size = new System.Drawing.Size(152, 22); this.programSortToolStripMenuItem.Text = "Program Sort"; this.programSortToolStripMenuItem.DropDownOpening += new System.EventHandler(this.programSortToolStripMenuItem_DropDownOpening); // // byRankToolStripMenuItem // this.byRankToolStripMenuItem.Name = "byRankToolStripMenuItem"; this.byRankToolStripMenuItem.Size = new System.Drawing.Size(149, 22); this.byRankToolStripMenuItem.Text = "By Rank"; this.byRankToolStripMenuItem.Click += new System.EventHandler(this.byRankToolStripMenuItem_Click); // // alphabeticallyToolStripMenuItem // this.alphabeticallyToolStripMenuItem.Name = "alphabeticallyToolStripMenuItem"; this.alphabeticallyToolStripMenuItem.Size = new System.Drawing.Size(149, 22); this.alphabeticallyToolStripMenuItem.Text = "Alphabetically"; this.alphabeticallyToolStripMenuItem.Click += new System.EventHandler(this.alphabeticallyToolStripMenuItem_Click); // // byValueToolStripMenuItem // this.byValueToolStripMenuItem.Name = "byValueToolStripMenuItem"; this.byValueToolStripMenuItem.Size = new System.Drawing.Size(149, 22); this.byValueToolStripMenuItem.Text = "By Value"; this.byValueToolStripMenuItem.Click += new System.EventHandler(this.byValueToolStripMenuItem_Click); // // programFilterToolStripMenuItem // this.programFilterToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.filterAllToolStripMenuItem, this.toolStripSeparator2, this.filterNoneToolStripMenuItem, this.filterSilverToolStripMenuItem, this.filterGoldToolStripMenuItem, this.filterPlatinumToolStripMenuItem}); this.programFilterToolStripMenuItem.Name = "programFilterToolStripMenuItem"; this.programFilterToolStripMenuItem.Size = new System.Drawing.Size(152, 22); this.programFilterToolStripMenuItem.Text = "Program Filter"; this.programFilterToolStripMenuItem.DropDownOpening += new System.EventHandler(this.programFilterToolStripMenuItem_DropDownOpening); // // filterAllToolStripMenuItem // this.filterAllToolStripMenuItem.Name = "filterAllToolStripMenuItem"; this.filterAllToolStripMenuItem.Size = new System.Drawing.Size(126, 22); this.filterAllToolStripMenuItem.Text = "Unfiltered"; this.filterAllToolStripMenuItem.Click += new System.EventHandler(this.filterAllToolStripMenuItem_Click); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(123, 6); // // filterNoneToolStripMenuItem // this.filterNoneToolStripMenuItem.Name = "filterNoneToolStripMenuItem"; this.filterNoneToolStripMenuItem.Size = new System.Drawing.Size(126, 22); this.filterNoneToolStripMenuItem.Text = "None"; this.filterNoneToolStripMenuItem.Click += new System.EventHandler(this.filterNoneToolStripMenuItem_Click); // // filterSilverToolStripMenuItem // this.filterSilverToolStripMenuItem.Name = "filterSilverToolStripMenuItem"; this.filterSilverToolStripMenuItem.Size = new System.Drawing.Size(126, 22); this.filterSilverToolStripMenuItem.Text = "Silver"; this.filterSilverToolStripMenuItem.Click += new System.EventHandler(this.filterSilverToolStripMenuItem_Click); // // filterGoldToolStripMenuItem // this.filterGoldToolStripMenuItem.Name = "filterGoldToolStripMenuItem"; this.filterGoldToolStripMenuItem.Size = new System.Drawing.Size(126, 22); this.filterGoldToolStripMenuItem.Text = "Gold"; this.filterGoldToolStripMenuItem.Click += new System.EventHandler(this.filterGoldToolStripMenuItem_Click); // // filterPlatinumToolStripMenuItem // this.filterPlatinumToolStripMenuItem.Name = "filterPlatinumToolStripMenuItem"; this.filterPlatinumToolStripMenuItem.Size = new System.Drawing.Size(126, 22); this.filterPlatinumToolStripMenuItem.Text = "Platinum"; this.filterPlatinumToolStripMenuItem.Click += new System.EventHandler(this.filterPlatinumToolStripMenuItem_Click); // // useNewRowToolStripMenuItem // this.useNewRowToolStripMenuItem.CheckOnClick = true; this.useNewRowToolStripMenuItem.Name = "useNewRowToolStripMenuItem"; this.useNewRowToolStripMenuItem.Size = new System.Drawing.Size(152, 22); this.useNewRowToolStripMenuItem.Text = "Use New Row"; this.useNewRowToolStripMenuItem.Click += new System.EventHandler(this.useNewRowToolStripMenuItem_Click); // // dataGridViewTextBoxColumn1 // this.dataGridViewTextBoxColumn1.DataPropertyName = "Program"; this.dataGridViewTextBoxColumn1.HeaderText = "Program"; this.dataGridViewTextBoxColumn1.Name = "dataGridViewTextBoxColumn1"; this.dataGridViewTextBoxColumn1.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.dataGridViewTextBoxColumn1.Width = 50; // // dataGridViewTextBoxColumn2 // this.dataGridViewTextBoxColumn2.DataPropertyName = "Program"; this.dataGridViewTextBoxColumn2.HeaderText = "Program"; this.dataGridViewTextBoxColumn2.Name = "dataGridViewTextBoxColumn2"; this.dataGridViewTextBoxColumn2.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.dataGridViewTextBoxColumn2.Width = 50; // // dataGridViewTextBoxColumn3 // this.dataGridViewTextBoxColumn3.DataPropertyName = "Program"; this.dataGridViewTextBoxColumn3.HeaderText = "Program"; this.dataGridViewTextBoxColumn3.Name = "dataGridViewTextBoxColumn3"; this.dataGridViewTextBoxColumn3.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.dataGridViewTextBoxColumn3.Width = 50; // // dataGridViewTextBoxColumn4 // this.dataGridViewTextBoxColumn4.DataPropertyName = "Program"; this.dataGridViewTextBoxColumn4.HeaderText = "Program"; this.dataGridViewTextBoxColumn4.Name = "dataGridViewTextBoxColumn4"; this.dataGridViewTextBoxColumn4.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.dataGridViewTextBoxColumn4.Width = 50; // // dataGridViewTextBoxColumn5 // this.dataGridViewTextBoxColumn5.DataPropertyName = "Program"; this.dataGridViewTextBoxColumn5.HeaderText = "Program"; this.dataGridViewTextBoxColumn5.Name = "dataGridViewTextBoxColumn5"; this.dataGridViewTextBoxColumn5.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.dataGridViewTextBoxColumn5.Width = 50; // // dataGridViewTextBoxColumn6 // this.dataGridViewTextBoxColumn6.DataPropertyName = "Program"; this.dataGridViewTextBoxColumn6.HeaderText = "Program"; this.dataGridViewTextBoxColumn6.Name = "dataGridViewTextBoxColumn6"; this.dataGridViewTextBoxColumn6.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.dataGridViewTextBoxColumn6.Width = 50; // // dataGridViewTextBoxColumn7 // this.dataGridViewTextBoxColumn7.DataPropertyName = "Program"; this.dataGridViewTextBoxColumn7.HeaderText = "Program"; this.dataGridViewTextBoxColumn7.Name = "dataGridViewTextBoxColumn7"; this.dataGridViewTextBoxColumn7.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.dataGridViewTextBoxColumn7.Width = 50; // // dataGridViewTextBoxColumn8 // this.dataGridViewTextBoxColumn8.DataPropertyName = "Program"; this.dataGridViewTextBoxColumn8.HeaderText = "Program"; this.dataGridViewTextBoxColumn8.Name = "dataGridViewTextBoxColumn8"; this.dataGridViewTextBoxColumn8.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.dataGridViewTextBoxColumn8.Width = 50; // // dataGridViewTextBoxColumn9 // this.dataGridViewTextBoxColumn9.DataPropertyName = "Program"; this.dataGridViewTextBoxColumn9.HeaderText = "Program"; this.dataGridViewTextBoxColumn9.Name = "dataGridViewTextBoxColumn9"; this.dataGridViewTextBoxColumn9.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.dataGridViewTextBoxColumn9.Width = 50; // // dataGridViewTextBoxColumn10 // this.dataGridViewTextBoxColumn10.DataPropertyName = "Program"; this.dataGridViewTextBoxColumn10.HeaderText = "Program"; this.dataGridViewTextBoxColumn10.Name = "dataGridViewTextBoxColumn10"; this.dataGridViewTextBoxColumn10.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.dataGridViewTextBoxColumn10.Width = 50; // // dataGridViewTextBoxColumn11 // this.dataGridViewTextBoxColumn11.DataPropertyName = "Program"; this.dataGridViewTextBoxColumn11.HeaderText = "Program"; this.dataGridViewTextBoxColumn11.Name = "dataGridViewTextBoxColumn11"; this.dataGridViewTextBoxColumn11.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.dataGridViewTextBoxColumn11.Width = 50; // // dataGridViewTextBoxColumn12 // this.dataGridViewTextBoxColumn12.DataPropertyName = "Program"; this.dataGridViewTextBoxColumn12.HeaderText = "Program"; this.dataGridViewTextBoxColumn12.Name = "dataGridViewTextBoxColumn12"; this.dataGridViewTextBoxColumn12.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.dataGridViewTextBoxColumn12.Width = 50; // // dataGridViewTextBoxColumn13 // this.dataGridViewTextBoxColumn13.DataPropertyName = "Program"; this.dataGridViewTextBoxColumn13.HeaderText = "Program"; this.dataGridViewTextBoxColumn13.Name = "dataGridViewTextBoxColumn13"; this.dataGridViewTextBoxColumn13.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.dataGridViewTextBoxColumn13.Width = 50; // // dataGridViewTextBoxColumn14 // this.dataGridViewTextBoxColumn14.DataPropertyName = "Program"; this.dataGridViewTextBoxColumn14.HeaderText = "Program"; this.dataGridViewTextBoxColumn14.Name = "dataGridViewTextBoxColumn14"; this.dataGridViewTextBoxColumn14.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.dataGridViewTextBoxColumn14.Width = 75; // // dataGridViewTextBoxColumn15 // this.dataGridViewTextBoxColumn15.DataPropertyName = "Program"; this.dataGridViewTextBoxColumn15.HeaderText = "Program"; this.dataGridViewTextBoxColumn15.Name = "dataGridViewTextBoxColumn15"; this.dataGridViewTextBoxColumn15.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.dataGridViewTextBoxColumn15.Width = 75; // // dataGridViewTextBoxColumn16 // this.dataGridViewTextBoxColumn16.DataPropertyName = "Program"; this.dataGridViewTextBoxColumn16.HeaderText = "Program"; this.dataGridViewTextBoxColumn16.Name = "dataGridViewTextBoxColumn16"; this.dataGridViewTextBoxColumn16.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.dataGridViewTextBoxColumn16.Width = 75; // // dataGridViewTextBoxColumn17 // this.dataGridViewTextBoxColumn17.DataPropertyName = "Program"; this.dataGridViewTextBoxColumn17.HeaderText = "Program"; this.dataGridViewTextBoxColumn17.Name = "dataGridViewTextBoxColumn17"; this.dataGridViewTextBoxColumn17.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.dataGridViewTextBoxColumn17.Width = 75; // // buttonShowVisualizer // this.buttonShowVisualizer.Location = new System.Drawing.Point(104, 9); this.buttonShowVisualizer.Name = "buttonShowVisualizer"; this.buttonShowVisualizer.Size = new System.Drawing.Size(119, 23); this.buttonShowVisualizer.TabIndex = 23; this.buttonShowVisualizer.Text = "Show Visualizer..."; this.buttonShowVisualizer.UseVisualStyleBackColor = true; this.buttonShowVisualizer.Click += new System.EventHandler(this.buttonShowVisualizer_Click); // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(914, 501); this.Controls.Add(this.splitContainer); this.Controls.Add(this.mainMenuStrip); this.MainMenuStrip = this.mainMenuStrip; this.Name = "MainForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Master/Details Demo"; ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.bindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.bindingNavigator)).EndInit(); this.bindingNavigator.ResumeLayout(false); this.bindingNavigator.PerformLayout(); this.splitContainer.Panel1.ResumeLayout(false); this.splitContainer.Panel1.PerformLayout(); this.splitContainer.Panel2.ResumeLayout(false); this.splitContainer.Panel2.PerformLayout(); this.splitContainer.ResumeLayout(false); this.mainMenuStrip.ResumeLayout(false); this.mainMenuStrip.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.BindingSource bindingSource; private System.Windows.Forms.DataGridView dataGridView; private System.Windows.Forms.BindingNavigator bindingNavigator; private System.Windows.Forms.ToolStripButton bindingNavigatorAddNewItem; private System.Windows.Forms.ToolStripLabel bindingNavigatorCountItem; private System.Windows.Forms.ToolStripButton bindingNavigatorDeleteItem; private System.Windows.Forms.ToolStripButton bindingNavigatorMoveFirstItem; private System.Windows.Forms.ToolStripButton bindingNavigatorMovePreviousItem; private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator; private System.Windows.Forms.ToolStripTextBox bindingNavigatorPositionItem; private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator1; private System.Windows.Forms.ToolStripButton bindingNavigatorMoveNextItem; private System.Windows.Forms.ToolStripButton bindingNavigatorMoveLastItem; private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator2; private System.Windows.Forms.SplitContainer splitContainer; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox textBoxCompany; private System.Windows.Forms.MenuStrip mainMenuStrip; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem loadToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.TextBox textBoxTitle; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox textBoxContact; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox textBoxId; private System.Windows.Forms.Label label2; private System.Windows.Forms.Button buttonNew; private System.Windows.Forms.TextBox textBoxPhone; private System.Windows.Forms.Label label5; private System.Windows.Forms.TextBox textBoxAddress; private System.Windows.Forms.Label label7; private System.Windows.Forms.TextBox textBoxFax; private System.Windows.Forms.Label label6; private System.Windows.Forms.TextBox textBoxZip; private System.Windows.Forms.Label label10; private System.Windows.Forms.TextBox textBoxState; private System.Windows.Forms.Label label9; private System.Windows.Forms.TextBox textBoxCity; private System.Windows.Forms.Label label8; private System.Windows.Forms.ComboBox comboBoxProgram; private System.Windows.Forms.Label label11; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn3; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn4; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn5; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn6; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn7; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn8; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn9; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn10; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn11; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn12; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn13; private System.Windows.Forms.DataGridViewTextBoxColumn companyDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn Program; private System.Windows.Forms.DataGridViewTextBoxColumn idDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn contactNameDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn contactTitleDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn phoneDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn faxDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn addressDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn cityDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn regionDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn zipCodeDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn countryDataGridViewTextBoxColumn; private System.Windows.Forms.ToolStripMenuItem optionsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem programSortToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem byRankToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem alphabeticallyToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem byValueToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem useNewRowToolStripMenuItem; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn14; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn15; private System.Windows.Forms.ToolStripMenuItem programFilterToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem filterNoneToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripMenuItem filterSilverToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem filterGoldToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem filterPlatinumToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem filterAllToolStripMenuItem; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn16; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn17; private System.Windows.Forms.Button buttonShowVisualizer; } }
using UnityEngine; using UnityEditor; using System.Text; using System.IO; using UMA; using System.Collections.Generic; namespace UMAEditor { public class UmaSlotBuilderWindow : EditorWindow { public string slotName; public UnityEngine.Object slotFolder; public UnityEngine.Object relativeFolder; public SkinnedMeshRenderer normalReferenceMesh; public SkinnedMeshRenderer slotMesh; public UMAMaterial slotMaterial; string GetAssetFolder() { int index = slotName.LastIndexOf('/'); if( index > 0 ) { return slotName.Substring(0, index+1); } return ""; } string GetAssetName() { int index = slotName.LastIndexOf('/'); if (index > 0) { return slotName.Substring(index + 1); } return slotName; } public void EnforceFolder(ref UnityEngine.Object folderObject) { if (folderObject != null) { string destpath = AssetDatabase.GetAssetPath(folderObject); if (string.IsNullOrEmpty(destpath)) { folderObject = null; } else if (!System.IO.Directory.Exists(destpath)) { destpath = destpath.Substring(0, destpath.LastIndexOf('/')); folderObject = AssetDatabase.LoadMainAssetAtPath(destpath); } } } void OnGUI() { GUILayout.Label("UMA Slot Builder"); GUILayout.Space(20); normalReferenceMesh = EditorGUILayout.ObjectField("Seams Mesh (Optional)", normalReferenceMesh, typeof(SkinnedMeshRenderer), false) as SkinnedMeshRenderer; slotMesh = EditorGUILayout.ObjectField("Slot Mesh", slotMesh, typeof(SkinnedMeshRenderer), false) as SkinnedMeshRenderer; slotMaterial = EditorGUILayout.ObjectField("UMAMaterial", slotMaterial, typeof(UMAMaterial), false) as UMAMaterial; slotFolder = EditorGUILayout.ObjectField("Slot Destination Folder", slotFolder, typeof(UnityEngine.Object), false) as UnityEngine.Object; EnforceFolder(ref slotFolder); slotName = EditorGUILayout.TextField("Element Name", slotName); if (GUILayout.Button("Create Slot")) { Debug.Log("Processing..."); if (CreateSlot() != null) { Debug.Log("Success."); } } GUILayout.Label("", EditorStyles.boldLabel); Rect dropArea = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true)); GUI.Box(dropArea, "Drag meshes here"); GUILayout.Label("Automatic Drag and Drop processing", EditorStyles.boldLabel); relativeFolder = EditorGUILayout.ObjectField("Relative Folder", relativeFolder, typeof(UnityEngine.Object), false) as UnityEngine.Object; EnforceFolder(ref relativeFolder); DropAreaGUI(dropArea); } private SlotDataAsset CreateSlot() { if(slotName == null || slotName == ""){ Debug.LogError("slotName must be specified."); return null; } return CreateSlot_Internal(); } private SlotDataAsset CreateSlot_Internal() { var material = slotMaterial; if (slotName == null || slotName == "") { Debug.LogError("slotName must be specified."); return null; } if (material == null) { Debug.LogWarning("No UMAMaterial specified, you need to specify that later."); return null; } if (slotFolder == null) { Debug.LogError("Slot folder not supplied"); return null; } if (slotMesh == null) { Debug.LogError("Slot Mesh not supplied."); return null; } Debug.Log("Slot Mesh: " + slotMesh.name, slotMesh.gameObject); SlotDataAsset slot = UMASlotProcessingUtil.CreateSlotData(AssetDatabase.GetAssetPath(slotFolder), GetAssetFolder(), GetAssetName(), slotMesh, material, normalReferenceMesh); return slot; } private void DropAreaGUI(Rect dropArea) { var evt = Event.current; if (evt.type == EventType.DragUpdated) { if (dropArea.Contains(evt.mousePosition)) { DragAndDrop.visualMode = DragAndDropVisualMode.Copy; } } if (evt.type == EventType.DragPerform) { if (dropArea.Contains(evt.mousePosition)) { DragAndDrop.AcceptDrag(); UnityEngine.Object[] draggedObjects = DragAndDrop.objectReferences as UnityEngine.Object[]; var meshes = new HashSet<SkinnedMeshRenderer>(); for (int i = 0; i < draggedObjects.Length; i++) { RecurseObject(draggedObjects[i], meshes); } foreach(var mesh in meshes) { slotMesh = mesh; GetMaterialName(mesh.name, mesh); if (CreateSlot() != null) { Debug.Log("Batch importer processed mesh: " + slotName); } } } } } private void RecurseObject(Object obj, HashSet<SkinnedMeshRenderer> meshes) { GameObject go = obj as GameObject; if (go != null) { foreach (var smr in go.GetComponentsInChildren<SkinnedMeshRenderer>(true)) { meshes.Add(smr); } return; } var path = AssetDatabase.GetAssetPath(obj); if (!string.IsNullOrEmpty(path) && System.IO.Directory.Exists(path)) { foreach (var guid in AssetDatabase.FindAssets("t:GameObject", new string[] {path})) { RecurseObject(AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guid), typeof(GameObject)), meshes); } } } private string ProcessTextureTypeAndName(Texture2D tex) { var suffixes = new string[] { "_dif", "_spec", "_nor" }; int index = 0; foreach( var suffix in suffixes ) { index = tex.name.IndexOf(suffix, System.StringComparison.InvariantCultureIgnoreCase); if( index > 0 ) { string name = tex.name.Substring(0,index); GetMaterialName(name, tex); return suffix; } } return ""; } private void GetMaterialName(string name, UnityEngine.Object obj) { if (relativeFolder != null) { var relativeLocation = AssetDatabase.GetAssetPath(relativeFolder); var assetLocation = AssetDatabase.GetAssetPath(obj); if (assetLocation.StartsWith(relativeLocation, System.StringComparison.InvariantCultureIgnoreCase)) { string temp = assetLocation.Substring(relativeLocation.Length + 1); // remove the prefix temp = temp.Substring(0, temp.LastIndexOf('/') + 1); // remove the asset name slotName = temp + name; // add the cleaned name } } else { slotName = name; } } [MenuItem("UMA/Slot Builder")] public static void OpenUmaTexturePrepareWindow() { UmaSlotBuilderWindow window = (UmaSlotBuilderWindow)EditorWindow.GetWindow(typeof(UmaSlotBuilderWindow)); window.titleContent.text = "Slot Builder"; } } }
// Copyright (c) rubicon IT GmbH, www.rubicon.eu // // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. rubicon 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 System.Collections; using System.Reflection; using TITcs.SharePoint.Query.SharedSource.ReSharperAnnotations; using TITcs.SharePoint.Query.SharedSource.Utilities; // ReSharper disable once CheckNamespace namespace TITcs.SharePoint.Query.SharedSource.Utilities { /// <summary> /// This utility class provides methods for checking arguments. /// </summary> /// <remarks> /// Some methods of this class return the value of the parameter. In some cases, this is useful because the value will be converted to another /// type: /// <code><![CDATA[ /// void foo (object o) /// { /// int i = ArgumentUtility.CheckNotNullAndType<int> ("o", o); /// } /// ]]></code> /// In some other cases, the input value is returned unmodified. This makes it easier to use the argument checks in calls to base class constructors /// or property setters: /// <code><![CDATA[ /// class MyType : MyBaseType /// { /// public MyType (string name) : base (ArgumentUtility.CheckNotNullOrEmpty ("name", name)) /// { /// } /// /// public override Name /// { /// set { base.Name = ArgumentUtility.CheckNotNullOrEmpty ("value", value); } /// } /// } /// ]]></code> /// </remarks> static partial class ArgumentUtility { // Duplicated in Remotion.Linq.Utilities.ArgumentUtility [AssertionMethod] public static T CheckNotNull<T> ( [InvokerParameterName] string argumentName, [AssertionCondition (AssertionConditionType.IS_NOT_NULL)] [NoEnumeration] T actualValue) { // ReSharper disable CompareNonConstrainedGenericWithNull if (actualValue == null) // ReSharper restore CompareNonConstrainedGenericWithNull throw new ArgumentNullException (argumentName); return actualValue; } // Duplicated in Remotion.Linq.Utilities.ArgumentUtility [AssertionMethod] public static string CheckNotNullOrEmpty ( [InvokerParameterName] string argumentName, [AssertionCondition (AssertionConditionType.IS_NOT_NULL)] string actualValue) { CheckNotNull (argumentName, actualValue); if (actualValue.Length == 0) throw CreateArgumentEmptyException (argumentName); return actualValue; } [AssertionMethod] public static T CheckNotNullOrEmpty<T> ( [InvokerParameterName] string argumentName, [AssertionCondition (AssertionConditionType.IS_NOT_NULL)] T enumerable) where T: IEnumerable { CheckNotNull (argumentName, enumerable); CheckNotEmpty (argumentName, enumerable); return enumerable; } [AssertionMethod] public static T CheckNotNullOrItemsNull<T> ( [InvokerParameterName] string argumentName, [AssertionCondition (AssertionConditionType.IS_NOT_NULL)] T enumerable) where T: IEnumerable { CheckNotNull (argumentName, enumerable); int i = 0; foreach (object item in enumerable) { if (item == null) throw CreateArgumentItemNullException (argumentName, i); ++i; } return enumerable; } [AssertionMethod] public static T CheckNotNullOrEmptyOrItemsNull<T> ( [InvokerParameterName] string argumentName, [AssertionCondition (AssertionConditionType.IS_NOT_NULL)] T enumerable) where T: IEnumerable { CheckNotNullOrItemsNull (argumentName, enumerable); CheckNotEmpty (argumentName, enumerable); return enumerable; } [AssertionMethod] public static string CheckNotEmpty ([InvokerParameterName] string argumentName, string actualValue) { if (actualValue != null && actualValue.Length == 0) throw CreateArgumentEmptyException (argumentName); return actualValue; } [AssertionMethod] public static T CheckNotEmpty<T> ([InvokerParameterName] string argumentName, T enumerable) where T: IEnumerable { // ReSharper disable CompareNonConstrainedGenericWithNull if (enumerable != null) // ReSharper restore CompareNonConstrainedGenericWithNull { var collection = enumerable as ICollection; if (collection != null) { if (collection.Count == 0) throw CreateArgumentEmptyException (argumentName); else return enumerable; } IEnumerator enumerator = enumerable.GetEnumerator(); var disposableEnumerator = enumerator as IDisposable; using (disposableEnumerator) // using (null) is allowed in C# { if (!enumerator.MoveNext()) throw CreateArgumentEmptyException (argumentName); } } return enumerable; } [AssertionMethod] public static Guid CheckNotEmpty ([InvokerParameterName] string argumentName, Guid actualValue) { if (actualValue == Guid.Empty) throw CreateArgumentEmptyException (argumentName); return actualValue; } public static object CheckNotNullAndType ( [InvokerParameterName] string argumentName, [AssertionCondition (AssertionConditionType.IS_NOT_NULL)] [NoEnumeration] object actualValue, Type expectedType) { if (actualValue == null) throw new ArgumentNullException (argumentName); // ReSharper disable UseMethodIsInstanceOfType if (!expectedType.GetTypeInfo().IsAssignableFrom (actualValue.GetType().GetTypeInfo())) throw CreateArgumentTypeException (argumentName, actualValue.GetType(), expectedType); // ReSharper restore UseMethodIsInstanceOfType return actualValue; } ///// <summary>Returns the value itself if it is not <see langword="null"/> and of the specified value type.</summary> ///// <typeparam name="TExpected"> The type that <paramref name="actualValue"/> must have. </typeparam> ///// <exception cref="ArgumentNullException"> <paramref name="actualValue"/> is <see langword="null"/>.</exception> ///// <exception cref="ArgumentException"> <paramref name="actualValue"/> is an instance of another type (which is not a subclass of <typeparamref name="TExpected"/>).</exception> //public static TExpected CheckNotNullAndType<TExpected> (string argumentName, object actualValue) // where TExpected: class //{ // if (actualValue == null) // throw new ArgumentNullException (argumentName); // return CheckType<TExpected> (argumentName, actualValue); //} /// <summary>Returns the value itself if it is not <see langword="null"/> and of the specified value type.</summary> /// <typeparam name="TExpected"> The type that <paramref name="actualValue"/> must have. </typeparam> /// <exception cref="ArgumentNullException">The <paramref name="actualValue"/> is a <see langword="null"/>.</exception> /// <exception cref="ArgumentException">The <paramref name="actualValue"/> is an instance of another type.</exception> // Duplicated in Remotion.Linq.Utilities.ArgumentUtility public static TExpected CheckNotNullAndType<TExpected> ( [InvokerParameterName] string argumentName, [AssertionCondition (AssertionConditionType.IS_NOT_NULL)] [NoEnumeration] object actualValue) // where TExpected: struct { if (actualValue == null) throw new ArgumentNullException (argumentName); if (! (actualValue is TExpected)) throw CreateArgumentTypeException (argumentName, actualValue.GetType(), typeof (TExpected)); return (TExpected) actualValue; } public static object CheckType ([InvokerParameterName] string argumentName, [NoEnumeration] object actualValue, Type expectedType) { if (actualValue == null) { if (NullableTypeUtility.IsNullableType_NoArgumentCheck (expectedType)) return null; else throw CreateArgumentTypeException (argumentName, null, expectedType); } // ReSharper disable UseMethodIsInstanceOfType if (!expectedType.GetTypeInfo().IsAssignableFrom (actualValue.GetType().GetTypeInfo())) throw CreateArgumentTypeException (argumentName, actualValue.GetType(), expectedType); // ReSharper restore UseMethodIsInstanceOfType return actualValue; } /// <summary>Returns the value itself if it is of the specified type.</summary> /// <typeparam name="TExpected"> The type that <paramref name="actualValue"/> must have. </typeparam> /// <exception cref="ArgumentException"> /// <paramref name="actualValue"/> is an instance of another type (which is not a subtype of <typeparamref name="TExpected"/>).</exception> /// <exception cref="ArgumentNullException"> /// <paramref name="actualValue" /> is null and <typeparamref name="TExpected"/> cannot be null. </exception> /// <remarks> /// For non-nullable value types, you should use either <see cref="CheckNotNullAndType{TExpected}"/> or pass the type /// <see cref="Nullable{T}" /> instead. /// </remarks> public static TExpected CheckType<TExpected> ([InvokerParameterName] string argumentName, [NoEnumeration] object actualValue) { if (actualValue == null) { try { return (TExpected) actualValue; } catch (NullReferenceException) { throw new ArgumentNullException (argumentName); } } if (!(actualValue is TExpected)) throw CreateArgumentTypeException (argumentName, actualValue.GetType(), typeof (TExpected)); return (TExpected) actualValue; } /// <summary>Checks whether <paramref name="actualType"/> is not <see langword="null"/> and can be assigned to <paramref name="expectedType"/>.</summary> /// <exception cref="ArgumentNullException">The <paramref name="actualType"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentException">The <paramref name="actualType"/> cannot be assigned to <paramref name="expectedType"/>.</exception> public static Type CheckNotNullAndTypeIsAssignableFrom ( [InvokerParameterName] string argumentName, [AssertionCondition (AssertionConditionType.IS_NOT_NULL)] Type actualType, [AssertionCondition (AssertionConditionType.IS_NOT_NULL)] Type expectedType) { if (actualType == null) throw new ArgumentNullException (argumentName); return CheckTypeIsAssignableFrom (argumentName, actualType, expectedType); } /// <summary>Checks whether <paramref name="actualType"/> can be assigned to <paramref name="expectedType"/>.</summary> /// <exception cref="ArgumentException">The <paramref name="actualType"/> cannot be assigned to <paramref name="expectedType"/>.</exception> // Duplicated in Remotion.Linq.Utilities.ArgumentUtility public static Type CheckTypeIsAssignableFrom ( [InvokerParameterName] string argumentName, Type actualType, [AssertionCondition (AssertionConditionType.IS_NOT_NULL)] Type expectedType) { CheckNotNull ("expectedType", expectedType); if (actualType != null) { if (!expectedType.GetTypeInfo().IsAssignableFrom (actualType.GetTypeInfo())) { string message = string.Format ( "Parameter '{0}' is a '{2}', which cannot be assigned to type '{1}'.", argumentName, expectedType, actualType); throw new ArgumentException (message, argumentName); } } return actualType; } /// <summary>Checks whether all items in <paramref name="collection"/> are of type <paramref name="itemType"/> or a null reference.</summary> /// <exception cref="ArgumentException"> If at least one element is not of the specified type or a derived type. </exception> public static T CheckItemsType<T> ([InvokerParameterName] string argumentName, T collection, Type itemType) where T: ICollection { // ReSharper disable CompareNonConstrainedGenericWithNull if (collection != null) // ReSharper restore CompareNonConstrainedGenericWithNull { int index = 0; foreach (object item in collection) { // ReSharper disable UseMethodIsInstanceOfType if (item != null && !itemType.GetTypeInfo().IsAssignableFrom (item.GetType().GetTypeInfo())) throw CreateArgumentItemTypeException (argumentName, index, itemType, item.GetType()); // ReSharper restore UseMethodIsInstanceOfType ++index; } } return collection; } /// <summary>Checks whether all items in <paramref name="collection"/> are of type <paramref name="itemType"/> and not null references.</summary> /// <exception cref="ArgumentException"> If at least one element is not of the specified type or a derived type. </exception> /// <exception cref="ArgumentNullException"> If at least one element is a null reference. </exception> public static T CheckItemsNotNullAndType<T> ([InvokerParameterName] string argumentName, T collection, Type itemType) where T: ICollection { // ReSharper disable CompareNonConstrainedGenericWithNull if (collection != null) // ReSharper restore CompareNonConstrainedGenericWithNull { int index = 0; foreach (object item in collection) { if (item == null) throw CreateArgumentItemNullException (argumentName, index); // ReSharper disable UseMethodIsInstanceOfType if (!itemType.GetTypeInfo().IsAssignableFrom (item.GetType().GetTypeInfo())) throw CreateArgumentItemTypeException (argumentName, index, itemType, item.GetType()); // ReSharper restore UseMethodIsInstanceOfType ++index; } } return collection; } public static ArgumentException CreateArgumentEmptyException ([InvokerParameterName] string argumentName) { return new ArgumentException (string.Format("Parameter '{0}' cannot be empty.", argumentName), argumentName); } public static ArgumentException CreateArgumentTypeException ([InvokerParameterName] string argumentName, Type actualType, Type expectedType) { string actualTypeName = actualType != null ? actualType.ToString() : "<null>"; if (expectedType == null) { return new ArgumentException (string.Format ("Parameter '{0}' has unexpected type '{1}'.", argumentName, actualTypeName), argumentName); } else { return new ArgumentException ( string.Format ("Parameter '{0}' has type '{2}' when type '{1}' was expected.", argumentName, expectedType, actualTypeName), argumentName); } } public static ArgumentException CreateArgumentItemTypeException ( [InvokerParameterName] string argumentName, int index, Type expectedType, Type actualType) { return new ArgumentException ( string.Format ( "Item {0} of parameter '{1}' has the type '{2}' instead of '{3}'.", index, argumentName, actualType, expectedType), argumentName); } public static ArgumentNullException CreateArgumentItemNullException ([InvokerParameterName] string argumentName, int index) { return new ArgumentNullException (argumentName, string.Format ("Item {0} of parameter '{1}' is null.", index, argumentName)); } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Concurrent; using System.Collections.Generic; using ASC.Common.DependencyInjection; using Autofac; using log4net.Config; using log4net.Core; using NLog; namespace ASC.Common.Logging { public interface ILog { bool IsDebugEnabled { get; } bool IsInfoEnabled { get; } bool IsWarnEnabled { get; } bool IsErrorEnabled { get; } bool IsFatalEnabled { get; } bool IsTraceEnabled { get; } void Trace(object message); void TraceFormat(string message, object arg0); void DebugWithProps(string message, params KeyValuePair<string, object>[] props); void Debug(object message); void Debug(object message, Exception exception); void DebugFormat(string format, params object[] args); void DebugFormat(string format, object arg0); void DebugFormat(string format, object arg0, object arg1); void DebugFormat(string format, object arg0, object arg1, object arg2); void DebugFormat(IFormatProvider provider, string format, params object[] args); void Info(object message); void Info(string message, Exception exception); void InfoFormat(string format, params object[] args); void InfoFormat(string format, object arg0); void InfoFormat(string format, object arg0, object arg1); void InfoFormat(string format, object arg0, object arg1, object arg2); void InfoFormat(IFormatProvider provider, string format, params object[] args); void Warn(object message); void Warn(object message, Exception exception); void WarnFormat(string format, params object[] args); void WarnFormat(string format, object arg0); void WarnFormat(string format, object arg0, object arg1); void WarnFormat(string format, object arg0, object arg1, object arg2); void WarnFormat(IFormatProvider provider, string format, params object[] args); void Error(object message); void Error(object message, Exception exception); void ErrorFormat(string format, params object[] args); void ErrorFormat(string format, object arg0); void ErrorFormat(string format, object arg0, object arg1); void ErrorFormat(string format, object arg0, object arg1, object arg2); void ErrorFormat(IFormatProvider provider, string format, params object[] args); void Fatal(object message); void Fatal(string message, Exception exception); void FatalFormat(string format, params object[] args); void FatalFormat(string format, object arg0); void FatalFormat(string format, object arg0, object arg1); void FatalFormat(string format, object arg0, object arg1, object arg2); void FatalFormat(IFormatProvider provider, string format, params object[] args); string LogDirectory { get; } } public class Log : ILog { static Log() { XmlConfigurator.Configure(); } private readonly log4net.ILog loger; public bool IsDebugEnabled { get; private set; } public bool IsInfoEnabled { get; private set; } public bool IsWarnEnabled { get; private set; } public bool IsErrorEnabled { get; private set; } public bool IsFatalEnabled { get; private set; } public bool IsTraceEnabled { get; private set; } public Log(string name) { loger = log4net.LogManager.GetLogger(name); IsDebugEnabled = loger.IsDebugEnabled; IsInfoEnabled = loger.IsInfoEnabled; IsWarnEnabled = loger.IsWarnEnabled; IsErrorEnabled = loger.IsErrorEnabled; IsFatalEnabled = loger.IsFatalEnabled; IsTraceEnabled = loger.Logger.IsEnabledFor(Level.Trace); } public void Trace(object message) { if (IsTraceEnabled) loger.Logger.Log(GetType(), Level.Trace, message, null); } public void TraceFormat(string message, object arg0) { if (IsTraceEnabled) loger.Logger.Log(GetType(), Level.Trace, string.Format(message, arg0), null); } public void Debug(object message) { if (IsDebugEnabled) loger.Debug(message); } public void Debug(object message, Exception exception) { if (IsDebugEnabled) loger.Debug(message, exception); } public void DebugFormat(string format, params object[] args) { if (IsDebugEnabled) loger.DebugFormat(format, args); } public void DebugFormat(string format, object arg0) { if (IsDebugEnabled) loger.DebugFormat(format, arg0); } public void DebugFormat(string format, object arg0, object arg1) { if (IsDebugEnabled) loger.DebugFormat(format, arg0, arg1); } public void DebugFormat(string format, object arg0, object arg1, object arg2) { if (IsDebugEnabled) loger.DebugFormat(format, arg0, arg1, arg2); } public void DebugFormat(IFormatProvider provider, string format, params object[] args) { if (IsDebugEnabled) loger.DebugFormat(provider, format, args); } public void DebugWithProps(string message, params KeyValuePair<string, object>[] props) { if (!IsDebugEnabled) return; foreach (var p in props) { log4net.ThreadContext.Properties[p.Key] = p.Value; } loger.Debug(message); } public void Info(object message) { if (IsInfoEnabled) loger.Info(message); } public void Info(string message, Exception exception) { if (IsInfoEnabled) loger.Info(message, exception); } public void InfoFormat(string format, params object[] args) { if (IsInfoEnabled) loger.InfoFormat(format, args); } public void InfoFormat(string format, object arg0) { if (IsInfoEnabled) loger.InfoFormat(format, arg0); } public void InfoFormat(string format, object arg0, object arg1) { if (IsInfoEnabled) loger.InfoFormat(format, arg0, arg1); } public void InfoFormat(string format, object arg0, object arg1, object arg2) { if (IsInfoEnabled) loger.InfoFormat(format, arg0, arg1, arg2); } public void InfoFormat(IFormatProvider provider, string format, params object[] args) { if (IsInfoEnabled) loger.InfoFormat(provider, format, args); } public void Warn(object message) { if (IsWarnEnabled) loger.Warn(message); } public void Warn(object message, Exception exception) { if (IsWarnEnabled) loger.Warn(message, exception); } public void WarnFormat(string format, params object[] args) { if (IsWarnEnabled) loger.WarnFormat(format, args); } public void WarnFormat(string format, object arg0) { if (IsWarnEnabled) loger.WarnFormat(format, arg0); } public void WarnFormat(string format, object arg0, object arg1) { if (IsWarnEnabled) loger.WarnFormat(format, arg0, arg1); } public void WarnFormat(string format, object arg0, object arg1, object arg2) { if (IsWarnEnabled) loger.WarnFormat(format, arg0, arg1, arg2); } public void WarnFormat(IFormatProvider provider, string format, params object[] args) { if (IsWarnEnabled) loger.WarnFormat(provider, format, args); } public void Error(object message) { if (IsErrorEnabled) loger.Error(message); } public void Error(object message, Exception exception) { if (IsErrorEnabled) loger.Error(message, exception); } public void ErrorFormat(string format, params object[] args) { if (IsErrorEnabled) loger.ErrorFormat(format, args); } public void ErrorFormat(string format, object arg0) { if (IsErrorEnabled) loger.ErrorFormat(format, arg0); } public void ErrorFormat(string format, object arg0, object arg1) { if (IsErrorEnabled) loger.ErrorFormat(format, arg0, arg1); } public void ErrorFormat(string format, object arg0, object arg1, object arg2) { if (IsErrorEnabled) loger.ErrorFormat(format, arg0, arg1, arg2); } public void ErrorFormat(IFormatProvider provider, string format, params object[] args) { if (IsErrorEnabled) loger.ErrorFormat(provider, format, args); } public void Fatal(object message) { if (IsFatalEnabled) loger.Fatal(message); } public void Fatal(string message, Exception exception) { if (IsFatalEnabled) loger.Fatal(message, exception); } public void FatalFormat(string format, params object[] args) { if (IsFatalEnabled) loger.FatalFormat(format, args); } public void FatalFormat(string format, object arg0) { if (IsFatalEnabled) loger.FatalFormat(format, arg0); } public void FatalFormat(string format, object arg0, object arg1) { if (IsFatalEnabled) loger.FatalFormat(format, arg0, arg1); } public void FatalFormat(string format, object arg0, object arg1, object arg2) { if (IsFatalEnabled) loger.FatalFormat(format, arg0, arg1, arg2); } public void FatalFormat(IFormatProvider provider, string format, params object[] args) { if (IsFatalEnabled) loger.FatalFormat(provider, format, args); } public string LogDirectory { get { return log4net.GlobalContext.Properties["LogDirectory"].ToString(); } } } public class LogNLog : ILog { private readonly NLog.ILogger loger; private readonly string name; public bool IsDebugEnabled { get; private set; } public bool IsInfoEnabled { get; private set; } public bool IsWarnEnabled { get; private set; } public bool IsErrorEnabled { get; private set; } public bool IsFatalEnabled { get; private set; } public bool IsTraceEnabled { get; private set; } static LogNLog() { var args = Environment.GetCommandLineArgs(); for (var i = 0; i < args.Length; i++) { if (args[i] == "--log" && !string.IsNullOrEmpty(args[i + 1])) { NLog.LogManager.Configuration.Variables["svcName"] = args[i + 1].Trim().Trim('"'); } } NLog.Targets.Target.Register<SelfCleaningTarget>("SelfCleaning"); } public LogNLog(string name) { this.name = name; loger = NLog.LogManager.GetLogger(name); IsDebugEnabled = loger.IsDebugEnabled; IsInfoEnabled = loger.IsInfoEnabled; IsWarnEnabled = loger.IsWarnEnabled; IsErrorEnabled = loger.IsErrorEnabled; IsFatalEnabled = loger.IsFatalEnabled; IsTraceEnabled = loger.IsEnabled(LogLevel.Trace); } public void Trace(object message) { if (IsTraceEnabled) loger.Log(LogLevel.Trace, message); } public void TraceFormat(string message, object arg0) { if (IsTraceEnabled) loger.Log(LogLevel.Trace, string.Format(message, arg0)); } public void Debug(object message) { if (IsDebugEnabled) loger.Debug(message); } public void Debug(object message, Exception exception) { if (IsDebugEnabled) loger.Debug(exception, "{0}", message); } public void DebugFormat(string format, params object[] args) { if (IsDebugEnabled) loger.Debug(format, args); } public void DebugFormat(string format, object arg0) { if (IsDebugEnabled) loger.Debug(format, arg0); } public void DebugFormat(string format, object arg0, object arg1) { if (IsDebugEnabled) loger.Debug(format, arg0, arg1); } public void DebugFormat(string format, object arg0, object arg1, object arg2) { if (IsDebugEnabled) loger.Debug(format, arg0, arg1, arg2); } public void DebugFormat(IFormatProvider provider, string format, params object[] args) { if (IsDebugEnabled) loger.Debug(provider, format, args); } public void DebugWithProps(string message, params KeyValuePair<string, object>[] props) { if (!IsDebugEnabled) return; var theEvent = new LogEventInfo { Message = message, LoggerName = name, Level = LogLevel.Debug }; foreach (var p in props) { theEvent.Properties[p.Key] = p.Value; } loger.Log(theEvent); } public void Info(object message) { if (IsInfoEnabled) loger.Info(message); } public void Info(string message, Exception exception) { if (IsInfoEnabled) loger.Info(exception, message); } public void InfoFormat(string format, params object[] args) { if (IsInfoEnabled) loger.Info(format, args); } public void InfoFormat(string format, object arg0) { if (IsInfoEnabled) loger.Info(format, arg0); } public void InfoFormat(string format, object arg0, object arg1) { if (IsInfoEnabled) loger.Info(format, arg0, arg1); } public void InfoFormat(string format, object arg0, object arg1, object arg2) { if (IsInfoEnabled) loger.Info(format, arg0, arg1, arg2); } public void InfoFormat(IFormatProvider provider, string format, params object[] args) { if (IsInfoEnabled) loger.Info(provider, format, args); } public void Warn(object message) { if (IsWarnEnabled) loger.Warn(message); } public void Warn(object message, Exception exception) { if (IsWarnEnabled) loger.Warn(exception, "{0}", message); } public void WarnFormat(string format, params object[] args) { if (IsWarnEnabled) loger.Warn(format, args); } public void WarnFormat(string format, object arg0) { if (IsWarnEnabled) loger.Warn(format, arg0); } public void WarnFormat(string format, object arg0, object arg1) { if (IsWarnEnabled) loger.Warn(format, arg0, arg1); } public void WarnFormat(string format, object arg0, object arg1, object arg2) { if (IsWarnEnabled) loger.Warn(format, arg0, arg1, arg2); } public void WarnFormat(IFormatProvider provider, string format, params object[] args) { if (IsWarnEnabled) loger.Warn(provider, format, args); } public void Error(object message) { if (IsErrorEnabled) loger.Error(message); } public void Error(object message, Exception exception) { if (IsErrorEnabled) loger.Error(exception, "{0}", message); } public void ErrorFormat(string format, params object[] args) { if (IsErrorEnabled) loger.Error(format, args); } public void ErrorFormat(string format, object arg0) { if (IsErrorEnabled) loger.Error(format, arg0); } public void ErrorFormat(string format, object arg0, object arg1) { if (IsErrorEnabled) loger.Error(format, arg0, arg1); } public void ErrorFormat(string format, object arg0, object arg1, object arg2) { if (IsErrorEnabled) loger.Error(format, arg0, arg1, arg2); } public void ErrorFormat(IFormatProvider provider, string format, params object[] args) { if (IsErrorEnabled) loger.Error(provider, format, args); } public void Fatal(object message) { if (IsFatalEnabled) loger.Fatal(message); } public void Fatal(string message, Exception exception) { if (IsFatalEnabled) loger.Fatal(exception, message); } public void FatalFormat(string format, params object[] args) { if (IsFatalEnabled) loger.Fatal(format, args); } public void FatalFormat(string format, object arg0) { if (IsFatalEnabled) loger.Fatal(format, arg0); } public void FatalFormat(string format, object arg0, object arg1) { if (IsFatalEnabled) loger.Fatal(format, arg0, arg1); } public void FatalFormat(string format, object arg0, object arg1, object arg2) { if (IsFatalEnabled) loger.Fatal(format, arg0, arg1, arg2); } public void FatalFormat(IFormatProvider provider, string format, params object[] args) { if (IsFatalEnabled) loger.Fatal(provider, format, args); } public string LogDirectory { get { return NLog.LogManager.Configuration.Variables["logDirectory"].Text; } } } public class NullLog : ILog { public bool IsDebugEnabled { get; set; } public bool IsInfoEnabled { get; set; } public bool IsWarnEnabled { get; set; } public bool IsErrorEnabled { get; set; } public bool IsFatalEnabled { get; set; } public bool IsTraceEnabled { get; set; } public void Trace(object message) { } public void TraceFormat(string message, object arg0) { } public void DebugWithProps(string message, params KeyValuePair<string, object>[] props) { } public void Debug(object message) { } public void Debug(object message, Exception exception) { } public void DebugFormat(string format, params object[] args) { } public void DebugFormat(string format, object arg0) { } public void DebugFormat(string format, object arg0, object arg1) { } public void DebugFormat(string format, object arg0, object arg1, object arg2) { } public void DebugFormat(IFormatProvider provider, string format, params object[] args) { } public void Info(object message) { } public void Info(string message, Exception exception) { } public void InfoFormat(string format, params object[] args) { } public void InfoFormat(string format, object arg0) { } public void InfoFormat(string format, object arg0, object arg1) { } public void InfoFormat(string format, object arg0, object arg1, object arg2) { } public void InfoFormat(IFormatProvider provider, string format, params object[] args) { } public void Warn(object message) { } public void Warn(object message, Exception exception) { } public void WarnFormat(string format, params object[] args) { } public void WarnFormat(string format, object arg0) { } public void WarnFormat(string format, object arg0, object arg1) { } public void WarnFormat(string format, object arg0, object arg1, object arg2) { } public void WarnFormat(IFormatProvider provider, string format, params object[] args) { } public void Error(object message) { } public void Error(object message, Exception exception) { } public void ErrorFormat(string format, params object[] args) { } public void ErrorFormat(string format, object arg0) { } public void ErrorFormat(string format, object arg0, object arg1) { } public void ErrorFormat(string format, object arg0, object arg1, object arg2) { } public void ErrorFormat(IFormatProvider provider, string format, params object[] args) { } public void Fatal(object message) { } public void Fatal(string message, Exception exception) { } public void FatalFormat(string format, params object[] args) { } public void FatalFormat(string format, object arg0) { } public void FatalFormat(string format, object arg0, object arg1) { } public void FatalFormat(string format, object arg0, object arg1, object arg2) { } public void FatalFormat(IFormatProvider provider, string format, params object[] args) { } public string LogDirectory { get { return ""; } } } public class LogManager { internal static IContainer Builder { get; set; } internal static ConcurrentDictionary<string, ILog> Logs; static LogManager() { var container = AutofacConfigLoader.Load("core"); if (container != null) { Builder = container.Build(); } Logs = new ConcurrentDictionary<string, ILog>(); } public static ILog GetLogger(string name) { ILog result; if (!Logs.TryGetValue(name, out result)) { result = Logs.AddOrUpdate(name, Builder != null ? Builder.Resolve<ILog>(new TypedParameter(typeof(string), name)) : new NullLog(), (k, v) => v); } return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Globalization; /// <summary> /// String.System.IConvertible.ToInt64(IFormatProvider provider) /// This method supports the .NET Framework infrastructure and is /// not intended to be used directly from your code. /// Converts the value of the current String object to a 32-bit signed integer. /// </summary> class IConvertibleToInt64 { private const int c_MIN_STRING_LEN = 8; private const int c_MAX_STRING_LEN = 256; public static int Main() { IConvertibleToInt64 iege = new IConvertibleToInt64(); TestLibrary.TestFramework.BeginTestCase("for method: String.System.IConvertible.ToInt64(IFormatProvider)"); if (iege.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } #region Positive test scenarioes public bool PosTest1() { bool retVal = true; const string c_TEST_DESC = "PosTest1: Random numeric string"; const string c_TEST_ID = "P001"; string strSrc; IFormatProvider provider; Int64 i; bool expectedValue = true; bool actualValue = false; i = TestLibrary.Generator.GetInt64(-55); strSrc = i.ToString(); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = (i == ((IConvertible)strSrc).ToInt64(provider)); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(strSrc, provider); TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_DESC = "PosTest2: Positive sign"; const string c_TEST_ID = "P002"; string strSrc; IFormatProvider provider; NumberFormatInfo ni = new NumberFormatInfo(); Int64 i; bool expectedValue = true; bool actualValue = false; i = TestLibrary.Generator.GetInt64(-55); ni.PositiveSign = TestLibrary.Generator.GetString(-55, false,false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); strSrc = ni.PositiveSign + i.ToString(); provider = (IFormatProvider)ni; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = (i == ((IConvertible)strSrc).ToInt64(provider)); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(strSrc, provider); TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; const string c_TEST_DESC = "PosTest3: string is Int64.MaxValue"; const string c_TEST_ID = "P003"; string strSrc; IFormatProvider provider; bool expectedValue = true; bool actualValue = false; strSrc = Int64.MaxValue.ToString(); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = (Int64.MaxValue == ((IConvertible)strSrc).ToInt64(provider)); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(strSrc, provider); TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; const string c_TEST_DESC = "PosTest4: string is Int32.MinValue"; const string c_TEST_ID = "P004"; string strSrc; IFormatProvider provider; bool expectedValue = true; bool actualValue = false; strSrc = Int64.MinValue.ToString(); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = (Int64.MinValue == ((IConvertible)strSrc).ToInt64(provider)); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(strSrc, provider); TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; const string c_TEST_DESC = "PosTest5: Positive sign"; const string c_TEST_ID = "P005"; string strSrc; IFormatProvider provider; NumberFormatInfo ni = new NumberFormatInfo(); Int64 i; bool expectedValue = true; bool actualValue = false; i = TestLibrary.Generator.GetInt64(-55); ni.NegativeSign = TestLibrary.Generator.GetString(-55, false,false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); strSrc = ni.NegativeSign + i.ToString(); provider = (IFormatProvider)ni; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = ((-1 * i) == ((IConvertible)strSrc).ToInt64(provider)); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(strSrc, provider); TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } #endregion // end for positive test scenarioes #region Negative test scenarios //FormatException public bool NegTest1() { bool retVal = true; const string c_TEST_DESC = "NegTest1: The value of String object cannot be parsed"; const string c_TEST_ID = "N001"; string strSrc; IFormatProvider provider; strSrc = "p" + TestLibrary.Generator.GetString(-55, false, 9, c_MAX_STRING_LEN); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((IConvertible)strSrc).ToInt64(provider); TestLibrary.TestFramework.LogError("011" + "TestId-" + c_TEST_ID, "FormatException is not thrown as expected" + GetDataString(strSrc, provider)); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("012" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool NegTest2() //bug { bool retVal = true; const string c_TEST_DESC = "NegTest2: The value of String object is a number greater than MaxValue"; const string c_TEST_ID = "N002"; string strSrc; IFormatProvider provider; Int64 i; i = TestLibrary.Generator.GetInt64(-55); strSrc = Int64.MaxValue.ToString() + i.ToString(); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((IConvertible)strSrc).ToInt64(provider); TestLibrary.TestFramework.LogError("013" + "TestId-" + c_TEST_ID, "OverflowException is not thrown as expected" + GetDataString(strSrc, provider)); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("014" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool NegTest3() //bug { bool retVal = true; const string c_TEST_DESC = "NegTest3: The value of String object is a number less than MinValue"; const string c_TEST_ID = "N003"; string strSrc; NumberFormatInfo ni = new NumberFormatInfo(); IFormatProvider provider; Int64 i; i = TestLibrary.Generator.GetInt64(-55); strSrc = ni.NegativeSign + Int64.MaxValue + i.ToString(); provider = (IFormatProvider)ni; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((IConvertible)strSrc).ToInt64(provider); TestLibrary.TestFramework.LogError("015" + "TestId-" + c_TEST_ID, "OverflowException is not thrown as expected" + GetDataString(strSrc, provider)); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("016" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } #endregion private string GetDataString(string strSrc, IFormatProvider provider) { string str1, str2, str; int len1; if (null == strSrc) { str1 = "null"; len1 = 0; } else { str1 = strSrc; len1 = strSrc.Length; } str2 = (null == provider) ? "null" : provider.ToString(); str = string.Format("\n[Source string value]\n \"{0}\"", str1); str += string.Format("\n[Length of source string]\n {0}", len1); str += string.Format("\n[Format provider string]\n {0}", str2); return str; } }
// 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.Threading; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Navigation; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TaskList { internal class VisualStudioTaskItemBase<T> : IVsErrorItem, IVsTaskItem where T : class, ITaskItem { protected readonly VSTASKCATEGORY ItemCategory; internal readonly T Info; protected VisualStudioTaskItemBase(VSTASKCATEGORY category, T taskItem) { this.ItemCategory = category; this.Info = taskItem; } protected ContainedDocument GetContainedDocumentFromWorkspace() { var visualStudioWorkspace = this.Info.Workspace as VisualStudioWorkspaceImpl; if (visualStudioWorkspace == null) { return null; } return visualStudioWorkspace.GetHostDocument(this.Info.DocumentId) as ContainedDocument; } /// <summary> /// Gets the display location of the tasklist item. This is the same as the navigation /// location except for Venus which must have their original /// unmapped line numbers mapped through its buffer coordinator. /// </summary> protected VsTextSpan GetDisplayLocation() { var containedDocument = GetContainedDocumentFromWorkspace(); if (containedDocument != null) { var displayLocation = new VsTextSpan() { iStartLine = this.Info.OriginalLine, iStartIndex = this.Info.OriginalColumn, iEndLine = this.Info.OriginalLine, iEndIndex = this.Info.OriginalColumn }; var containedLanguage = containedDocument.ContainedLanguage; var bufferCoordinator = containedLanguage.BufferCoordinator; var containedLanguageHost = containedLanguage.ContainedLanguageHost; var mappedLocation = new VsTextSpan[1]; if (VSConstants.S_OK == bufferCoordinator.MapSecondaryToPrimarySpan(displayLocation, mappedLocation)) { return mappedLocation[0]; } else if (containedLanguageHost != null && VSConstants.S_OK == containedLanguageHost.GetNearestVisibleToken(displayLocation, mappedLocation)) { return mappedLocation[0]; } } return GetMappedLocation(); } /// <summary> /// Gets the location to be used when navigating to the item. This is the same /// as the display location except for Venus which must use their /// original unmapped location as the navigation location so that it can be /// translated correctly during navigation. /// </summary> protected VsTextSpan GetNavigationLocation() { var containedDocument = GetContainedDocumentFromWorkspace(); if (containedDocument != null) { return new VsTextSpan() { iStartLine = this.Info.OriginalLine, iStartIndex = this.Info.OriginalColumn, iEndLine = this.Info.OriginalLine, iEndIndex = this.Info.OriginalColumn }; } return GetMappedLocation(); } private VsTextSpan GetMappedLocation() { if (this.Info.DocumentId != null) { return new VsTextSpan { iStartLine = this.Info.MappedLine, iStartIndex = this.Info.MappedColumn, iEndLine = this.Info.MappedLine, iEndIndex = this.Info.MappedColumn }; } return new VsTextSpan(); } public override bool Equals(object obj) { return Equals(obj as VisualStudioTaskItemBase<T>); } protected bool Equals(VisualStudioTaskItemBase<T> other) { if (this == other) { return true; } if (this.Info == other.Info) { return true; } if (this.Info.DocumentId != null && other.Info.DocumentId != null) { return this.ItemCategory == other.ItemCategory && this.Info.DocumentId == other.Info.DocumentId && this.Info.Message == other.Info.Message && this.Info.OriginalColumn == other.Info.OriginalColumn && this.Info.OriginalLine == other.Info.OriginalLine && this.Info.MappedColumn == other.Info.MappedColumn && this.Info.MappedLine == other.Info.MappedLine && this.Info.MappedFilePath == other.Info.MappedFilePath; } return this.ItemCategory == other.ItemCategory && this.Info.DocumentId == other.Info.DocumentId && this.Info.Message == other.Info.Message && this.Info.MappedFilePath == other.Info.MappedFilePath; } public override int GetHashCode() { if (this.Info.DocumentId != null) { return Hash.Combine((int)this.ItemCategory, Hash.Combine(this.Info.DocumentId, Hash.Combine(this.Info.Message, Hash.Combine(this.Info.MappedFilePath, Hash.Combine(this.Info.OriginalColumn, Hash.Combine(this.Info.OriginalLine, Hash.Combine(this.Info.MappedColumn, Hash.Combine(this.Info.MappedLine, 0)))))))); } return Hash.Combine((int)this.ItemCategory, Hash.Combine(this.Info.DocumentId, Hash.Combine(this.Info.Message, Hash.Combine(this.Info.MappedFilePath, 0)))); } public virtual int CanDelete(out int pfCanDelete) { pfCanDelete = 0; return VSConstants.S_OK; } public virtual int GetCategory(out uint pCategory) { pCategory = (uint)TaskErrorCategory.Error; return VSConstants.S_OK; } public virtual int ImageListIndex(out int pIndex) { pIndex = (int)_vstaskbitmap.BMP_COMPILE; return VSConstants.E_NOTIMPL; } public virtual int IsReadOnly(VSTASKFIELD field, out int pfReadOnly) { pfReadOnly = 1; return VSConstants.S_OK; } public virtual int HasHelp(out int pfHasHelp) { pfHasHelp = 0; return VSConstants.S_OK; } public virtual int GetHierarchy(out IVsHierarchy ppProject) { ppProject = null; return VSConstants.S_OK; } public virtual int NavigateToHelp() { return VSConstants.E_NOTIMPL; } public virtual int OnDeleteTask() { return VSConstants.E_NOTIMPL; } public virtual int OnFilterTask(int fVisible) { return VSConstants.E_NOTIMPL; } protected virtual int GetChecked(out int pfChecked) { pfChecked = 0; return VSConstants.S_OK; } protected virtual int GetPriority(VSTASKPRIORITY[] ptpPriority) { if (ptpPriority != null) { ptpPriority[0] = VSTASKPRIORITY.TP_NORMAL; } return VSConstants.S_OK; } protected virtual int PutChecked(int fChecked) { return VSConstants.E_NOTIMPL; } protected virtual int PutPriority(VSTASKPRIORITY tpPriority) { return VSConstants.E_NOTIMPL; } protected virtual int PutText(string bstrName) { return VSConstants.E_NOTIMPL; } public virtual int SubcategoryIndex(out int pIndex) { pIndex = 0; return VSConstants.E_NOTIMPL; } public int Category(VSTASKCATEGORY[] pCat) { if (pCat != null) { pCat[0] = ItemCategory; } return VSConstants.S_OK; } public int Line(out int line) { if (this.Info.DocumentId == null) { line = 0; return VSConstants.E_NOTIMPL; } var displayLocation = this.GetDisplayLocation(); line = displayLocation.iStartLine; return VSConstants.S_OK; } public int Column(out int column) { if (this.Info.DocumentId == null) { column = 0; return VSConstants.E_NOTIMPL; } var displayLocation = this.GetDisplayLocation(); column = displayLocation.iStartIndex; return VSConstants.S_OK; } public int Document(out string documentPath) { if (this.Info.DocumentId == null) { documentPath = null; return VSConstants.E_NOTIMPL; } // // TODO (bug 904049): the path may be relative and should to be resolved with OriginalFilePath as its base documentPath = this.Info.MappedFilePath; return VSConstants.S_OK; } public int NavigateTo() { using (Logger.LogBlock(FunctionId.TaskList_NavigateTo, CancellationToken.None)) { if (this.Info.DocumentId == null) { // Some items do not have a location in a document return VSConstants.E_NOTIMPL; } // TODO (bug 904049): We should not navigate to the documentId if diagnosticItem.MappedFilePath is available. // We should find the corresponding document if it exists. var workspace = this.Info.Workspace; var documentId = this.Info.DocumentId; var document = workspace.CurrentSolution.GetDocument(documentId); if (document == null) { // document could be already removed from the solution return VSConstants.E_NOTIMPL; } var navigationService = workspace.Services.GetService<IDocumentNavigationService>(); var navigationLocation = this.GetNavigationLocation(); navigationService.TryNavigateToLineAndOffset( workspace, documentId, navigationLocation.iStartLine, navigationLocation.iStartIndex); return VSConstants.S_OK; } } // use explicit interface to workaround style cop complaints int IVsTaskItem.get_Text(out string text) { text = this.Info.Message; return VSConstants.S_OK; } int IVsTaskItem.get_Checked(out int pfChecked) { return GetChecked(out pfChecked); } int IVsTaskItem.get_Priority(VSTASKPRIORITY[] ptpPriority) { return GetPriority(ptpPriority); } int IVsTaskItem.put_Checked(int fChecked) { return PutChecked(fChecked); } int IVsTaskItem.put_Priority(VSTASKPRIORITY tpPriority) { return PutPriority(tpPriority); } int IVsTaskItem.put_Text(string bstrName) { return PutText(bstrName); } } }
// 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.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Graphics; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Online.API.Requests.Responses; using osu.Game.Overlays.Settings; using osu.Game.Tournament.Components; using osu.Game.Tournament.Models; using osuTK; namespace osu.Game.Tournament.Screens.Editors { public class RoundEditorScreen : TournamentEditorScreen<RoundEditorScreen.RoundRow, TournamentRound> { protected override BindableList<TournamentRound> Storage => LadderInfo.Rounds; public class RoundRow : CompositeDrawable, IModelBacked<TournamentRound> { public TournamentRound Model { get; } [Resolved] private LadderInfo ladderInfo { get; set; } public RoundRow(TournamentRound round) { Model = round; Masking = true; CornerRadius = 10; RoundBeatmapEditor beatmapEditor = new RoundBeatmapEditor(round) { Width = 0.95f }; InternalChildren = new Drawable[] { new Box { Colour = OsuColour.Gray(0.1f), RelativeSizeAxes = Axes.Both, }, new FillFlowContainer { Margin = new MarginPadding(5), Padding = new MarginPadding { Right = 160 }, Spacing = new Vector2(5), Direction = FillDirection.Full, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Children = new Drawable[] { new SettingsTextBox { LabelText = "Name", Width = 0.33f, Current = Model.Name }, new SettingsTextBox { LabelText = "Description", Width = 0.33f, Current = Model.Description }, new DateTextBox { LabelText = "Start Time", Width = 0.33f, Current = Model.StartDate }, new SettingsSlider<int> { LabelText = "Best of", Width = 0.33f, Current = Model.BestOf }, new SettingsButton { Width = 0.2f, Margin = new MarginPadding(10), Text = "Add beatmap", Action = () => beatmapEditor.CreateNew() }, beatmapEditor } }, new DangerousSettingsButton { Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, RelativeSizeAxes = Axes.None, Width = 150, Text = "Delete Round", Action = () => { Expire(); ladderInfo.Rounds.Remove(Model); }, } }; RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; } public class RoundBeatmapEditor : CompositeDrawable { private readonly TournamentRound round; private readonly FillFlowContainer flow; public RoundBeatmapEditor(TournamentRound round) { this.round = round; RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; InternalChild = flow = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, ChildrenEnumerable = round.Beatmaps.Select(p => new RoundBeatmapRow(round, p)) }; } public void CreateNew() { var user = new RoundBeatmap(); round.Beatmaps.Add(user); flow.Add(new RoundBeatmapRow(round, user)); } public class RoundBeatmapRow : CompositeDrawable { public RoundBeatmap Model { get; } [Resolved] protected IAPIProvider API { get; private set; } private readonly Bindable<int?> beatmapId = new Bindable<int?>(); private readonly Bindable<string> mods = new Bindable<string>(string.Empty); private readonly Container drawableContainer; public RoundBeatmapRow(TournamentRound team, RoundBeatmap beatmap) { Model = beatmap; Margin = new MarginPadding(10); RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; Masking = true; CornerRadius = 5; InternalChildren = new Drawable[] { new Box { Colour = OsuColour.Gray(0.2f), RelativeSizeAxes = Axes.Both, }, new FillFlowContainer { Margin = new MarginPadding(5), Padding = new MarginPadding { Right = 160 }, Spacing = new Vector2(5), Direction = FillDirection.Horizontal, AutoSizeAxes = Axes.Both, Children = new Drawable[] { new SettingsNumberBox { LabelText = "Beatmap ID", RelativeSizeAxes = Axes.None, Width = 200, Current = beatmapId, }, new SettingsTextBox { LabelText = "Mods", RelativeSizeAxes = Axes.None, Width = 200, Current = mods, }, drawableContainer = new Container { Size = new Vector2(100, 70), }, } }, new DangerousSettingsButton { Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, RelativeSizeAxes = Axes.None, Width = 150, Text = "Delete Beatmap", Action = () => { Expire(); team.Beatmaps.Remove(beatmap); }, } }; } [BackgroundDependencyLoader] private void load() { beatmapId.Value = Model.ID; beatmapId.BindValueChanged(id => { Model.ID = id.NewValue ?? 0; if (id.NewValue != id.OldValue) Model.Beatmap = null; if (Model.Beatmap != null) { updatePanel(); return; } var req = new GetBeatmapRequest(new APIBeatmap { OnlineID = Model.ID }); req.Success += res => { Model.Beatmap = res; updatePanel(); }; req.Failure += _ => { Model.Beatmap = null; updatePanel(); }; API.Queue(req); }, true); mods.Value = Model.Mods; mods.BindValueChanged(modString => Model.Mods = modString.NewValue); } private void updatePanel() { drawableContainer.Clear(); if (Model.Beatmap != null) { drawableContainer.Child = new TournamentBeatmapPanel(Model.Beatmap, Model.Mods) { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Width = 300 }; } } } } } protected override RoundRow CreateDrawable(TournamentRound model) => new RoundRow(model); } }
using System; using System.Text; using System.Collections.Generic; namespace Configuration { //TODO: Vielleicht durch http://visitmix.com/writings/the-rise-of-json ersetzen public class JSON { public JSON() { } public delegate T inputConverter<T>(string str, ref int pos); public static string write(string[] arr) { StringBuilder res = new StringBuilder(); int i, j, len; string str; bool first = true; res.Append("[ "); for (i=0; i<arr.Length; i++) { if (arr[i] == null) { continue; } if (!first) { first = false; res.Append(", "); } res.Append('"'); str = arr[i]; len = str.Length; for (j=0; j<len; j++) { switch (str[j]) { case '\n': res.Append("\\n"); break; case '\r': res.Append("\\r"); break; case '\t': res.Append("\\t"); break; case '"': res.Append("\\\""); break; case '\\': res.Append("\\\\"); break; default: res.Append(str[j]); break; } } res.Append('"'); } res.Append(" ]"); return res.ToString(); } public static string write(int[] arr) { StringBuilder res = new StringBuilder(); int i; res.Append("[ "); for (i=0; i<arr.Length; i++) { if (i != 0) { res.Append(", "); } res.Append(arr[i]); } res.Append(" ]"); return res.ToString(); } // reading public static string readString(string str) { int pos = 0; return readString(str, ref pos); } public static string readString(string str, ref int pos) { StringBuilder res; int len = str.Length; bool escape = false; res = new StringBuilder(); // skip space while (pos < len && (str[pos] == ' ' || str[pos] == '\t')) { pos++; } // end? if (pos < len) { // correct start of the string? if (str[pos] != '"') { throw new InvalidCastException("incorrect JSON string"); } pos++; while (pos < len && (escape || str[pos] != '"')) { if (escape) { switch (str[pos]) { case 'n': res.Append('\n'); break; case 'r': res.Append('\r'); break; case 't': res.Append('\t'); break; default: res.Append(str[pos]); break; } escape = false; } else { switch (str[pos]) { case '\\': escape = true; break; default: res.Append(str[pos]); break; } } pos++; } // correct end of the string? (pev. loop ends at string end or '"') if (pos >= len) { throw new InvalidCastException("incorrect JSON string array"); } pos++; return res.ToString(); } throw new InvalidCastException("no JSON string found"); } public static int readInt(string str) { int pos = 0; return readInt(str, ref pos); } public static int readInt(string str, ref int pos) { int number = 0; int len = str.Length; // skip space while (pos < len && (str[pos] == ' ' || str[pos] == '\t')) { pos++; } if (pos > len || str[pos] < '0' || str[pos] > '9') { throw new InvalidCastException("not a JSON int '"+str[pos]+"'("+pos+")"); } while (pos < len && str[pos] >= '0' && str[pos] <= '9') { number *= 10; number += str[pos] - '0'; pos++; } return number; } public static T[] readArray<T>(string str, inputConverter<T> reader) { int pos = 0; return readArray<T>(str, ref pos, reader); } public static T[] readArray<T>(string str, ref int pos, inputConverter<T> reader) { int len = str.Length; List<T> res; // skip space while (pos < len && (str[pos] == ' ' || str[pos] == '\t')) { pos++; } if (pos < len && str[pos] == '[') { res = new List<T>(); pos++; // skip initial space while (pos < len && (str[pos] == ' ' || str[pos] == '\t')) { pos++; } while (true) { if (str[pos] != ']') { res.Add(reader(str, ref pos)); // skip space while (pos < len && (str[pos] == ' ' || str[pos] == '\t')) { pos++; } // check correckt string seperator if (pos >= len || (str[pos] != ',' && str[pos] != ']')) { throw new InvalidCastException("incorrect JSON array"); } } if (str[pos] == ']') { return res.ToArray(); } pos++; } } else { throw new InvalidCastException("incorrect JSON array"); } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management.Compute; using Microsoft.WindowsAzure.Management.Compute.Models; namespace Microsoft.WindowsAzure.Management.Compute { /// <summary> /// The Service Management API includes operations for managing the OS /// images in your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157175.aspx for /// more information) /// </summary> internal partial class VirtualMachineImageOperations : IServiceOperations<ComputeManagementClient>, IVirtualMachineImageOperations { /// <summary> /// Initializes a new instance of the VirtualMachineImageOperations /// class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal VirtualMachineImageOperations(ComputeManagementClient client) { this._client = client; } private ComputeManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Compute.ComputeManagementClient. /// </summary> public ComputeManagementClient Client { get { return this._client; } } /// <summary> /// The Add OS Image operation adds an operating system image that is /// stored in a storage account and is available from the image /// repository. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157192.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Parameters supplied to the Create Virtual Machine Image operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Parameters returned from the Create Virtual Machine Image operation. /// </returns> public async Task<VirtualMachineImageCreateResponse> CreateAsync(VirtualMachineImageCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Label == null) { throw new ArgumentNullException("parameters.Label"); } if (parameters.MediaLinkUri == null) { throw new ArgumentNullException("parameters.MediaLinkUri"); } if (parameters.Name == null) { throw new ArgumentNullException("parameters.Name"); } if (parameters.OperatingSystemType == null) { throw new ArgumentNullException("parameters.OperatingSystemType"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "CreateAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/images"; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-11-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement oSImageElement = new XElement(XName.Get("OSImage", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(oSImageElement); XElement labelElement = new XElement(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); labelElement.Value = parameters.Label; oSImageElement.Add(labelElement); XElement mediaLinkElement = new XElement(XName.Get("MediaLink", "http://schemas.microsoft.com/windowsazure")); mediaLinkElement.Value = parameters.MediaLinkUri.ToString(); oSImageElement.Add(mediaLinkElement); XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); nameElement.Value = parameters.Name; oSImageElement.Add(nameElement); XElement osElement = new XElement(XName.Get("OS", "http://schemas.microsoft.com/windowsazure")); osElement.Value = parameters.OperatingSystemType; oSImageElement.Add(osElement); if (parameters.Eula != null) { XElement eulaElement = new XElement(XName.Get("Eula", "http://schemas.microsoft.com/windowsazure")); eulaElement.Value = parameters.Eula; oSImageElement.Add(eulaElement); } if (parameters.Description != null) { XElement descriptionElement = new XElement(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); descriptionElement.Value = parameters.Description; oSImageElement.Add(descriptionElement); } if (parameters.ImageFamily != null) { XElement imageFamilyElement = new XElement(XName.Get("ImageFamily", "http://schemas.microsoft.com/windowsazure")); imageFamilyElement.Value = parameters.ImageFamily; oSImageElement.Add(imageFamilyElement); } if (parameters.PublishedDate != null) { XElement publishedDateElement = new XElement(XName.Get("PublishedDate", "http://schemas.microsoft.com/windowsazure")); publishedDateElement.Value = string.Format(CultureInfo.InvariantCulture, "{0:O}", parameters.PublishedDate.Value.ToUniversalTime()); oSImageElement.Add(publishedDateElement); } XElement isPremiumElement = new XElement(XName.Get("IsPremium", "http://schemas.microsoft.com/windowsazure")); isPremiumElement.Value = parameters.IsPremium.ToString().ToLower(); oSImageElement.Add(isPremiumElement); XElement showInGuiElement = new XElement(XName.Get("ShowInGui", "http://schemas.microsoft.com/windowsazure")); showInGuiElement.Value = parameters.ShowInGui.ToString().ToLower(); oSImageElement.Add(showInGuiElement); if (parameters.PrivacyUri != null) { XElement privacyUriElement = new XElement(XName.Get("PrivacyUri", "http://schemas.microsoft.com/windowsazure")); privacyUriElement.Value = parameters.PrivacyUri.ToString(); oSImageElement.Add(privacyUriElement); } if (parameters.IconUri != null) { XElement iconUriElement = new XElement(XName.Get("IconUri", "http://schemas.microsoft.com/windowsazure")); iconUriElement.Value = parameters.IconUri.ToString(); oSImageElement.Add(iconUriElement); } if (parameters.RecommendedVMSize != null) { XElement recommendedVMSizeElement = new XElement(XName.Get("RecommendedVMSize", "http://schemas.microsoft.com/windowsazure")); recommendedVMSizeElement.Value = parameters.RecommendedVMSize; oSImageElement.Add(recommendedVMSizeElement); } if (parameters.SmallIconUri != null) { XElement smallIconUriElement = new XElement(XName.Get("SmallIconUri", "http://schemas.microsoft.com/windowsazure")); smallIconUriElement.Value = parameters.SmallIconUri.ToString(); oSImageElement.Add(smallIconUriElement); } if (parameters.Language != null) { XElement languageElement = new XElement(XName.Get("Language", "http://schemas.microsoft.com/windowsazure")); languageElement.Value = parameters.Language; oSImageElement.Add(languageElement); } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result VirtualMachineImageCreateResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new VirtualMachineImageCreateResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement oSImageElement2 = responseDoc.Element(XName.Get("OSImage", "http://schemas.microsoft.com/windowsazure")); if (oSImageElement2 != null) { XElement locationElement = oSImageElement2.Element(XName.Get("Location", "http://schemas.microsoft.com/windowsazure")); if (locationElement != null) { string locationInstance = locationElement.Value; result.Location = locationInstance; } XElement categoryElement = oSImageElement2.Element(XName.Get("Category", "http://schemas.microsoft.com/windowsazure")); if (categoryElement != null) { string categoryInstance = categoryElement.Value; result.Category = categoryInstance; } XElement labelElement2 = oSImageElement2.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); if (labelElement2 != null) { string labelInstance = labelElement2.Value; result.Label = labelInstance; } XElement logicalSizeInGBElement = oSImageElement2.Element(XName.Get("LogicalSizeInGB", "http://schemas.microsoft.com/windowsazure")); if (logicalSizeInGBElement != null) { double logicalSizeInGBInstance = double.Parse(logicalSizeInGBElement.Value, CultureInfo.InvariantCulture); result.LogicalSizeInGB = logicalSizeInGBInstance; } XElement mediaLinkElement2 = oSImageElement2.Element(XName.Get("MediaLink", "http://schemas.microsoft.com/windowsazure")); if (mediaLinkElement2 != null) { Uri mediaLinkInstance = TypeConversion.TryParseUri(mediaLinkElement2.Value); result.MediaLinkUri = mediaLinkInstance; } XElement nameElement2 = oSImageElement2.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement2 != null) { string nameInstance = nameElement2.Value; result.Name = nameInstance; } XElement osElement2 = oSImageElement2.Element(XName.Get("OS", "http://schemas.microsoft.com/windowsazure")); if (osElement2 != null) { string osInstance = osElement2.Value; result.OperatingSystemType = osInstance; } XElement eulaElement2 = oSImageElement2.Element(XName.Get("Eula", "http://schemas.microsoft.com/windowsazure")); if (eulaElement2 != null) { string eulaInstance = eulaElement2.Value; result.Eula = eulaInstance; } XElement descriptionElement2 = oSImageElement2.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); if (descriptionElement2 != null) { string descriptionInstance = descriptionElement2.Value; result.Description = descriptionInstance; } XElement imageFamilyElement2 = oSImageElement2.Element(XName.Get("ImageFamily", "http://schemas.microsoft.com/windowsazure")); if (imageFamilyElement2 != null) { string imageFamilyInstance = imageFamilyElement2.Value; result.ImageFamily = imageFamilyInstance; } XElement publishedDateElement2 = oSImageElement2.Element(XName.Get("PublishedDate", "http://schemas.microsoft.com/windowsazure")); if (publishedDateElement2 != null && string.IsNullOrEmpty(publishedDateElement2.Value) == false) { DateTime publishedDateInstance = DateTime.Parse(publishedDateElement2.Value, CultureInfo.InvariantCulture); result.PublishedDate = publishedDateInstance; } XElement publisherNameElement = oSImageElement2.Element(XName.Get("PublisherName", "http://schemas.microsoft.com/windowsazure")); if (publisherNameElement != null) { string publisherNameInstance = publisherNameElement.Value; result.PublisherName = publisherNameInstance; } XElement isPremiumElement2 = oSImageElement2.Element(XName.Get("IsPremium", "http://schemas.microsoft.com/windowsazure")); if (isPremiumElement2 != null && string.IsNullOrEmpty(isPremiumElement2.Value) == false) { bool isPremiumInstance = bool.Parse(isPremiumElement2.Value); result.IsPremium = isPremiumInstance; } XElement showInGuiElement2 = oSImageElement2.Element(XName.Get("ShowInGui", "http://schemas.microsoft.com/windowsazure")); if (showInGuiElement2 != null && string.IsNullOrEmpty(showInGuiElement2.Value) == false) { bool showInGuiInstance = bool.Parse(showInGuiElement2.Value); result.ShowInGui = showInGuiInstance; } XElement privacyUriElement2 = oSImageElement2.Element(XName.Get("PrivacyUri", "http://schemas.microsoft.com/windowsazure")); if (privacyUriElement2 != null) { Uri privacyUriInstance = TypeConversion.TryParseUri(privacyUriElement2.Value); result.PrivacyUri = privacyUriInstance; } XElement iconUriElement2 = oSImageElement2.Element(XName.Get("IconUri", "http://schemas.microsoft.com/windowsazure")); if (iconUriElement2 != null) { Uri iconUriInstance = TypeConversion.TryParseUri(iconUriElement2.Value); result.IconUri = iconUriInstance; } XElement recommendedVMSizeElement2 = oSImageElement2.Element(XName.Get("RecommendedVMSize", "http://schemas.microsoft.com/windowsazure")); if (recommendedVMSizeElement2 != null) { string recommendedVMSizeInstance = recommendedVMSizeElement2.Value; result.RecommendedVMSize = recommendedVMSizeInstance; } XElement smallIconUriElement2 = oSImageElement2.Element(XName.Get("SmallIconUri", "http://schemas.microsoft.com/windowsazure")); if (smallIconUriElement2 != null) { Uri smallIconUriInstance = TypeConversion.TryParseUri(smallIconUriElement2.Value); result.SmallIconUri = smallIconUriInstance; } XElement languageElement2 = oSImageElement2.Element(XName.Get("Language", "http://schemas.microsoft.com/windowsazure")); if (languageElement2 != null) { string languageInstance = languageElement2.Value; result.Language = languageInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Delete OS Image operation deletes the specified OS image from /// your image repository. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157203.aspx /// for more information) /// </summary> /// <param name='imageName'> /// The name of the image to delete. /// </param> /// <param name='deleteFromStorage'> /// Optional. Specifies that the source blob for the image should also /// be deleted from storage. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<OperationResponse> DeleteAsync(string imageName, bool deleteFromStorage, CancellationToken cancellationToken) { // Validate if (imageName == null) { throw new ArgumentNullException("imageName"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("imageName", imageName); tracingParameters.Add("deleteFromStorage", deleteFromStorage); Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/images/" + imageName + "?"; if (deleteFromStorage == true) { url = url + "&comp=" + Uri.EscapeUriString("media"); } // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-11-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationResponse result = null; result = new OperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Get OS Image operation retrieves the details for an operating /// system image from the image repository. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157191.aspx /// for more information) /// </summary> /// <param name='imageName'> /// The name of the OS image to retrieve. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A virtual machine image associated with your subscription. /// </returns> public async Task<VirtualMachineImageGetResponse> GetAsync(string imageName, CancellationToken cancellationToken) { // Validate if (imageName == null) { throw new ArgumentNullException("imageName"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("imageName", imageName); Tracing.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/images/" + imageName; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-11-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result VirtualMachineImageGetResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new VirtualMachineImageGetResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement oSImageElement = responseDoc.Element(XName.Get("OSImage", "http://schemas.microsoft.com/windowsazure")); if (oSImageElement != null) { XElement affinityGroupElement = oSImageElement.Element(XName.Get("AffinityGroup", "http://schemas.microsoft.com/windowsazure")); if (affinityGroupElement != null) { string affinityGroupInstance = affinityGroupElement.Value; result.AffinityGroup = affinityGroupInstance; } XElement categoryElement = oSImageElement.Element(XName.Get("Category", "http://schemas.microsoft.com/windowsazure")); if (categoryElement != null) { string categoryInstance = categoryElement.Value; result.Category = categoryInstance; } XElement labelElement = oSImageElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); if (labelElement != null) { string labelInstance = labelElement.Value; result.Label = labelInstance; } XElement locationElement = oSImageElement.Element(XName.Get("Location", "http://schemas.microsoft.com/windowsazure")); if (locationElement != null) { string locationInstance = locationElement.Value; result.Location = locationInstance; } XElement logicalSizeInGBElement = oSImageElement.Element(XName.Get("LogicalSizeInGB", "http://schemas.microsoft.com/windowsazure")); if (logicalSizeInGBElement != null) { double logicalSizeInGBInstance = double.Parse(logicalSizeInGBElement.Value, CultureInfo.InvariantCulture); result.LogicalSizeInGB = logicalSizeInGBInstance; } XElement mediaLinkElement = oSImageElement.Element(XName.Get("MediaLink", "http://schemas.microsoft.com/windowsazure")); if (mediaLinkElement != null) { Uri mediaLinkInstance = TypeConversion.TryParseUri(mediaLinkElement.Value); result.MediaLinkUri = mediaLinkInstance; } XElement nameElement = oSImageElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement != null) { string nameInstance = nameElement.Value; result.Name = nameInstance; } XElement osElement = oSImageElement.Element(XName.Get("OS", "http://schemas.microsoft.com/windowsazure")); if (osElement != null) { string osInstance = osElement.Value; result.OperatingSystemType = osInstance; } XElement eulaElement = oSImageElement.Element(XName.Get("Eula", "http://schemas.microsoft.com/windowsazure")); if (eulaElement != null) { string eulaInstance = eulaElement.Value; result.Eula = eulaInstance; } XElement descriptionElement = oSImageElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); if (descriptionElement != null) { string descriptionInstance = descriptionElement.Value; result.Description = descriptionInstance; } XElement imageFamilyElement = oSImageElement.Element(XName.Get("ImageFamily", "http://schemas.microsoft.com/windowsazure")); if (imageFamilyElement != null) { string imageFamilyInstance = imageFamilyElement.Value; result.ImageFamily = imageFamilyInstance; } XElement showInGuiElement = oSImageElement.Element(XName.Get("ShowInGui", "http://schemas.microsoft.com/windowsazure")); if (showInGuiElement != null && string.IsNullOrEmpty(showInGuiElement.Value) == false) { bool showInGuiInstance = bool.Parse(showInGuiElement.Value); result.ShowInGui = showInGuiInstance; } XElement publishedDateElement = oSImageElement.Element(XName.Get("PublishedDate", "http://schemas.microsoft.com/windowsazure")); if (publishedDateElement != null) { DateTime publishedDateInstance = DateTime.Parse(publishedDateElement.Value, CultureInfo.InvariantCulture); result.PublishedDate = publishedDateInstance; } XElement isPremiumElement = oSImageElement.Element(XName.Get("IsPremium", "http://schemas.microsoft.com/windowsazure")); if (isPremiumElement != null && string.IsNullOrEmpty(isPremiumElement.Value) == false) { bool isPremiumInstance = bool.Parse(isPremiumElement.Value); result.IsPremium = isPremiumInstance; } XElement iconUriElement = oSImageElement.Element(XName.Get("IconUri", "http://schemas.microsoft.com/windowsazure")); if (iconUriElement != null) { Uri iconUriInstance = TypeConversion.TryParseUri(iconUriElement.Value); result.IconUri = iconUriInstance; } XElement privacyUriElement = oSImageElement.Element(XName.Get("PrivacyUri", "http://schemas.microsoft.com/windowsazure")); if (privacyUriElement != null) { Uri privacyUriInstance = TypeConversion.TryParseUri(privacyUriElement.Value); result.PrivacyUri = privacyUriInstance; } XElement recommendedVMSizeElement = oSImageElement.Element(XName.Get("RecommendedVMSize", "http://schemas.microsoft.com/windowsazure")); if (recommendedVMSizeElement != null) { string recommendedVMSizeInstance = recommendedVMSizeElement.Value; result.RecommendedVMSize = recommendedVMSizeInstance; } XElement publisherNameElement = oSImageElement.Element(XName.Get("PublisherName", "http://schemas.microsoft.com/windowsazure")); if (publisherNameElement != null) { string publisherNameInstance = publisherNameElement.Value; result.PublisherName = publisherNameInstance; } XElement smallIconUriElement = oSImageElement.Element(XName.Get("SmallIconUri", "http://schemas.microsoft.com/windowsazure")); if (smallIconUriElement != null) { Uri smallIconUriInstance = TypeConversion.TryParseUri(smallIconUriElement.Value); result.SmallIconUri = smallIconUriInstance; } XElement languageElement = oSImageElement.Element(XName.Get("Language", "http://schemas.microsoft.com/windowsazure")); if (languageElement != null) { string languageInstance = languageElement.Value; result.Language = languageInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The List OS Images operation retrieves a list of the operating /// system images from the image repository. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157191.aspx /// for more information) /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List OS Images operation response. /// </returns> public async Task<VirtualMachineImageListResponse> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/images"; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-11-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result VirtualMachineImageListResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new VirtualMachineImageListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement imagesSequenceElement = responseDoc.Element(XName.Get("Images", "http://schemas.microsoft.com/windowsazure")); if (imagesSequenceElement != null) { foreach (XElement imagesElement in imagesSequenceElement.Elements(XName.Get("OSImage", "http://schemas.microsoft.com/windowsazure"))) { VirtualMachineImageListResponse.VirtualMachineImage oSImageInstance = new VirtualMachineImageListResponse.VirtualMachineImage(); result.Images.Add(oSImageInstance); XElement affinityGroupElement = imagesElement.Element(XName.Get("AffinityGroup", "http://schemas.microsoft.com/windowsazure")); if (affinityGroupElement != null) { string affinityGroupInstance = affinityGroupElement.Value; oSImageInstance.AffinityGroup = affinityGroupInstance; } XElement categoryElement = imagesElement.Element(XName.Get("Category", "http://schemas.microsoft.com/windowsazure")); if (categoryElement != null) { string categoryInstance = categoryElement.Value; oSImageInstance.Category = categoryInstance; } XElement labelElement = imagesElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); if (labelElement != null) { string labelInstance = labelElement.Value; oSImageInstance.Label = labelInstance; } XElement locationElement = imagesElement.Element(XName.Get("Location", "http://schemas.microsoft.com/windowsazure")); if (locationElement != null) { string locationInstance = locationElement.Value; oSImageInstance.Location = locationInstance; } XElement logicalSizeInGBElement = imagesElement.Element(XName.Get("LogicalSizeInGB", "http://schemas.microsoft.com/windowsazure")); if (logicalSizeInGBElement != null) { double logicalSizeInGBInstance = double.Parse(logicalSizeInGBElement.Value, CultureInfo.InvariantCulture); oSImageInstance.LogicalSizeInGB = logicalSizeInGBInstance; } XElement mediaLinkElement = imagesElement.Element(XName.Get("MediaLink", "http://schemas.microsoft.com/windowsazure")); if (mediaLinkElement != null) { Uri mediaLinkInstance = TypeConversion.TryParseUri(mediaLinkElement.Value); oSImageInstance.MediaLinkUri = mediaLinkInstance; } XElement nameElement = imagesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement != null) { string nameInstance = nameElement.Value; oSImageInstance.Name = nameInstance; } XElement osElement = imagesElement.Element(XName.Get("OS", "http://schemas.microsoft.com/windowsazure")); if (osElement != null) { string osInstance = osElement.Value; oSImageInstance.OperatingSystemType = osInstance; } XElement eulaElement = imagesElement.Element(XName.Get("Eula", "http://schemas.microsoft.com/windowsazure")); if (eulaElement != null) { string eulaInstance = eulaElement.Value; oSImageInstance.Eula = eulaInstance; } XElement descriptionElement = imagesElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); if (descriptionElement != null) { string descriptionInstance = descriptionElement.Value; oSImageInstance.Description = descriptionInstance; } XElement imageFamilyElement = imagesElement.Element(XName.Get("ImageFamily", "http://schemas.microsoft.com/windowsazure")); if (imageFamilyElement != null) { string imageFamilyInstance = imageFamilyElement.Value; oSImageInstance.ImageFamily = imageFamilyInstance; } XElement publishedDateElement = imagesElement.Element(XName.Get("PublishedDate", "http://schemas.microsoft.com/windowsazure")); if (publishedDateElement != null) { DateTime publishedDateInstance = DateTime.Parse(publishedDateElement.Value, CultureInfo.InvariantCulture); oSImageInstance.PublishedDate = publishedDateInstance; } XElement isPremiumElement = imagesElement.Element(XName.Get("IsPremium", "http://schemas.microsoft.com/windowsazure")); if (isPremiumElement != null && string.IsNullOrEmpty(isPremiumElement.Value) == false) { bool isPremiumInstance = bool.Parse(isPremiumElement.Value); oSImageInstance.IsPremium = isPremiumInstance; } XElement privacyUriElement = imagesElement.Element(XName.Get("PrivacyUri", "http://schemas.microsoft.com/windowsazure")); if (privacyUriElement != null) { Uri privacyUriInstance = TypeConversion.TryParseUri(privacyUriElement.Value); oSImageInstance.PrivacyUri = privacyUriInstance; } XElement recommendedVMSizeElement = imagesElement.Element(XName.Get("RecommendedVMSize", "http://schemas.microsoft.com/windowsazure")); if (recommendedVMSizeElement != null) { string recommendedVMSizeInstance = recommendedVMSizeElement.Value; oSImageInstance.RecommendedVMSize = recommendedVMSizeInstance; } XElement publisherNameElement = imagesElement.Element(XName.Get("PublisherName", "http://schemas.microsoft.com/windowsazure")); if (publisherNameElement != null) { string publisherNameInstance = publisherNameElement.Value; oSImageInstance.PublisherName = publisherNameInstance; } XElement pricingDetailLinkElement = imagesElement.Element(XName.Get("PricingDetailLink", "http://schemas.microsoft.com/windowsazure")); if (pricingDetailLinkElement != null) { Uri pricingDetailLinkInstance = TypeConversion.TryParseUri(pricingDetailLinkElement.Value); oSImageInstance.PricingDetailUri = pricingDetailLinkInstance; } XElement smallIconUriElement = imagesElement.Element(XName.Get("SmallIconUri", "http://schemas.microsoft.com/windowsazure")); if (smallIconUriElement != null) { Uri smallIconUriInstance = TypeConversion.TryParseUri(smallIconUriElement.Value); oSImageInstance.SmallIconUri = smallIconUriInstance; } XElement languageElement = imagesElement.Element(XName.Get("Language", "http://schemas.microsoft.com/windowsazure")); if (languageElement != null) { string languageInstance = languageElement.Value; oSImageInstance.Language = languageInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Update OS Image operation updates an OS image that in your /// image repository. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157198.aspx /// for more information) /// </summary> /// <param name='imageName'> /// The name of the virtual machine image to be updated. /// </param> /// <param name='parameters'> /// Parameters supplied to the Update Virtual Machine Image operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Parameters returned from the Create Virtual Machine Image operation. /// </returns> public async Task<VirtualMachineImageUpdateResponse> UpdateAsync(string imageName, VirtualMachineImageUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (imageName == null) { throw new ArgumentNullException("imageName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Label == null) { throw new ArgumentNullException("parameters.Label"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("imageName", imageName); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "UpdateAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/images/" + imageName; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-11-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement oSImageElement = new XElement(XName.Get("OSImage", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(oSImageElement); XElement labelElement = new XElement(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); labelElement.Value = parameters.Label; oSImageElement.Add(labelElement); if (parameters.Eula != null) { XElement eulaElement = new XElement(XName.Get("Eula", "http://schemas.microsoft.com/windowsazure")); eulaElement.Value = parameters.Eula; oSImageElement.Add(eulaElement); } if (parameters.Description != null) { XElement descriptionElement = new XElement(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); descriptionElement.Value = parameters.Description; oSImageElement.Add(descriptionElement); } if (parameters.ImageFamily != null) { XElement imageFamilyElement = new XElement(XName.Get("ImageFamily", "http://schemas.microsoft.com/windowsazure")); imageFamilyElement.Value = parameters.ImageFamily; oSImageElement.Add(imageFamilyElement); } if (parameters.PublishedDate != null) { XElement publishedDateElement = new XElement(XName.Get("PublishedDate", "http://schemas.microsoft.com/windowsazure")); publishedDateElement.Value = string.Format(CultureInfo.InvariantCulture, "{0:O}", parameters.PublishedDate.Value.ToUniversalTime()); oSImageElement.Add(publishedDateElement); } XElement isPremiumElement = new XElement(XName.Get("IsPremium", "http://schemas.microsoft.com/windowsazure")); isPremiumElement.Value = parameters.IsPremium.ToString().ToLower(); oSImageElement.Add(isPremiumElement); if (parameters.PrivacyUri != null) { XElement privacyUriElement = new XElement(XName.Get("PrivacyUri", "http://schemas.microsoft.com/windowsazure")); privacyUriElement.Value = parameters.PrivacyUri.ToString(); oSImageElement.Add(privacyUriElement); } if (parameters.IconUri != null) { XElement iconUriElement = new XElement(XName.Get("IconUri", "http://schemas.microsoft.com/windowsazure")); iconUriElement.Value = parameters.IconUri.ToString(); oSImageElement.Add(iconUriElement); } if (parameters.RecommendedVMSize != null) { XElement recommendedVMSizeElement = new XElement(XName.Get("RecommendedVMSize", "http://schemas.microsoft.com/windowsazure")); recommendedVMSizeElement.Value = parameters.RecommendedVMSize; oSImageElement.Add(recommendedVMSizeElement); } if (parameters.SmallIconUri != null) { XElement smallIconUriElement = new XElement(XName.Get("SmallIconUri", "http://schemas.microsoft.com/windowsazure")); smallIconUriElement.Value = parameters.SmallIconUri.ToString(); oSImageElement.Add(smallIconUriElement); } if (parameters.Language != null) { XElement languageElement = new XElement(XName.Get("Language", "http://schemas.microsoft.com/windowsazure")); languageElement.Value = parameters.Language; oSImageElement.Add(languageElement); } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result VirtualMachineImageUpdateResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new VirtualMachineImageUpdateResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement oSImageElement2 = responseDoc.Element(XName.Get("OSImage", "http://schemas.microsoft.com/windowsazure")); if (oSImageElement2 != null) { XElement locationElement = oSImageElement2.Element(XName.Get("Location", "http://schemas.microsoft.com/windowsazure")); if (locationElement != null) { string locationInstance = locationElement.Value; result.Location = locationInstance; } XElement categoryElement = oSImageElement2.Element(XName.Get("Category", "http://schemas.microsoft.com/windowsazure")); if (categoryElement != null) { string categoryInstance = categoryElement.Value; result.Category = categoryInstance; } XElement labelElement2 = oSImageElement2.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); if (labelElement2 != null) { string labelInstance = labelElement2.Value; result.Label = labelInstance; } XElement logicalSizeInGBElement = oSImageElement2.Element(XName.Get("LogicalSizeInGB", "http://schemas.microsoft.com/windowsazure")); if (logicalSizeInGBElement != null) { double logicalSizeInGBInstance = double.Parse(logicalSizeInGBElement.Value, CultureInfo.InvariantCulture); result.LogicalSizeInGB = logicalSizeInGBInstance; } XElement mediaLinkElement = oSImageElement2.Element(XName.Get("MediaLink", "http://schemas.microsoft.com/windowsazure")); if (mediaLinkElement != null) { Uri mediaLinkInstance = TypeConversion.TryParseUri(mediaLinkElement.Value); result.MediaLinkUri = mediaLinkInstance; } XElement nameElement = oSImageElement2.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement != null) { string nameInstance = nameElement.Value; result.Name = nameInstance; } XElement osElement = oSImageElement2.Element(XName.Get("OS", "http://schemas.microsoft.com/windowsazure")); if (osElement != null) { string osInstance = osElement.Value; result.OperatingSystemType = osInstance; } XElement eulaElement2 = oSImageElement2.Element(XName.Get("Eula", "http://schemas.microsoft.com/windowsazure")); if (eulaElement2 != null) { string eulaInstance = eulaElement2.Value; result.Eula = eulaInstance; } XElement descriptionElement2 = oSImageElement2.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); if (descriptionElement2 != null) { string descriptionInstance = descriptionElement2.Value; result.Description = descriptionInstance; } XElement imageFamilyElement2 = oSImageElement2.Element(XName.Get("ImageFamily", "http://schemas.microsoft.com/windowsazure")); if (imageFamilyElement2 != null) { string imageFamilyInstance = imageFamilyElement2.Value; result.ImageFamily = imageFamilyInstance; } XElement publishedDateElement2 = oSImageElement2.Element(XName.Get("PublishedDate", "http://schemas.microsoft.com/windowsazure")); if (publishedDateElement2 != null && string.IsNullOrEmpty(publishedDateElement2.Value) == false) { DateTime publishedDateInstance = DateTime.Parse(publishedDateElement2.Value, CultureInfo.InvariantCulture); result.PublishedDate = publishedDateInstance; } XElement publisherNameElement = oSImageElement2.Element(XName.Get("PublisherName", "http://schemas.microsoft.com/windowsazure")); if (publisherNameElement != null) { string publisherNameInstance = publisherNameElement.Value; result.PublisherName = publisherNameInstance; } XElement isPremiumElement2 = oSImageElement2.Element(XName.Get("IsPremium", "http://schemas.microsoft.com/windowsazure")); if (isPremiumElement2 != null && string.IsNullOrEmpty(isPremiumElement2.Value) == false) { bool isPremiumInstance = bool.Parse(isPremiumElement2.Value); result.IsPremium = isPremiumInstance; } XElement showInGuiElement = oSImageElement2.Element(XName.Get("ShowInGui", "http://schemas.microsoft.com/windowsazure")); if (showInGuiElement != null && string.IsNullOrEmpty(showInGuiElement.Value) == false) { bool showInGuiInstance = bool.Parse(showInGuiElement.Value); result.ShowInGui = showInGuiInstance; } XElement privacyUriElement2 = oSImageElement2.Element(XName.Get("PrivacyUri", "http://schemas.microsoft.com/windowsazure")); if (privacyUriElement2 != null) { Uri privacyUriInstance = TypeConversion.TryParseUri(privacyUriElement2.Value); result.PrivacyUri = privacyUriInstance; } XElement iconUriElement2 = oSImageElement2.Element(XName.Get("IconUri", "http://schemas.microsoft.com/windowsazure")); if (iconUriElement2 != null) { Uri iconUriInstance = TypeConversion.TryParseUri(iconUriElement2.Value); result.IconUri = iconUriInstance; } XElement recommendedVMSizeElement2 = oSImageElement2.Element(XName.Get("RecommendedVMSize", "http://schemas.microsoft.com/windowsazure")); if (recommendedVMSizeElement2 != null) { string recommendedVMSizeInstance = recommendedVMSizeElement2.Value; result.RecommendedVMSize = recommendedVMSizeInstance; } XElement smallIconUriElement2 = oSImageElement2.Element(XName.Get("SmallIconUri", "http://schemas.microsoft.com/windowsazure")); if (smallIconUriElement2 != null) { Uri smallIconUriInstance = TypeConversion.TryParseUri(smallIconUriElement2.Value); result.SmallIconUri = smallIconUriInstance; } XElement languageElement2 = oSImageElement2.Element(XName.Get("Language", "http://schemas.microsoft.com/windowsazure")); if (languageElement2 != null) { string languageInstance = languageElement2.Value; result.Language = languageInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Kemel.Entity.Attributes; using System.Reflection; using Kemel.Entity; using Kemel.Constants; using Kemel.Base; using System.ComponentModel.DataAnnotations.Schema; namespace Kemel.Schema { public class TableSchema : ITableDefinition { public TableSchema() { this.Columns = new ColumnSchemaCollection(); } public TableSchema(Type entityType) : this() { this.EntityType = entityType; this.SetColumnsFromType(); } #region Properties #region Name private string strName = null; public string Name { get { if (this.strName == null) this.strName = TableSchema.GetTableName(this.EntityType); return this.strName; } set { this.strName = value; } } #endregion #region Alias private string strAlias = null; public string Alias { get { if (string.IsNullOrEmpty(this.strAlias) && this.EntityType != null) this.strAlias = TableSchema.GetTableAlias(this.EntityType); return this.strAlias; } set { this.strAlias = value; } } #endregion #region SchemaType private SchemaType enmSchemaType = SchemaType.None; public SchemaType SchemaType { get { if (this.enmSchemaType == SchemaType.None) this.enmSchemaType = TableSchema.GetSchemaType(this.EntityType); return this.enmSchemaType; } set { this.enmSchemaType = value; } } #endregion #region Owner private string strOwner = null; public string Owner { get { if (this.strOwner == null) this.strOwner = TableSchema.GetOwner(this.EntityType); return this.strOwner; } set { this.strOwner = value; } } #endregion #region KeyProvider private string strKeyProvider = null; public string KeyProvider { get { if (this.strKeyProvider == null) this.strKeyProvider = TableSchema.GetKeyProvider(this.EntityType); return this.strKeyProvider; } set { this.strKeyProvider = value; } } #endregion public Type EntityType { get; set; } public ColumnSchema clsLogicalExclusionColumn = null; public ColumnSchema LogicalExclusionColumn { get { if (!blnIsLogicalExclusion.HasValue) { blnIsLogicalExclusion = false; foreach (ColumnSchema column in this.Columns) { if (column.IsLogicalExclusionColumn) { clsLogicalExclusionColumn = column; blnIsLogicalExclusion = true; break; } } } return clsLogicalExclusionColumn; } } private bool? blnIsLogicalExclusion = null; public bool IsLogicalExclusion { get { if (!blnIsLogicalExclusion.HasValue) { blnIsLogicalExclusion = false; foreach (ColumnSchema column in this.Columns) { if (column.IsLogicalExclusionColumn) { clsLogicalExclusionColumn = column; blnIsLogicalExclusion = true; break; } } } return blnIsLogicalExclusion.Value; } } private ColumnSchemaCollection cscIdentityColumns = null; public ColumnSchemaCollection IdentityColumns { get { if (cscIdentityColumns == null) { cscIdentityColumns = new ColumnSchemaCollection(); foreach (ColumnSchema column in this.Columns) { if (column.IsIdentity) cscIdentityColumns.Add(column); } } return cscIdentityColumns; } } #endregion #region Columns public ColumnSchemaCollection Columns { get; set; } public ColumnSchema this[int index] { get { return this.Columns[index]; } set { this[index] = value; } } public ColumnSchema this[string name] { get { return this.Columns[name]; } set { this[name] = value; } } #endregion #region SetColumnsFromType public void SetColumnsFromType() { foreach (PropertyInfo prop in this.EntityType.GetPublicDeclaredProperties()) { if(ColumnSchema.IsColumn(prop)) this.Columns.Add(new ColumnSchema(prop, this)); } } #endregion #region Validate ///// <summary> ///// Validate entity. ///// </summary> public void Validate(CrudOperation crudOperation, EntityBase entity) { foreach (ColumnSchema column in this.Columns) { column.ValidateField(crudOperation, entity); } } #endregion #region Static Methods #region GetTableAlias /// <summary> /// GetTableAlias /// </summary> /// <param name="propInfo"></param> /// <returns></returns> public static string GetTableAlias(Type entityType) { TableAliasAttribute att = entityType.GetCustomAttribute<TableAliasAttribute>(); return (att != null) ? att.Alias : string.Empty; } #endregion #region GetTableAlias<TEtt> /// <summary> /// GetTableAlias /// </summary> /// <param name="propInfo"></param> /// <returns></returns> public static string GetTableAlias<TEtt>() where TEtt : EntityBase { return GetTableAlias(typeof(TEtt)); } #endregion #region GetTableName /// <summary> /// GetTableName /// </summary> /// <param name="entityType"></param> /// <returns></returns> public static string GetTableName(Type entityType) { TableAttribute att = entityType.GetCustomAttribute<TableAttribute>(); if (att != null) { return att.Name; } else { return entityType.Name.Replace(Sufix.ENTITY_NAME, string.Empty); } } #endregion #region GetTableName<TEtt> /// <summary> /// GetTableName /// </summary> /// <param name="propInfo"></param> /// <returns></returns> public static string GetTableName<TEtt>() where TEtt : EntityBase { return GetTableName(typeof(TEtt)); } #endregion #region GetOwner<TEtt> /// <summary> /// GetTableName /// </summary> /// <typeparam name="TEtt"></typeparam> /// <returns></returns> public static string GetOwner<TEtt>() where TEtt : EntityBase { OwnerAttribute att = typeof(TEtt).GetCustomAttribute<OwnerAttribute>(); return (att != null) ? att.Owner : string.Empty; } #endregion #region GetOwner /// <summary> /// GetTableName /// </summary> /// <param name="entityType"></param> /// <returns></returns> public static string GetOwner(Type entityType) { OwnerAttribute att = entityType.GetCustomAttribute<OwnerAttribute>(); return (att != null) ? att.Owner : string.Empty; } #endregion #region GetPrimaryKeys /// <summary> /// /// </summary> /// <returns></returns> public ColumnSchema[] GetPrimaryKeys() { List<ColumnSchema> lst = new List<ColumnSchema>(); foreach (ColumnSchema column in this.Columns) { if (column.IsPrimaryKey) lst.Add(column); } return lst.ToArray(); } #endregion #region GetSchemaType /// <summary> /// GetSchemaType /// </summary> /// <param name="entityType"></param> /// <returns></returns> private static SchemaType GetSchemaType(Type entityType) { TableSchemaTypeAttribute att = entityType.GetCustomAttribute<TableSchemaTypeAttribute>(); return att != null ? att.SchemaType : SchemaType.Table; } #endregion #region GetKeyProvider /// <summary> /// GetTableAlias /// </summary> /// <param name="propInfo"></param> /// <returns></returns> public static string GetKeyProvider(Type entityType) { KeyProviderAttribute att = entityType.GetCustomAttribute<KeyProviderAttribute>(); return (att != null) ? att.Key : string.Empty; } #endregion public static TableSchema FromEntity<TEtt>() where TEtt : EntityBase { return SchemaContainer.GetSchema<TEtt>(); } public static TableSchema FromEntity(Type entityType) { return SchemaContainer.GetSchema(entityType); } public static TableSchema FromEntity(EntityBase entity) { return SchemaContainer.GetSchema(entity); } public static TableSchema FromTableName(string tableName) { Type tp = Type.GetType(tableName); if (tp == null) tp = Type.GetType(tableName + Sufix.ENTITY_NAME); if (tp == null) { Assembly entryAsm = Assembly.GetEntryAssembly(); if (entryAsm != null) { return FindTypeInAssembly(tableName, entryAsm); } else { Assembly[] asms = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly asm in asms) { try { if (asm.ManifestModule.GetType().Namespace != "System.Reflection.Emit" && !asm.GlobalAssemblyCache) { TableSchema schema = FindTypeInAssembly(tableName, asm); if (schema != null) return schema; } } catch { } } return null; } } else { return new TableSchema(tp); } } public static TableSchema FindTypeInAssembly(string tableName, Assembly asm) { Type[] types = asm.GetExportedTypes(); Type tp = FindEntityType(tableName, types); if (tp == null) { AssemblyName[] asms = asm.GetReferencedAssemblies(); foreach (AssemblyName asmName in asms) { types = Assembly.Load(asmName).GetExportedTypes(); tp = FindEntityType(tableName, types); if (tp != null) return new TableSchema(tp); } return null; } else { return new TableSchema(tp); } } private static Type FindEntityType(string tableName, Type[] types) { tableName = tableName.ToUpper(); foreach (Type type in types) { if(tableName.Equals(TableSchema.GetTableName(type).ToUpper())) return type; } return null; } #endregion #region ITableDefinition Members public IColumnDefinition GetColumn(string columnName) { return this[columnName]; } public void AddColumn(IColumnDefinition column) { throw new NotImplementedException(); } #endregion } }
using System; using System.Collections.Generic; using System.Net; using PacketParser; using PacketParser.Packets; using ProtocolIdentification; namespace Spid { internal class SessionHandler { public delegate void SessionProtocolModelCompletedEventHandler(ISession session, ProtocolModel protocolModel); public enum TransportProtocol { TCP, UDP } //60 seconds private static readonly TimeSpan SESSION_TIMEOUT = new TimeSpan(0, 1, 0); //60 seconds. Rossi et al uses 200s in their Skype paper //this protocol model is here just to save memory //sessions protocol models are replaced this one when //they have reached 100 frames public static ProtocolModel PlaceholderProtocolModel = new ProtocolModel("Placeholder Protocol Model", Configuration.GetInstance().ActiveAttributeMeters); private Configuration config; //the purpose with having a separate list for not-yet established //sessions is to prevent SYN scans from pushing established sessions //out from the list private PopularityList<String, ISession> establishedSessionsList, upcomingSessionsList; //10.000 simultaneous sessions might a good (high) value //each session will consume ~30kB public SessionHandler(Int32 maxSimultaneousSessions, Configuration config) { this.upcomingSessionsList = new PopularityList<String, ISession>(maxSimultaneousSessions); this.establishedSessionsList = new PopularityList<String, ISession>(maxSimultaneousSessions); this.establishedSessionsList.PopularityLost += this.establishedSessionsList_PopularityLost; this.config = config; } public Int32 SessionsCount => this.establishedSessionsList.Count; public static String GetSessionIdentifier(IPAddress clientIp, UInt16 clientPort, IPAddress serverIp, UInt16 serverPort, TransportProtocol transportProtocol) => transportProtocol + " " + clientIp + ":" + clientPort + " -> " + serverIp + ":" + serverPort; /// <summary> /// To get the remaining sessions whose protocol models have not yet been fully completed /// </summary> /// <returns>Sessions</returns> public IEnumerable<ISession> GetSessionsWithoutCompletedProtocolModels() { foreach(var s in this.establishedSessionsList.GetValueEnumerator()) { if(s.ApplicationProtocolModel != null && s.ApplicationProtocolModel != PlaceholderProtocolModel) { yield return s; } } } public event SessionProtocolModelCompletedEventHandler SessionProtocolModelCompleted; public static Boolean TryGetEthernetPacket(Frame frame, out Ethernet2Packet ethernetPacket) { ethernetPacket = null; foreach(var p in frame.PacketList) { if(p.GetType() == typeof(Ethernet2Packet)) { ethernetPacket = (Ethernet2Packet) p; return true; } if(p.GetType() == typeof(RawPacket)) { return false; } if(p.GetType() == typeof(IPv4Packet)) { return false; } } return false; } /// <summary> /// </summary> /// <param name="frame"></param> /// <param name="ipPacket">IPv4 or IPv6 packet in frame</param> /// <param name="tcpPacket">TCP packet in frame</param> /// <returns></returns> public static Boolean TryGetIpAndTcpPackets(Frame frame, out AbstractPacket ipPacket, out TcpPacket tcpPacket) { ipPacket = null; //sourceIp=System.Net.IPAddress.None; //destinationIp=System.Net.IPAddress.None; tcpPacket = null; foreach(var p in frame.PacketList) { if(p.GetType() == typeof(RawPacket)) { return false; } if(p.GetType() == typeof(UdpPacket)) { return false; } if(p.GetType() == typeof(IPv4Packet)) { ipPacket = p; } else if(p.GetType() == typeof(IPv6Packet)) { ipPacket = p; } else if(p.GetType() == typeof(TcpPacket)) { tcpPacket = (TcpPacket) p; //there is no point in enumarating further than the TCP packet if(ipPacket != null) { return true; } return false; } } return false; } public static Boolean TryGetIpAndUdpPackets(Frame frame, out AbstractPacket ipPacket, out UdpPacket udpPacket) { ipPacket = null; udpPacket = null; foreach(var p in frame.PacketList) { if(p.GetType() == typeof(RawPacket)) { return false; } if(p.GetType() == typeof(TcpPacket)) { return false; } if(p.GetType() == typeof(IPv4Packet)) { ipPacket = p; } else if(p.GetType() == typeof(IPv6Packet)) { ipPacket = p; } else if(p.GetType() == typeof(UdpPacket)) { udpPacket = (UdpPacket) p; //there is no point in enumarating further than the UDP packet if(ipPacket != null) { return true; } return false; } } return false; } public Boolean TryGetSession(Frame frame, out ISession session) { //start with getting the IP adresses and port numbers AbstractPacket ipPacket; TcpPacket tcpPacket; UdpPacket udpPacket; session = null; var sourceIp = IPAddress.None; var destinationIp = IPAddress.None; if(TryGetIpAndTcpPackets(frame, out ipPacket, out tcpPacket)) { if(ipPacket.GetType() == typeof(IPv4Packet)) { var ipv4Packet = (IPv4Packet) ipPacket; sourceIp = ipv4Packet.SourceIPAddress; destinationIp = ipv4Packet.DestinationIPAddress; } else if(ipPacket.GetType() == typeof(IPv6Packet)) { var ipv6Packet = (IPv6Packet) ipPacket; sourceIp = ipv6Packet.SourceIP; destinationIp = ipv6Packet.DestinationIP; } //we now have the IP addresses TcpSession tcpSession; if(this.TryGetSession(sourceIp, destinationIp, tcpPacket, out tcpSession)) { session = tcpSession; return true; } return false; } if(TryGetIpAndUdpPackets(frame, out ipPacket, out udpPacket)) { if(ipPacket.GetType() == typeof(IPv4Packet)) { var ipv4Packet = (IPv4Packet) ipPacket; sourceIp = ipv4Packet.SourceIPAddress; destinationIp = ipv4Packet.DestinationIPAddress; } else if(ipPacket.GetType() == typeof(IPv6Packet)) { var ipv6Packet = (IPv6Packet) ipPacket; sourceIp = ipv6Packet.SourceIP; destinationIp = ipv6Packet.DestinationIP; } //we now have the IP addresses UdpSession udpSession; if(this.TryGetSession(sourceIp, destinationIp, udpPacket, out udpSession)) { session = udpSession; return true; } return false; } return false; //no session found } public Boolean TryGetSession(IPAddress sourceIp, IPAddress destinationIp, UdpPacket udpPacket, out UdpSession session) { session = null; var clientToServerIdentifier = GetSessionIdentifier(sourceIp, udpPacket.SourcePort, destinationIp, udpPacket.DestinationPort, TransportProtocol.UDP); var serverToClientIdentifier = GetSessionIdentifier(destinationIp, udpPacket.DestinationPort, sourceIp, udpPacket.SourcePort, TransportProtocol.UDP); if(this.upcomingSessionsList.ContainsKey(clientToServerIdentifier)) { session = (UdpSession) this.upcomingSessionsList[clientToServerIdentifier]; } else if(this.establishedSessionsList.ContainsKey(clientToServerIdentifier)) { session = (UdpSession) this.establishedSessionsList[clientToServerIdentifier]; } else if(this.upcomingSessionsList.ContainsKey(serverToClientIdentifier)) { session = (UdpSession) this.upcomingSessionsList[serverToClientIdentifier]; } else if(this.establishedSessionsList.ContainsKey(serverToClientIdentifier)) { session = (UdpSession) this.establishedSessionsList[serverToClientIdentifier]; } //see if the session has timed out if(session != null && session.LastPacketTimestamp.Add(SESSION_TIMEOUT) < udpPacket.ParentFrame.Timestamp) { //session has timed out if(this.establishedSessionsList.ContainsKey(session.Identifier)) { this.establishedSessionsList.Remove(session.Identifier); if(this.SessionProtocolModelCompleted != null) { this.SessionProtocolModelCompleted(session, session.ApplicationProtocolModel); } } session = null; } if(session == null) { //create a new session, source is client (the UDP client is defined as the host that send the first packet) session = new UdpSession(this.config, sourceIp, udpPacket.SourcePort, destinationIp, udpPacket.DestinationPort); this.upcomingSessionsList.Add(session.Identifier, session); session.SessionEstablished += this.session_SessionEstablished; session.ProtocolModelCompleted += this.session_ProtocolModelCompleted; } if(session != null) { return true; } return false; } public Boolean TryGetSession(IPAddress sourceIp, IPAddress destinationIp, TcpPacket tcpPacket, out TcpSession session) { session = null; var clientToServerIdentifier = GetSessionIdentifier(sourceIp, tcpPacket.SourcePort, destinationIp, tcpPacket.DestinationPort, TransportProtocol.TCP); var serverToClientIdentifier = GetSessionIdentifier(destinationIp, tcpPacket.DestinationPort, sourceIp, tcpPacket.SourcePort, TransportProtocol.TCP); if(this.upcomingSessionsList.ContainsKey(clientToServerIdentifier)) { session = (TcpSession) this.upcomingSessionsList[clientToServerIdentifier]; } else if(this.establishedSessionsList.ContainsKey(clientToServerIdentifier)) { session = (TcpSession) this.establishedSessionsList[clientToServerIdentifier]; } else if(this.upcomingSessionsList.ContainsKey(serverToClientIdentifier)) { session = (TcpSession) this.upcomingSessionsList[serverToClientIdentifier]; } else if(this.establishedSessionsList.ContainsKey(serverToClientIdentifier)) { session = (TcpSession) this.establishedSessionsList[serverToClientIdentifier]; } //see if the session has timed out if(session != null && session.LastPacketTimestamp.Add(SESSION_TIMEOUT) < tcpPacket.ParentFrame.Timestamp) { //session has timed out if(this.upcomingSessionsList.ContainsKey(session.Identifier)) { this.upcomingSessionsList.Remove(session.Identifier); } else if(this.establishedSessionsList.ContainsKey(session.Identifier)) { this.establishedSessionsList.Remove(session.Identifier); if(this.SessionProtocolModelCompleted != null) { this.SessionProtocolModelCompleted(session, session.ApplicationProtocolModel); } } session = null; } if(session == null) { //try to create a new session if(tcpPacket.FlagBits.Synchronize && !tcpPacket.FlagBits.Acknowledgement) { //the first SYN packet - source is client session = new TcpSession(this.config, sourceIp, tcpPacket.SourcePort, destinationIp, tcpPacket.DestinationPort); } else if(tcpPacket.FlagBits.Synchronize && tcpPacket.FlagBits.Acknowledgement) { //we've missed the first SYN but caught the SYN+ACK - destination is client session = new TcpSession(this.config, destinationIp, tcpPacket.DestinationPort, sourceIp, tcpPacket.SourcePort); session.State = TcpSession.TCPState.SYN; //I will pretend that the SYN has already been observed } if(session != null) { this.upcomingSessionsList.Add(session.Identifier, session); session.UsePlaceholderProtocolModel = true; //in order to save memory, but I will need to detect when the protocol model is completed instead session.SessionEstablished += this.session_SessionEstablished; session.ProtocolModelCompleted += this.session_ProtocolModelCompleted; session.SessionClosed += this.session_SessionClosed; } } if(session != null) { return true; } return false; } private void establishedSessionsList_PopularityLost(String sessionIdentifierKey, ISession session) { //now, do something smart with the session if(this.SessionProtocolModelCompleted != null) { this.SessionProtocolModelCompleted(session, session.ApplicationProtocolModel); } } private void session_ProtocolModelCompleted(ISession session, ProtocolModel protocolModel) { if(protocolModel != null && protocolModel != PlaceholderProtocolModel && this.SessionProtocolModelCompleted != null) { this.SessionProtocolModelCompleted(session, protocolModel); } } private void session_SessionClosed(TcpSession session, ProtocolModel protocolModel) { //first remove the session from the list if(this.upcomingSessionsList.ContainsKey(session.Identifier)) { this.upcomingSessionsList.Remove(session.Identifier); } else if(this.establishedSessionsList.ContainsKey(session.Identifier)) { this.establishedSessionsList.Remove(session.Identifier); } if(protocolModel != null && protocolModel != PlaceholderProtocolModel && this.SessionProtocolModelCompleted != null) { this.SessionProtocolModelCompleted(session, protocolModel); } } private void session_SessionEstablished(ISession session) { //see if the session is in the non-established list if(this.upcomingSessionsList.ContainsKey(session.Identifier)) { this.upcomingSessionsList.Remove(session.Identifier); } //now move it to the established list instead if(!this.establishedSessionsList.ContainsKey(session.Identifier)) { this.establishedSessionsList.Add(session.Identifier, session); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.Serialization; using System.Xml; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Impl; using NUnit.Framework; /// <summary> /// Tests for native serialization. /// </summary> public class SerializationTest { /** Grid name. */ private const string GridName = "SerializationTest"; /// <summary> /// Set up routine. /// </summary> [TestFixtureSetUp] public void SetUp() { var cfg = new IgniteConfigurationEx { GridName = GridName, JvmClasspath = TestUtils.CreateTestClasspath(), JvmOptions = TestUtils.TestJavaOptions(), SpringConfigUrl = "config\\native-client-test-cache.xml" }; Ignition.Start(cfg); } /// <summary> /// Tear down routine. /// </summary> [TestFixtureTearDown] public void TearDown() { Ignition.StopAll(true); } /// <summary> /// Test complex file serialization. /// </summary> [Test] public void TestSerializableXmlDoc() { var grid = Ignition.GetIgnite(GridName); var cache = grid.Cache<int, SerializableXmlDoc>("replicated"); var doc = new SerializableXmlDoc(); doc.LoadXml("<document><test1>val</test1><test2 attr=\"x\" /></document>"); for (var i = 0; i < 50; i++) { // Test cache cache.Put(i, doc); var resultDoc = cache.Get(i); Assert.AreEqual(doc.OuterXml, resultDoc.OuterXml); // Test task with document arg CheckTask(grid, doc); } } /// <summary> /// Checks task execution. /// </summary> /// <param name="grid">Grid.</param> /// <param name="arg">Task arg.</param> private static void CheckTask(IIgnite grid, object arg) { var jobResult = grid.Compute().Execute(new CombineStringsTask(), arg); var nodeCount = grid.Cluster.Nodes().Count; var expectedRes = CombineStringsTask.CombineStrings(Enumerable.Range(0, nodeCount).Select(x => arg.ToString())); Assert.AreEqual(expectedRes, jobResult.InnerXml); } /// <summary> /// Tests custom serialization binder. /// </summary> [Test] public void TestSerializationBinder() { const int count = 50; var cache = Ignition.GetIgnite(GridName).Cache<int, object>("local"); // Put multiple objects from muliple same-named assemblies to cache for (var i = 0; i < count; i++) { dynamic val = Activator.CreateInstance(GenerateDynamicType()); val.Id = i; val.Name = "Name_" + i; cache.Put(i, val); } // Verify correct deserialization for (var i = 0; i < count; i++) { dynamic val = cache.Get(i); Assert.AreEqual(val.Id, i); Assert.AreEqual(val.Name, "Name_" + i); } } /// <summary> /// Generates a Type in runtime, puts it into a dynamic assembly. /// </summary> /// <returns></returns> public static Type GenerateDynamicType() { var asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly( new AssemblyName("GridSerializationTestDynamicAssembly"), AssemblyBuilderAccess.Run); var moduleBuilder = asmBuilder.DefineDynamicModule("GridSerializationTestDynamicModule"); var typeBuilder = moduleBuilder.DefineType("GridSerializationTestDynamicType", TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Serializable); typeBuilder.DefineField("Id", typeof (int), FieldAttributes.Public); typeBuilder.DefineField("Name", typeof (string), FieldAttributes.Public); return typeBuilder.CreateType(); } } [Serializable] [DataContract] public sealed class SerializableXmlDoc : XmlDocument, ISerializable { /// <summary> /// Default ctor. /// </summary> public SerializableXmlDoc() { // No-op } /// <summary> /// Serialization ctor. /// </summary> private SerializableXmlDoc(SerializationInfo info, StreamingContext context) { LoadXml(info.GetString("xmlDocument")); } /** <inheritdoc /> */ public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("xmlDocument", OuterXml, typeof(string)); } } [Serializable] public class CombineStringsTask : IComputeTask<object, string, SerializableXmlDoc> { public IDictionary<IComputeJob<string>, IClusterNode> Map(IList<IClusterNode> subgrid, object arg) { return subgrid.ToDictionary(x => (IComputeJob<string>) new ToStringJob {Arg = arg}, x => x); } public ComputeJobResultPolicy Result(IComputeJobResult<string> res, IList<IComputeJobResult<string>> rcvd) { return ComputeJobResultPolicy.Wait; } public SerializableXmlDoc Reduce(IList<IComputeJobResult<string>> results) { var result = new SerializableXmlDoc(); result.LoadXml(CombineStrings(results.Select(x => x.Data()))); return result; } public static string CombineStrings(IEnumerable<string> strings) { var text = string.Concat(strings.Select(x => string.Format("<val>{0}</val>", x))); return string.Format("<document>{0}</document>", text); } } [Serializable] public class ToStringJob : IComputeJob<string> { /// <summary> /// Job argument. /// </summary> public object Arg { get; set; } /** <inheritdoc /> */ public string Execute() { return Arg.ToString(); } /** <inheritdoc /> */ public void Cancel() { // No-op. } } }
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 OCR.Web.Areas.HelpPage.ModelDescriptions; using OCR.Web.Areas.HelpPage.Models; namespace OCR.Web.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
/* ==================================================================== 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 System.Text; using System.Globalization; namespace NPOI.HSSF.Util { /** * Title: Range Address * Description: provides connectivity utilities for ranges * * * REFERENCE: * @author IgOr KaTz &amp; EuGeNe BuMaGiN (Tal Moshaiov) (VistaPortal LDT.) @version 1.0 */ internal class RangeAddress { const int WRONG_POS = -1; const int MAX_HEIGHT = 66666; //static char SO_FORMNAME_ENCLOSURE = '\''; String m_sheetName; String m_cellFrom; String m_cellTo; /** * Accepts an external reference from excel. * * i.e. Sheet1!$A$4:$B$9 * @param _url */ public RangeAddress(String _url) { init(_url); } public RangeAddress(int _startCol, int _startRow, int _endCol, int _endRow) { init(NumTo26Sys(_startCol) + _startRow + ":" + NumTo26Sys(_endCol) + _endRow); } /** * * @return String <b>note: </b> All absolute references are Removed */ public String Address { get { String result = ""; if (m_sheetName != null) result += m_sheetName + "!"; if (m_cellFrom != null) { result += m_cellFrom; if (m_cellTo != null) result += ":" + m_cellTo; } return result; } } public String SheetName { get { return m_sheetName; } } public String Range { get { String result = ""; if (m_cellFrom != null) { result += m_cellFrom; if (m_cellTo != null) result += ":" + m_cellTo; } return result; } } public bool IsCellOk(String _cell) { if (_cell != null) { if ((GetYPosition(_cell) != WRONG_POS) && (GetXPosition(_cell) != WRONG_POS)) return true; else return false; } else return false; } public bool IsSheetNameOk() { return IsSheetNameOk(m_sheetName); } private static bool intern_isSheetNameOk(String _sheetName, bool _canBeWaitSpace) { for (int i = 0; i < _sheetName.Length; i++) { char ch = _sheetName[i]; if (!(Char.IsLetterOrDigit(ch) || (ch == '_') || _canBeWaitSpace && (ch == ' '))) { return false; } } return true; } public static bool IsSheetNameOk(String _sheetName) { bool res = false; if (!string.IsNullOrEmpty(_sheetName)) { res = intern_isSheetNameOk(_sheetName, true); } else res = true; return res; } public String FromCell { get { return m_cellFrom; } } public String ToCell { get { return m_cellTo; } } public int Width { get { if (m_cellFrom != null && m_cellTo != null) { int toX = GetXPosition(m_cellTo); int fromX = GetXPosition(m_cellFrom); if ((toX == WRONG_POS) || (fromX == WRONG_POS)) { return 0; } else return toX - fromX + 1; } return 0; } } public int Height { get { if (m_cellFrom != null && m_cellTo != null) { int toY = GetYPosition(m_cellTo); int fromY = GetYPosition(m_cellFrom); if ((toY == WRONG_POS) || (fromY == WRONG_POS)) { return 0; } else return toY - fromY + 1; } return 0; } } public void SetSize(int _width, int _height) { if (m_cellFrom == null) m_cellFrom = "a1"; int tlX, tlY; // fix warning CS0168 "never used": , rbX, rbY; //Tony Qu: not sure what's doing here tlX = GetXPosition(m_cellFrom); tlY = GetYPosition(m_cellFrom); m_cellTo = NumTo26Sys(tlX + _width - 1); m_cellTo += (tlY + _height - 1).ToString(CultureInfo.InvariantCulture); } public bool HasSheetName { get { if (m_sheetName == null) return false; return true; } } public bool HasRange { get { return (m_cellFrom != null && m_cellTo != null && !m_cellFrom.Equals(m_cellTo)); } } public bool HasCell { get { if (m_cellFrom == null) return false; return true; } } private void init(String _url) { _url = RemoveString(_url, "$"); _url = RemoveString(_url, "'"); String[] urls = ParseURL(_url); m_sheetName = urls[0]; m_cellFrom = urls[1]; m_cellTo = urls[2]; //What if range is one celled ? if (m_cellTo == null) { m_cellTo = m_cellFrom; } //Removing noneeds Chars m_cellTo = RemoveString(m_cellTo, "."); } private String[] ParseURL(String _url) { String[] result = new String[3]; int index = _url.IndexOf(':'); if (index >= 0) { String fromStr = _url.Substring(0, index); String toStr = _url.Substring(index + 1); index = fromStr.IndexOf('!'); if (index >= 0) { result[0] = fromStr.Substring(0, index); result[1] = fromStr.Substring(index + 1); } else { result[1] = fromStr; } index = toStr.IndexOf('!'); if (index >= 0) { result[2] = toStr.Substring(index + 1); } else { result[2] = toStr; } } else { index = _url.IndexOf('!'); if (index >= 0) { result[0] = _url.Substring(0, index); result[1] = _url.Substring(index + 1); } else { result[1] = _url; } } return result; } public int GetYPosition(String _subrange) { int result = WRONG_POS; _subrange = _subrange.Trim(); if (_subrange.Length != 0) { String digitstr = GetDigitPart(_subrange); try { result = int.Parse(digitstr, CultureInfo.InvariantCulture); if (result > MAX_HEIGHT) { result = WRONG_POS; } } catch (Exception) { result = WRONG_POS; } } return result; } private static bool IsLetter(String _str) { bool res = true; if (!string.IsNullOrEmpty(_str)) { for (int i = 0; i < _str.Length; i++) { char ch = _str[i]; if (!Char.IsLetter(ch)) { res = false; break; } } } else res = false; return res; } public int GetXPosition(String _subrange) { int result = WRONG_POS; String tmp = Filter(_subrange); tmp = this.GetCharPart(_subrange); // we will Process only 2 letters ranges if (IsLetter(tmp) && ((tmp.Length == 2) || (tmp.Length == 1))) { result = Get26Sys(tmp); } return result; } public String GetDigitPart(String _value) { String result = ""; int digitpos = GetFirstDigitPosition(_value); if (digitpos >= 0) { result = _value.Substring(digitpos); } return result; } public String GetCharPart(String _value) { String result = ""; int digitpos = GetFirstDigitPosition(_value); if (digitpos >= 0) { result = _value.Substring(0, digitpos); } return result; } private String Filter(String _range) { String res = ""; for (int i = 0; i < _range.Length; i++) { char ch = _range[i]; if (ch != '$') { res = res + ch; } } return res; } private int GetFirstDigitPosition(String _value) { int result = WRONG_POS; if (_value != null && _value.Trim().Length == 0) { return result; } _value = _value.Trim(); int Length = _value.Length; for (int i = 0; i < Length; i++) { if (Char.IsDigit(_value[i])) { result = i; break; } } return result; } public int Get26Sys(String _s) { int sum = 0; int multiplier = 1; if (!string.IsNullOrEmpty(_s)) { for (int i = _s.Length - 1; i >= 0; i--) { char ch = _s[i]; int val = (int)(Char.GetNumericValue(ch) - Char.GetNumericValue('A') + 1); sum = sum + val * multiplier; multiplier = multiplier * 26; } return sum; } return WRONG_POS; } public String NumTo26Sys(int _num) { //int sum = 0; int reminder; String s = ""; do { _num--; reminder = _num % 26; int val = 65 + reminder; _num = _num / 26; s = (char)val + s; // reverce } while (_num > 0); return s; } public String ReplaceString(String _source, String _oldPattern, String _newPattern) { StringBuilder res = new StringBuilder(_source); res = res.Replace(_oldPattern, _newPattern); return res.ToString(); } public String RemoveString(String _source, String _match) { return ReplaceString(_source, _match, ""); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Baseline; using Marten.Events; using Marten.Linq; using Marten.Linq.Model; using Marten.Linq.QueryHandlers; using Marten.Schema; using Marten.Util; using Npgsql; namespace Marten.Services.BatchQuerying { public class BatchedQuery : IBatchedQuery, IBatchEvents { private static readonly MartenQueryParser QueryParser = new MartenQueryParser(); private readonly IIdentityMap _identityMap; private readonly IList<IBatchQueryItem> _items = new List<IBatchQueryItem>(); private readonly QuerySession _parent; private readonly DocumentStore _store; private readonly IManagedConnection _runner; public BatchedQuery(DocumentStore store, IManagedConnection runner, IIdentityMap identityMap, QuerySession parent) { _store = store; _runner = runner; _identityMap = identityMap; _parent = parent; } public IBatchEvents Events => this; public Task<T> Load<T>(string id) where T : class { return load<T>(id); } public Task<T> Load<T>(ValueType id) where T : class { return load<T>(id); } public IBatchLoadByKeys<TDoc> LoadMany<TDoc>() where TDoc : class { return new BatchLoadByKeys<TDoc>(this); } public Task<IList<T>> Query<T>(string sql, params object[] parameters) where T : class { return AddItem(new UserSuppliedQueryHandler<T>(_store, sql, parameters), null); } public IBatchedQueryable<T> Query<T>() where T : class { return new BatchedQueryable<T>(this, _parent.Query<T>()); } private NpgsqlCommand buildCommand() { return CommandBuilder.ToBatchCommand(_parent.Tenant, _items.Select(x => x.Handler)); } public async Task Execute(CancellationToken token = default(CancellationToken)) { var map = _identityMap.ForQuery(); if (!_items.Any()) return; var command = buildCommand(); await _runner.ExecuteAsync(command, async (cmd, tk) => { using (var reader = await command.ExecuteReaderAsync(tk).ConfigureAwait(false)) { await _items[0].Read(reader, map, token).ConfigureAwait(false); var others = _items.Skip(1).ToArray(); foreach (var item in others) { var hasNext = await reader.NextResultAsync(token).ConfigureAwait(false); if (!hasNext) throw new InvalidOperationException("There is no next result to read over."); await item.Read(reader, map, token).ConfigureAwait(false); } } return 0; }, token).ConfigureAwait(false); } public void ExecuteSynchronously() { var map = _identityMap.ForQuery(); if (!_items.Any()) return; var command = buildCommand(); _runner.Execute(command, cmd => { using (var reader = command.ExecuteReader()) { _items[0].Read(reader, map); _items.Skip(1).Each(item => { var hasNext = reader.NextResult(); if (!hasNext) throw new InvalidOperationException("There is no next result to read over."); item.Read(reader, map); }); } }); } public Task<TResult> Query<TDoc, TResult>(ICompiledQuery<TDoc, TResult> query) { QueryStatistics stats; var handler = _store.HandlerFactory.HandlerFor(query, out stats); return AddItem(handler, stats); } public Task<T> AggregateStream<T>(Guid streamId, int version = 0, DateTime? timestamp = null) where T : class, new() { var inner = new EventQueryHandler(new EventSelector(_store.Events, _store.Serializer), streamId, version, timestamp); var aggregator = _store.Events.AggregateFor<T>(); var handler = new AggregationQueryHandler<T>(aggregator, inner); return AddItem(handler, null); } public Task<IEvent> Load(Guid id) { var handler = new SingleEventQueryHandler(id, _store.Events, _store.Serializer); return AddItem(handler, null); } public Task<StreamState> FetchStreamState(Guid streamId) { var handler = new StreamStateHandler(_store.Events, streamId); return AddItem(handler, null); } public Task<IList<IEvent>> FetchStream(Guid streamId, int version = 0, DateTime? timestamp = null) { var selector = new EventSelector(_store.Events, _store.Serializer); var handler = new EventQueryHandler(selector, streamId, version, timestamp); return AddItem(handler, null); } public Task<T> AddItem<T>(IQueryHandler<T> handler, QueryStatistics stats) { _parent.Tenant.EnsureStorageExists(handler.SourceType); var item = new BatchQueryItem<T>(handler, stats); _items.Add(item); return item.Result; } private Task<T> load<T>(object id) where T : class { if (_identityMap.Has<T>(id)) return Task.FromResult(_identityMap.Retrieve<T>(id)); var mapping = _parent.Tenant.MappingFor(typeof(T)).ToQueryableDocument(); return AddItem(new LoadByIdHandler<T>(_parent.Tenant.StorageFor<T>(), mapping, id), null); } public Task<bool> Any<TDoc>(IMartenQueryable<TDoc> queryable) { return AddItem(queryable.ToLinqQuery().ToAny(), null); } public Task<long> Count<TDoc>(IMartenQueryable<TDoc> queryable) { return AddItem(queryable.ToLinqQuery().ToCount<long>(), null); } internal Task<IList<T>> Query<T>(IMartenQueryable<T> queryable) { var expression = queryable.Expression; var query = QueryParser.GetParsedQuery(expression); return AddItem(new LinqQuery<T>(_store, query, queryable.Includes.ToArray(), queryable.Statistics).ToList(), queryable.Statistics); } public Task<T> First<T>(IMartenQueryable<T> queryable) { var query = queryable.ToLinqQuery(); return AddItem(OneResultHandler<T>.First(query), queryable.Statistics); } public Task<T> FirstOrDefault<T>(IMartenQueryable<T> queryable) { var query = queryable.ToLinqQuery(); return AddItem(OneResultHandler<T>.FirstOrDefault(query), queryable.Statistics); } public Task<T> Single<T>(IMartenQueryable<T> queryable) { var query = queryable.ToLinqQuery(); return AddItem(OneResultHandler<T>.Single(query), queryable.Statistics); } public Task<T> SingleOrDefault<T>(IMartenQueryable<T> queryable) { var query = queryable.ToLinqQuery(); return AddItem(OneResultHandler<T>.SingleOrDefault(query), queryable.Statistics); } public Task<TResult> Min<TResult>(IQueryable<TResult> queryable) { var linqQuery = queryable.As<IMartenQueryable<TResult>>().ToLinqQuery(); return AddItem(AggregateQueryHandler<TResult>.Min(linqQuery), null); } public Task<TResult> Max<TResult>(IQueryable<TResult> queryable) { var linqQuery = queryable.As<IMartenQueryable<TResult>>().ToLinqQuery(); return AddItem(AggregateQueryHandler<TResult>.Max(linqQuery), null); } public Task<TResult> Sum<TResult>(IQueryable<TResult> queryable) { var linqQuery = queryable.As<IMartenQueryable<TResult>>().ToLinqQuery(); return AddItem(AggregateQueryHandler<TResult>.Sum(linqQuery), null); } public Task<double> Average<T>(IQueryable<T> queryable) { var linqQuery = queryable.As<IMartenQueryable<T>>().ToLinqQuery(); return AddItem(AggregateQueryHandler<double>.Average(linqQuery), null); } public class BatchLoadByKeys<TDoc> : IBatchLoadByKeys<TDoc> where TDoc : class { private readonly BatchedQuery _parent; public BatchLoadByKeys(BatchedQuery parent) { _parent = parent; } public Task<IList<TDoc>> ById<TKey>(params TKey[] keys) { return load(keys); } public Task<IList<TDoc>> ByIdList<TKey>(IEnumerable<TKey> keys) { return load(keys.ToArray()); } private Task<IList<TDoc>> load<TKey>(TKey[] keys) { var tenant = _parent._parent.Tenant; var resolver = tenant.StorageFor<TDoc>(); var mapping = tenant.MappingFor(typeof(TDoc)).ToQueryableDocument(); return _parent.AddItem(new LoadByIdArrayHandler<TDoc, TKey>(resolver, mapping, keys), null); } } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Xen2D; using XenAspects; namespace Demo_CompositeExtent { #region entry point #if WINDOWS || XBOX static class Program { /// <summary> /// The main entry point for the application. /// </summary> static void Main( string[] args ) { using( GameMain game = new GameMain() ) { game.Run(); } } } #endif #endregion public enum Textures : int { [ContentIdentifier( "textures\\colored_rect_200x200" )] ColoredRect, [ContentIdentifier( "textures\\explosion0" )] Explosion, [ContentIdentifier( "textures\\marker_blue" )] Marker_Blue, [ContentIdentifier( "textures\\marker_green" )] Marker_Green, [ContentIdentifier( "textures\\marker_red" )] Marker_Red, [ContentIdentifier( "textures\\gray_rect_100x200" )] GrayRect, } /// <summary> /// This demo shows how composite extents can be used to apply a transform uniformly to a set of sprites. /// Press W,A,S,D,Q,E,Z,C to transform the composite /// Hold down 1 and Press W,A,S,D,Q,E,Z,C to transform the colored square /// Hold down 2 and Press W,A,S,D,Q,E,Z,C to transform the gray rectangle /// Press Insert to toggle whether the texture is drawn /// Press Home to toggle whether the axis-aligned bounding box is drawn /// Press PageUp to toggle whether extent tracing and key points /// /// Keypoints legend: /// Green- Top Left /// Red- Origin /// Blue- Center /// /// NOTE: The composite extent has all three keypoints collapsed into a single point, and thus will display only a green point /// </summary> public class GameMain : Game { Texture2DCache _textures; SpriteBatch _spriteBatch; RenderParams _renderParamsTemplate = RenderParams.Default; KeyboardState _previousKeyboardState; StaticSprite _child1; StaticSprite _child2; StaticSprite _markerAnchor_Blue; StaticSprite _markerTopLeft_Red; StaticSprite _markerCompositeAnchor_Green; CompositeExtent _compositeExtent; bool _contentLoaded = false; public GameMain() { Globals.Graphics = new GraphicsDeviceManager( this ); Content.RootDirectory = "Content"; Globals.Content = Content; } protected override void LoadContent() { _textures = new Texture2DCache( typeof( Textures ) ); _spriteBatch = new SpriteBatch( Globals.GraphicsDevice ); _child1 = StaticSprite.Acquire( _textures[ (int)Textures.ColoredRect ], new Vector2( 100, 100 ) ); _child1.LayerDepth = 1; _child2 = StaticSprite.Acquire( _textures[ (int)Textures.GrayRect ], new Vector2( 25, 50 ) ); _child2.RenderingExtent.Anchor = new Vector2( 250, 250 ); _child2.LayerDepth = 1; _markerAnchor_Blue = StaticSprite.Acquire( _textures[ (int)Textures.Marker_Blue ], new Vector2( 4, 4 ) ); _markerAnchor_Blue.LayerDepth = 0; _renderParamsTemplate.GetTexture_MarkCenter = new Getter<ISprite>( () => { return _markerAnchor_Blue; } ); _markerTopLeft_Red = StaticSprite.Acquire( _textures[ (int)Textures.Marker_Red ], new Vector2( 4, 4 ) ); _markerTopLeft_Red.LayerDepth = 0; _renderParamsTemplate.GetTexture_MarkOrigin = new Getter<ISprite>( () => { return _markerTopLeft_Red; } ); _markerCompositeAnchor_Green = StaticSprite.Acquire( _textures[ (int)Textures.Marker_Green ], new Vector2( 4, 4 ) ); _markerCompositeAnchor_Green.LayerDepth = 0; _renderParamsTemplate.GetTexture_MarkTopLeft = new Getter<ISprite>( () => { return _markerCompositeAnchor_Green; } ); _compositeExtent = new CompositeExtent(); _compositeExtent.Add( _child1.RenderingExtent ); _compositeExtent.Add( _child2.RenderingExtent ); _contentLoaded = true; } protected override void Update( GameTime gameTime ) { base.Update( gameTime ); KeyboardState ks = Keyboard.GetState(); if( ks.IsKeyDown( Keys.Escape ) ) { this.Exit(); } else if( ks.IsKeyDown( Keys.D1 ) ) { #region Child1 if( ks.IsKeyDown( Keys.A ) ) { _child1.RenderingExtent.Anchor -= new Vector2( 5, 0 ); } if( ks.IsKeyDown( Keys.D ) ) { _child1.RenderingExtent.Anchor += new Vector2( 5, 0 ); } if( ks.IsKeyDown( Keys.W ) ) { _child1.RenderingExtent.Anchor += new Vector2( 0, -5 ); } if( ks.IsKeyDown( Keys.S ) ) { _child1.RenderingExtent.Anchor += new Vector2( 0, 5 ); } if( ks.IsKeyDown( Keys.Q ) ) { _child1.RenderingExtent.Angle -= 0.04f; } if( ks.IsKeyDown( Keys.E ) ) { _child1.RenderingExtent.Angle += 0.04f; } if( ks.IsKeyDown( Keys.Z ) ) { _child1.RenderingExtent.Scale *= 1.04f; } if( ks.IsKeyDown( Keys.C ) ) { _child1.RenderingExtent.Scale /= 1.04f; } #endregion } else if( ks.IsKeyDown( Keys.D2 ) ) { #region Child2 if( ks.IsKeyDown( Keys.A ) ) { _child2.RenderingExtent.Anchor -= new Vector2( 5, 0 ); } if( ks.IsKeyDown( Keys.D ) ) { _child2.RenderingExtent.Anchor += new Vector2( 5, 0 ); } if( ks.IsKeyDown( Keys.W ) ) { _child2.RenderingExtent.Anchor += new Vector2( 0, -5 ); } if( ks.IsKeyDown( Keys.S ) ) { _child2.RenderingExtent.Anchor += new Vector2( 0, 5 ); } if( ks.IsKeyDown( Keys.Q ) ) { _child2.RenderingExtent.Angle -= 0.04f; } if( ks.IsKeyDown( Keys.E ) ) { _child2.RenderingExtent.Angle += 0.04f; } if( ks.IsKeyDown( Keys.Z ) ) { _child2.RenderingExtent.Scale *= 1.04f; } if( ks.IsKeyDown( Keys.C ) ) { _child2.RenderingExtent.Scale /= 1.04f; } #endregion } else { #region Composite if( ks.IsKeyDown( Keys.A ) ) { _compositeExtent.Anchor -= new Vector2( 5, 0 ); } if( ks.IsKeyDown( Keys.D ) ) { _compositeExtent.Anchor += new Vector2( 5, 0 ); } if( ks.IsKeyDown( Keys.W ) ) { _compositeExtent.Anchor += new Vector2( 0, -5 ); } if( ks.IsKeyDown( Keys.S ) ) { _compositeExtent.Anchor += new Vector2( 0, 5 ); } if( ks.IsKeyDown( Keys.Q ) ) { _compositeExtent.Angle -= 0.04f; } if( ks.IsKeyDown( Keys.E ) ) { _compositeExtent.Angle += 0.04f; } if( ks.IsKeyDown( Keys.Z ) ) { _compositeExtent.Scale *= 1.04f; } if( ks.IsKeyDown( Keys.C ) ) { _compositeExtent.Scale /= 1.04f; } #endregion } if( _previousKeyboardState.IsKeyDown( Keys.Insert ) && ks.IsKeyUp( Keys.Insert ) ) _renderParamsTemplate.Mode ^= RenderMode.Texture; if( _previousKeyboardState.IsKeyDown( Keys.Home ) && ks.IsKeyUp( Keys.Home ) ) _renderParamsTemplate.Mode ^= RenderMode.TraceBoundingBox; if( _previousKeyboardState.IsKeyDown( Keys.PageUp ) && ks.IsKeyUp( Keys.PageUp ) ) _renderParamsTemplate.Mode ^= RenderMode.TraceRenderingExtent; _previousKeyboardState = ks; } protected override void Draw( GameTime gameTime ) { GraphicsDevice.Clear( Color.CornflowerBlue ); Matrix worldToCamera = Matrix.Identity; _spriteBatch.Begin(); if( _contentLoaded ) { _spriteBatch.DrawSprite( _child1, worldToCamera, _renderParamsTemplate ); _spriteBatch.DrawSprite( _child2, worldToCamera, _renderParamsTemplate ); _spriteBatch.DrawPolygonExtent( _compositeExtent, worldToCamera, _renderParamsTemplate ); } _spriteBatch.End(); base.Draw( gameTime ); } } }
// 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; namespace System.DirectoryServices.AccountManagement { #if TESTHOOK public class AccountInfo #else internal class AccountInfo #endif { // // Properties exposed to the public through AuthenticablePrincipal // // AccountLockoutTime private Nullable<DateTime> _accountLockoutTime = null; private LoadState _accountLockoutTimeLoaded = LoadState.NotSet; public Nullable<DateTime> AccountLockoutTime { get { return _owningPrincipal.HandleGet<Nullable<DateTime>>(ref _accountLockoutTime, PropertyNames.AcctInfoAcctLockoutTime, ref _accountLockoutTimeLoaded); } } // LastLogon private Nullable<DateTime> _lastLogon = null; private LoadState _lastLogonLoaded = LoadState.NotSet; public Nullable<DateTime> LastLogon { get { return _owningPrincipal.HandleGet<Nullable<DateTime>>(ref _lastLogon, PropertyNames.AcctInfoLastLogon, ref _lastLogonLoaded); } } // PermittedWorkstations private PrincipalValueCollection<string> _permittedWorkstations = new PrincipalValueCollection<string>(); private LoadState _permittedWorkstationsLoaded = LoadState.NotSet; public PrincipalValueCollection<string> PermittedWorkstations { get { if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoPermittedWorkstations)) throw new InvalidOperationException(SR.InvalidPropertyForStore); return _owningPrincipal.HandleGet<PrincipalValueCollection<string>>(ref _permittedWorkstations, PropertyNames.AcctInfoPermittedWorkstations, ref _permittedWorkstationsLoaded); } } // PermittedLogonTimes // We have to handle the change-tracking for this differently than for the other properties, because // a byte[] is mutable. After calling the get accessor, the app can change the permittedLogonTimes, // without needing to ever call the set accessor. Therefore, rather than a simple "changed" flag set // by the set accessor, we need to track the original value of the property, and flag it as changed // if current value != original value. private byte[] _permittedLogonTimes = null; private byte[] _permittedLogonTimesOriginal = null; private LoadState _permittedLogonTimesLoaded = LoadState.NotSet; public byte[] PermittedLogonTimes { get { return _owningPrincipal.HandleGet<byte[]>(ref _permittedLogonTimes, PropertyNames.AcctInfoPermittedLogonTimes, ref _permittedLogonTimesLoaded); } set { // We don't use HandleSet<T> here because of the slightly non-standard implementation of the change-tracking // for this property. // Check that we actually support this propery in our store //this.owningPrincipal.CheckSupportedProperty(PropertyNames.AcctInfoPermittedLogonTimes); if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoPermittedLogonTimes)) throw new InvalidOperationException(SR.InvalidPropertyForStore); // If we get to this point we know that the value of the property has changed and we should not load it from the store. // If value is retrived the state is set to loaded. Even if user modifies the reference we will // not overwrite it because we mark it as loaded. // If the user sets it before reading it we mark it as changed. When the users accesses it we just return the current // value. All change tracking to the store is done off of an actual object comparison because users can change the value // either through property set or modifying the reference returned. _permittedLogonTimesLoaded = LoadState.Changed; _permittedLogonTimes = value; } } // AccountExpirationDate private Nullable<DateTime> _expirationDate = null; private LoadState _expirationDateChanged = LoadState.NotSet; public Nullable<DateTime> AccountExpirationDate { get { return _owningPrincipal.HandleGet<Nullable<DateTime>>(ref _expirationDate, PropertyNames.AcctInfoExpirationDate, ref _expirationDateChanged); } set { if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoExpirationDate)) throw new InvalidOperationException(SR.InvalidPropertyForStore); _owningPrincipal.HandleSet<Nullable<DateTime>>(ref _expirationDate, value, ref _expirationDateChanged, PropertyNames.AcctInfoExpirationDate); } } // SmartcardLogonRequired private bool _smartcardLogonRequired = false; private LoadState _smartcardLogonRequiredChanged = LoadState.NotSet; public bool SmartcardLogonRequired { get { return _owningPrincipal.HandleGet<bool>(ref _smartcardLogonRequired, PropertyNames.AcctInfoSmartcardRequired, ref _smartcardLogonRequiredChanged); } set { if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoSmartcardRequired)) throw new InvalidOperationException(SR.InvalidPropertyForStore); _owningPrincipal.HandleSet<bool>(ref _smartcardLogonRequired, value, ref _smartcardLogonRequiredChanged, PropertyNames.AcctInfoSmartcardRequired); } } // DelegationPermitted private bool _delegationPermitted = false; private LoadState _delegationPermittedChanged = LoadState.NotSet; public bool DelegationPermitted { get { return _owningPrincipal.HandleGet<bool>(ref _delegationPermitted, PropertyNames.AcctInfoDelegationPermitted, ref _delegationPermittedChanged); } set { if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoDelegationPermitted)) throw new InvalidOperationException(SR.InvalidPropertyForStore); _owningPrincipal.HandleSet<bool>(ref _delegationPermitted, value, ref _delegationPermittedChanged, PropertyNames.AcctInfoDelegationPermitted); } } // BadLogonCount private int _badLogonCount = 0; private LoadState _badLogonCountChanged = LoadState.NotSet; public int BadLogonCount { get { return _owningPrincipal.HandleGet<int>(ref _badLogonCount, PropertyNames.AcctInfoBadLogonCount, ref _badLogonCountChanged); } } // HomeDirectory private string _homeDirectory = null; private LoadState _homeDirectoryChanged = LoadState.NotSet; public string HomeDirectory { get { return _owningPrincipal.HandleGet<string>(ref _homeDirectory, PropertyNames.AcctInfoHomeDirectory, ref _homeDirectoryChanged); } set { if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoHomeDirectory)) throw new InvalidOperationException(SR.InvalidPropertyForStore); _owningPrincipal.HandleSet<string>(ref _homeDirectory, value, ref _homeDirectoryChanged, PropertyNames.AcctInfoHomeDirectory); } } // HomeDrive private string _homeDrive = null; private LoadState _homeDriveChanged = LoadState.NotSet; public string HomeDrive { get { return _owningPrincipal.HandleGet<string>(ref _homeDrive, PropertyNames.AcctInfoHomeDrive, ref _homeDriveChanged); } set { if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoHomeDrive)) throw new InvalidOperationException(SR.InvalidPropertyForStore); _owningPrincipal.HandleSet<string>(ref _homeDrive, value, ref _homeDriveChanged, PropertyNames.AcctInfoHomeDrive); } } // ScriptPath private string _scriptPath = null; private LoadState _scriptPathChanged = LoadState.NotSet; public string ScriptPath { get { return _owningPrincipal.HandleGet<string>(ref _scriptPath, PropertyNames.AcctInfoScriptPath, ref _scriptPathChanged); } set { if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoScriptPath)) throw new InvalidOperationException(SR.InvalidPropertyForStore); _owningPrincipal.HandleSet<string>(ref _scriptPath, value, ref _scriptPathChanged, PropertyNames.AcctInfoScriptPath); } } // // Methods exposed to the public through AuthenticablePrincipal // public bool IsAccountLockedOut() { if (!_owningPrincipal.unpersisted) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AccountInfo", "IsAccountLockedOut: sending lockout query"); Debug.Assert(_owningPrincipal.Context != null); return _owningPrincipal.GetStoreCtxToUse().IsLockedOut(_owningPrincipal); } else { // A Principal that hasn't even been persisted can't be locked out return false; } } public void UnlockAccount() { if (!_owningPrincipal.unpersisted) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AccountInfo", "UnlockAccount: sending unlock request"); Debug.Assert(_owningPrincipal.Context != null); _owningPrincipal.GetStoreCtxToUse().UnlockAccount(_owningPrincipal); } // Since a Principal that's not persisted can't have been locked-out, // there's nothing to do in that case } // // Internal constructor // internal AccountInfo(AuthenticablePrincipal principal) { _owningPrincipal = principal; } // // Private implementation // private AuthenticablePrincipal _owningPrincipal; // // Load/Store // // // Loading with query results // internal void LoadValueIntoProperty(string propertyName, object value) { // GlobalDebug.WriteLineIf(GlobalDebug.Info, "AccountInfo", "LoadValueIntoProperty: name=" + propertyName + " value=" + value.ToString()); switch (propertyName) { case (PropertyNames.AcctInfoAcctLockoutTime): _accountLockoutTime = (Nullable<DateTime>)value; _accountLockoutTimeLoaded = LoadState.Loaded; break; case (PropertyNames.AcctInfoLastLogon): _lastLogon = (Nullable<DateTime>)value; _lastLogonLoaded = LoadState.Loaded; break; case (PropertyNames.AcctInfoPermittedWorkstations): _permittedWorkstations.Load((List<string>)value); _permittedWorkstationsLoaded = LoadState.Loaded; break; case (PropertyNames.AcctInfoPermittedLogonTimes): _permittedLogonTimes = (byte[])value; _permittedLogonTimesOriginal = (byte[])((byte[])value).Clone(); _permittedLogonTimesLoaded = LoadState.Loaded; break; case (PropertyNames.AcctInfoExpirationDate): _expirationDate = (Nullable<DateTime>)value; _expirationDateChanged = LoadState.Loaded; break; case (PropertyNames.AcctInfoSmartcardRequired): _smartcardLogonRequired = (bool)value; _smartcardLogonRequiredChanged = LoadState.Loaded; break; case (PropertyNames.AcctInfoDelegationPermitted): _delegationPermitted = (bool)value; _delegationPermittedChanged = LoadState.Loaded; break; case (PropertyNames.AcctInfoBadLogonCount): _badLogonCount = (int)value; _badLogonCountChanged = LoadState.Loaded; break; case (PropertyNames.AcctInfoHomeDirectory): _homeDirectory = (string)value; _homeDirectoryChanged = LoadState.Loaded; break; case (PropertyNames.AcctInfoHomeDrive): _homeDrive = (string)value; _homeDriveChanged = LoadState.Loaded; break; case (PropertyNames.AcctInfoScriptPath): _scriptPath = (string)value; _scriptPathChanged = LoadState.Loaded; break; default: Debug.Fail(String.Format(CultureInfo.CurrentCulture, "AccountInfo.LoadValueIntoProperty: fell off end looking for {0}", propertyName)); break; } } // // Getting changes to persist (or to build a query from a QBE filter) // // Given a property name, returns true if that property has changed since it was loaded, false otherwise. internal bool GetChangeStatusForProperty(string propertyName) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AccountInfo", "GetChangeStatusForProperty: name=" + propertyName); switch (propertyName) { case (PropertyNames.AcctInfoPermittedWorkstations): return _permittedWorkstations.Changed; case (PropertyNames.AcctInfoPermittedLogonTimes): // If they're equal, they have _not_ changed if ((_permittedLogonTimes == null) && (_permittedLogonTimesOriginal == null)) return false; if ((_permittedLogonTimes == null) || (_permittedLogonTimesOriginal == null)) return true; return !Utils.AreBytesEqual(_permittedLogonTimes, _permittedLogonTimesOriginal); case (PropertyNames.AcctInfoExpirationDate): return _expirationDateChanged == LoadState.Changed; case (PropertyNames.AcctInfoSmartcardRequired): return _smartcardLogonRequiredChanged == LoadState.Changed; case (PropertyNames.AcctInfoDelegationPermitted): return _delegationPermittedChanged == LoadState.Changed; case (PropertyNames.AcctInfoHomeDirectory): return _homeDirectoryChanged == LoadState.Changed; case (PropertyNames.AcctInfoHomeDrive): return _homeDriveChanged == LoadState.Changed; case (PropertyNames.AcctInfoScriptPath): return _scriptPathChanged == LoadState.Changed; default: Debug.Fail(String.Format(CultureInfo.CurrentCulture, "AccountInfo.GetChangeStatusForProperty: fell off end looking for {0}", propertyName)); return false; } } // Given a property name, returns the current value for the property. internal object GetValueForProperty(string propertyName) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AccountInfo", "GetValueForProperty: name=" + propertyName); switch (propertyName) { case (PropertyNames.AcctInfoPermittedWorkstations): return _permittedWorkstations; case (PropertyNames.AcctInfoPermittedLogonTimes): return _permittedLogonTimes; case (PropertyNames.AcctInfoExpirationDate): return _expirationDate; case (PropertyNames.AcctInfoSmartcardRequired): return _smartcardLogonRequired; case (PropertyNames.AcctInfoDelegationPermitted): return _delegationPermitted; case (PropertyNames.AcctInfoHomeDirectory): return _homeDirectory; case (PropertyNames.AcctInfoHomeDrive): return _homeDrive; case (PropertyNames.AcctInfoScriptPath): return _scriptPath; default: Debug.Fail(String.Format(CultureInfo.CurrentCulture, "AccountInfo.GetValueForProperty: fell off end looking for {0}", propertyName)); return null; } } // Reset all change-tracking status for all properties on the object to "unchanged". internal void ResetAllChangeStatus() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AccountInfo", "ResetAllChangeStatus"); _permittedWorkstations.ResetTracking(); _permittedLogonTimesOriginal = (_permittedLogonTimes != null) ? (byte[])_permittedLogonTimes.Clone() : null; _expirationDateChanged = (_expirationDateChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; _smartcardLogonRequiredChanged = (_smartcardLogonRequiredChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; _delegationPermittedChanged = (_delegationPermittedChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; _homeDirectoryChanged = (_homeDirectoryChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; _homeDriveChanged = (_homeDriveChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; _scriptPathChanged = (_scriptPathChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; } } }
#if !LOCALTEST using System.Threading; using System.Collections.Generic; using System.IO; namespace System.Globalization { public class CultureInfo { #region Static methods private static Dictionary<string, CultureInfo> shareByName = new Dictionary<string,CultureInfo>(); private static CultureInfo invariantCulture = null; public static CultureInfo GetCultureInfo(string name) { // Always use lower-case version of name lock (shareByName) { CultureInfo ci; if (!shareByName.TryGetValue(name.ToLowerInvariant(), out ci)) { ci = new CultureInfo(name); // Don't put in cache, as the constructor already does this } return ci; } } public static CultureInfo CurrentCulture { get { return Thread.CurrentThread.CurrentCulture; } } public static CultureInfo InvariantCulture { get { if (invariantCulture == null) { invariantCulture = new CultureInfo(string.Empty); } return invariantCulture; } } public static CultureInfo[] GetCultures(CultureTypes types) { DirectoryInfo cultureDir = new DirectoryInfo(Environment.CultureDirectory); List<CultureInfo> ret = new List<CultureInfo>(); foreach (FileInfo fi in cultureDir.GetFiles()) { CultureInfo ci = CultureInfo.GetCultureInfo(fi.Name); if ((ci.cultureTypes & types) > 0) { ret.Add(ci); } } return ret.ToArray(); } #endregion private string name; private int lcid; private string parentName; private CultureInfo parent = null; private string displayName; private string englishName; private string nativeName; private string twoLetterISOLanguageName; private string threeLetterISOLanguageName; private string threeLetterWindowsLanguageName; private CultureTypes cultureTypes; private string ietfLanguageTag; private bool isNeutralCulture; private NumberFormatInfo numberFormatInfo; private TextInfo textInfo; private DateTimeFormatInfo dateTimeFormat; public CultureInfo(string name) { if (name == null) { throw new ArgumentNullException(); } if (name.Length == 0) { ConstructInvariant(); return; } // Always use lower-case version of name string nameLower = name.ToLowerInvariant(); // If this culture is already loaded and cached, then just copy all of its settings lock (shareByName) { CultureInfo cached; if (shareByName.TryGetValue(nameLower, out cached)) { CopyFrom(cached); return; } } // Not cached, so create from new and place in cache ConstructFromFile(name); } private void ConstructInvariant() { this.name = string.Empty; this.displayName = this.englishName = this.nativeName = "Invariant Language (Invariant Country)"; this.lcid = 0x7f; this.numberFormatInfo = NumberFormatInfo.InvariantInfo; this.dateTimeFormat = DateTimeFormatInfo.InvariantInfo; } private void ConstructFromFile(string name) { string fileName = Environment.CultureDirectory + Path.DirectorySeparatorStr + name; try { using (StreamReader s = File.OpenText(fileName)) { this.name = s.ReadLine(); this.lcid = int.Parse(s.ReadLine().Substring(2), NumberStyles.HexNumber); this.parentName = s.ReadLine(); this.englishName = s.ReadLine(); this.nativeName = s.ReadLine(); this.displayName = s.ReadLine(); this.twoLetterISOLanguageName = s.ReadLine(); this.threeLetterISOLanguageName = s.ReadLine(); this.threeLetterWindowsLanguageName = s.ReadLine(); string calendarName = s.ReadLine(); // Calendar s.ReadLine(); // Optional calendars this.cultureTypes = (CultureTypes)int.Parse(s.ReadLine()); this.ietfLanguageTag = s.ReadLine(); this.isNeutralCulture = bool.Parse(s.ReadLine()); this.textInfo = new TextInfo(this, s); if (!this.isNeutralCulture) { this.numberFormatInfo = new NumberFormatInfo(s); this.dateTimeFormat = new DateTimeFormatInfo(s, calendarName); } else { this.numberFormatInfo = null; this.dateTimeFormat = null; } } } catch (FileNotFoundException) { throw new ArgumentException(string.Format("{0} is not a valid culture", name)); } lock (shareByName) { shareByName.Add(name.ToLowerInvariant(), this); } } private void CopyFrom(CultureInfo ci) { this.name = ci.name; this.lcid = ci.lcid; this.parent = ci.parent; this.englishName = ci.englishName; this.nativeName = ci.nativeName; this.displayName = ci.displayName; this.twoLetterISOLanguageName = ci.twoLetterISOLanguageName; this.threeLetterISOLanguageName = ci.threeLetterISOLanguageName; this.threeLetterWindowsLanguageName = ci.threeLetterWindowsLanguageName; this.cultureTypes = ci.cultureTypes; this.ietfLanguageTag = ci.ietfLanguageTag; this.isNeutralCulture = ci.isNeutralCulture; this.textInfo = ci.textInfo; this.numberFormatInfo = ci.numberFormatInfo; this.dateTimeFormat = ci.dateTimeFormat; } public bool IsReadOnly { get{ // At the moment, all CultureInfo's are read-only return true; } } public virtual NumberFormatInfo NumberFormat { get { if (this.numberFormatInfo == null) { throw new NotSupportedException("Not supported for neutral cultures"); } return this.numberFormatInfo; } } public virtual DateTimeFormatInfo DateTimeFormat { get { if (this.dateTimeFormat == null) { throw new NotSupportedException("Not supported for neutral cultures"); } return this.dateTimeFormat; } } public virtual int LCID { get { return this.lcid; } } public virtual string Name { get { return this.name; } } public virtual CultureInfo Parent { get { if (this.parent == null) { this.parent = CultureInfo.GetCultureInfo(this.parentName); } return this.parent; } } public virtual string DisplayName { get { return this.displayName; } } public virtual string EnglishName { get { return this.englishName; } } public virtual string NativeName { get { return this.nativeName; } } public virtual string TwoLetterISOLanguageName { get { return this.twoLetterISOLanguageName; } } public virtual string ThreeLetterISOLanguageName { get { return this.threeLetterISOLanguageName; } } public virtual string ThreeLetterWindowsLanguageName { get { return this.threeLetterWindowsLanguageName; } } public virtual CultureTypes CultureTypes { get { return this.cultureTypes; } } public virtual string IetfLanguageTag { get { return this.ietfLanguageTag; } } public virtual bool IsNeutralCulture { get { return this.isNeutralCulture; } } public virtual TextInfo TextInfo { get { return this.textInfo; } } public override string ToString() { return this.name; } } } #endif
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyDate { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; /// <summary> /// Extension methods for Date. /// </summary> public static partial class DateExtensions { /// <summary> /// Get null date value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateTime? GetNull(this IDate operations) { return Task.Factory.StartNew(s => ((IDate)s).GetNullAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get null date value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateTime?> GetNullAsync(this IDate operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get invalid date value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateTime? GetInvalidDate(this IDate operations) { return Task.Factory.StartNew(s => ((IDate)s).GetInvalidDateAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get invalid date value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateTime?> GetInvalidDateAsync(this IDate operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetInvalidDateWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get overflow date value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateTime? GetOverflowDate(this IDate operations) { return Task.Factory.StartNew(s => ((IDate)s).GetOverflowDateAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get overflow date value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateTime?> GetOverflowDateAsync(this IDate operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetOverflowDateWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get underflow date value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateTime? GetUnderflowDate(this IDate operations) { return Task.Factory.StartNew(s => ((IDate)s).GetUnderflowDateAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get underflow date value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateTime?> GetUnderflowDateAsync(this IDate operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetUnderflowDateWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put max date value 9999-12-31 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='dateBody'> /// </param> public static void PutMaxDate(this IDate operations, DateTime dateBody) { Task.Factory.StartNew(s => ((IDate)s).PutMaxDateAsync(dateBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put max date value 9999-12-31 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='dateBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutMaxDateAsync(this IDate operations, DateTime dateBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutMaxDateWithHttpMessagesAsync(dateBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get max date value 9999-12-31 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateTime? GetMaxDate(this IDate operations) { return Task.Factory.StartNew(s => ((IDate)s).GetMaxDateAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get max date value 9999-12-31 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateTime?> GetMaxDateAsync(this IDate operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetMaxDateWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put min date value 0000-01-01 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='dateBody'> /// </param> public static void PutMinDate(this IDate operations, DateTime dateBody) { Task.Factory.StartNew(s => ((IDate)s).PutMinDateAsync(dateBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put min date value 0000-01-01 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='dateBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutMinDateAsync(this IDate operations, DateTime dateBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutMinDateWithHttpMessagesAsync(dateBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get min date value 0000-01-01 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateTime? GetMinDate(this IDate operations) { return Task.Factory.StartNew(s => ((IDate)s).GetMinDateAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get min date value 0000-01-01 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateTime?> GetMinDateAsync(this IDate operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetMinDateWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using Newtonsoft.Json.Utilities; using System.Globalization; namespace Newtonsoft.Json.Linq { /// <summary> /// Represents a JSON constructor. /// </summary> public class JConstructor : JContainer { private string _name; private readonly List<JToken> _values = new List<JToken>(); /// <summary> /// Gets the container's children tokens. /// </summary> /// <value>The container's children tokens.</value> protected override IList<JToken> ChildrenTokens { get { return _values; } } /// <summary> /// Gets or sets the name of this constructor. /// </summary> /// <value>The constructor name.</value> public string Name { get { return _name; } set { _name = value; } } /// <summary> /// Gets the node type for this <see cref="JToken"/>. /// </summary> /// <value>The type.</value> public override JTokenType Type { get { return JTokenType.Constructor; } } /// <summary> /// Initializes a new instance of the <see cref="JConstructor"/> class. /// </summary> public JConstructor() { } /// <summary> /// Initializes a new instance of the <see cref="JConstructor"/> class from another <see cref="JConstructor"/> object. /// </summary> /// <param name="other">A <see cref="JConstructor"/> object to copy from.</param> public JConstructor(JConstructor other) : base(other) { _name = other.Name; } /// <summary> /// Initializes a new instance of the <see cref="JConstructor"/> class with the specified name and content. /// </summary> /// <param name="name">The constructor name.</param> /// <param name="content">The contents of the constructor.</param> public JConstructor(string name, params object[] content) : this(name, (object)content) { } /// <summary> /// Initializes a new instance of the <see cref="JConstructor"/> class with the specified name and content. /// </summary> /// <param name="name">The constructor name.</param> /// <param name="content">The contents of the constructor.</param> public JConstructor(string name, object content) : this(name) { Add(content); } /// <summary> /// Initializes a new instance of the <see cref="JConstructor"/> class with the specified name. /// </summary> /// <param name="name">The constructor name.</param> public JConstructor(string name) { ValidationUtils.ArgumentNotNullOrEmpty(name, "name"); _name = name; } internal override bool DeepEquals(JToken node) { JConstructor c = node as JConstructor; return (c != null && _name == c.Name && ContentsEqual(c)); } internal override JToken CloneToken() { return new JConstructor(this); } /// <summary> /// Writes this token to a <see cref="JsonWriter"/>. /// </summary> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { writer.WriteStartConstructor(_name); foreach (JToken token in Children()) { token.WriteTo(writer, converters); } writer.WriteEndConstructor(); } /// <summary> /// Gets the <see cref="JToken"/> with the specified key. /// </summary> /// <value>The <see cref="JToken"/> with the specified key.</value> public override JToken this[object key] { get { ValidationUtils.ArgumentNotNull(key, "o"); if (!(key is int)) throw new ArgumentException("Accessed JConstructor values with invalid key value: {0}. Argument position index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); return GetItem((int)key); } set { ValidationUtils.ArgumentNotNull(key, "o"); if (!(key is int)) throw new ArgumentException("Set JConstructor values with invalid key value: {0}. Argument position index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); SetItem((int)key, value); } } internal override int GetDeepHashCode() { return _name.GetHashCode() ^ ContentsHashCode(); } /// <summary> /// Loads an <see cref="JConstructor"/> from a <see cref="JsonReader"/>. /// </summary> /// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JConstructor"/>.</param> /// <returns>A <see cref="JConstructor"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns> public static new JConstructor Load(JsonReader reader) { if (reader.TokenType == JsonToken.None) { if (!reader.Read()) throw JsonReaderException.Create(reader, "Error reading JConstructor from JsonReader."); } while (reader.TokenType == JsonToken.Comment) { reader.Read(); } if (reader.TokenType != JsonToken.StartConstructor) throw JsonReaderException.Create(reader, "Error reading JConstructor from JsonReader. Current JsonReader item is not a constructor: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); JConstructor c = new JConstructor((string)reader.Value); c.SetLineInfo(reader as IJsonLineInfo); c.ReadTokenFrom(reader); return c; } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public abstract partial class ArmPlatform : ZeligIR.Abstractions.Platform { public enum Comparison : uint { Equal = 0x00, // EQ => Z set NotEqual = 0x01, // NE => Z clear CarrySet = 0x02, // CS/HS => C set CarryClear = 0x03, // CC/LO => C clear Negative = 0x04, // MI => N set PositiveOrZero = 0x05, // PL => N clear Overflow = 0x06, // VS => V set NoOverflow = 0x07, // VC => V clear UnsignedHigherThan = 0x08, // HI => C set and Z clear UnsignedLowerThanOrSame = 0x09, // LS => C clear or Z set SignedGreaterThanOrEqual = 0x0A, // GE => N set and V set, or N clear and V clear (N == V) SignedLessThan = 0x0B, // LT => N set and V clear, or N clear and V set (N != V) SignedGreaterThan = 0x0C, // GT => Z clear, and either N set and V set, or N clear and V clear (Z ==0, N == V) SignedLessThanOrEqual = 0x0D, // LE => Z set, or N set and V clear, or N clear and V set (Z == 1 or N != V) Always = 0x0E, // AL Always (unconditional) NotValid = 0x0F, // UnsignedHigherThanOrSame = CarrySet , UnsignedLowerThan = CarryClear, } [Flags] public enum Capabilities : uint { ARMv4 = 0x00000001, ARMv5 = 0x00000002, ARMv7M = 0x00000004, ARMv7R = 0x00000008, ARMv7A = 0x00000010, VFPv2 = 0x00010000, } // // State // private List< Runtime.Memory.Range > m_memoryBlocks; private Capabilities m_processorCapabilities; private ZeligIR.Abstractions.PlacementRequirements m_memoryRequirement_VectorTable; private ZeligIR.Abstractions.PlacementRequirements m_memoryRequirement_Bootstrap; private ZeligIR.Abstractions.PlacementRequirements m_memoryRequirement_Code; private ZeligIR.Abstractions.PlacementRequirements m_memoryRequirement_Data_RW; private ZeligIR.Abstractions.PlacementRequirements m_memoryRequirement_Data_RO; private bool m_fGotVectorTable; private MethodRepresentation m_vectorTable; // // Constructor Methods // protected ArmPlatform( Capabilities processorCapabilities ) { AllocateState( processorCapabilities ); } protected ArmPlatform( ZeligIR.TypeSystemForCodeTransformation typeSystem , MemoryMapCategory memoryMap , Capabilities processorCapabilities ) : base( typeSystem ) { AllocateState( processorCapabilities ); if(memoryMap != null) { ConfigureMemoryMap( memoryMap ); } //--// List< ZeligIR.Abstractions.RegisterDescriptor > regs = new List< ZeligIR.Abstractions.RegisterDescriptor >(); CreateRegisters( regs ); m_registers = regs.ToArray(); } public override InstructionSet GetInstructionSetProvider() { if(m_instructionSetProvider == null) { InstructionSetVersion iset = new InstructionSetVersion(this.PlatformName, this.PlatformVersion, this.PlatformVFP); if(this.HasVFPv2) { m_instructionSetProvider = new TargetModel.ArmProcessor.InstructionSet_VFP( iset ); } else { m_instructionSetProvider = new TargetModel.ArmProcessor.InstructionSet( iset ); } } return m_instructionSetProvider; } protected virtual void AllocateState( Capabilities processorCapabilities ) { m_processorCapabilities = processorCapabilities; m_memoryBlocks = new List< Runtime.Memory.Range >(); m_memoryRequirement_VectorTable = CreatePlacement( Runtime.MemoryUsage.VectorsTable ); m_memoryRequirement_Bootstrap = CreatePlacement( Runtime.MemoryUsage.Bootstrap ); m_memoryRequirement_Code = CreatePlacement( Runtime.MemoryUsage.Code ); m_memoryRequirement_Data_RO = CreatePlacement( Runtime.MemoryUsage.DataRO ); m_memoryRequirement_Data_RW = CreatePlacement( Runtime.MemoryUsage.DataRW ); } private static ZeligIR.Abstractions.PlacementRequirements CreatePlacement( Runtime.MemoryUsage usage ) { ZeligIR.Abstractions.PlacementRequirements pr = new ZeligIR.Abstractions.PlacementRequirements( sizeof(uint), 0 ); pr.AddConstraint( usage ); return pr; } // // Helper Methods // public override void ApplyTransformation( TransformationContext context ) { ZeligIR.TransformationContextForCodeTransformation context2 = (ZeligIR.TransformationContextForCodeTransformation)context; context2.Push( this ); base.ApplyTransformation( context2 ); context2.Transform( ref m_memoryBlocks ); context2.Transform( ref m_registers ); context2.Transform( ref m_scratchRegister ); context2.Pop(); } public override void RegisterForNotifications( ZeligIR.TypeSystemForCodeTransformation ts , ZeligIR.CompilationSteps.DelegationCache cache ) { cache.Register( this ); cache.Register( new ArmPlatform.PrepareForRegisterAllocation( this ) ); } public override TypeRepresentation GetRuntimeType( ZeligIR.TypeSystemForCodeTransformation ts , ZeligIR.Abstractions.RegisterDescriptor regDesc ) { WellKnownTypes wkt = ts.WellKnownTypes; if(regDesc.InIntegerRegisterFile) { return wkt.System_UIntPtr; } else if(regDesc.InFloatingPointRegisterFile) { if(regDesc.IsDoublePrecision) { return wkt.System_Double; } else { return wkt.System_Single; } } else { return wkt.System_UInt32; } } public override bool CanFitInRegister( TypeRepresentation td ) { if(td.IsFloatingPoint) { if(this.HasVFPv2) { return true; } } return (td.SizeOfHoldingVariableInWords <= 1); } //--// public void AddMemoryBlock( Runtime.Memory.Range range ) { m_memoryBlocks.Add( range ); } public void ConfigureMemoryMap( MemoryMapCategory memoryMap ) { foreach(AbstractCategory.ValueContext ctx in memoryMap.SearchValues( typeof(MemoryCategory) )) { MemoryCategory val = (MemoryCategory)ctx.Value; Runtime.MemoryAttributes flags = val.Characteristics; string name = null; Runtime.MemoryUsage usage = Runtime.MemoryUsage.Undefined; Type hnd = null; if((flags & (Runtime.MemoryAttributes.FLASH | Runtime.MemoryAttributes.RAM)) == 0) { // // Only interested in programmable memories, not peripherals. // continue; } MemorySectionAttribute attrib = ReflectionHelper.GetAttribute< MemorySectionAttribute >( ctx.Field, false ); if(attrib != null) { name = attrib.Name; usage = attrib.Usage; hnd = attrib.ExtensionHandler; } //--// uint address = val.BaseAddress; if(hnd != null) { object obj = Activator.CreateInstance( hnd ); if(obj is IMemoryMapper) { IMemoryMapper itf = (IMemoryMapper)obj; address = itf.GetCacheableAddress( address ); } } UIntPtr beginning = new UIntPtr( address ); UIntPtr end = new UIntPtr( address + val.SizeInBytes ); List< Runtime.Memory.Range > ranges = new List< Runtime.Memory.Range >(); ranges.Add( new Runtime.Memory.Range( beginning, end, name, flags, usage, hnd ) ); foreach(ReserveBlockAttribute resAttrib in ReflectionHelper.GetAttributes< ReserveBlockAttribute >( ctx.Field, false )) { UIntPtr blockStart = AddressMath.Increment( beginning , resAttrib.Offset ); UIntPtr blockEnd = AddressMath.Increment( blockStart, resAttrib.Size ); for(int i = ranges.Count; --i >= 0; ) { var rng = ranges[i]; Runtime.Memory.Range.SubstractionAction action = rng.ComputeSubstraction( blockStart, blockEnd ); if(action != Runtime.Memory.Range.SubstractionAction.RemoveNothing) { ranges.RemoveAt( i ); if(action == Runtime.Memory.Range.SubstractionAction.RemoveStart || action == Runtime.Memory.Range.SubstractionAction.RemoveMiddle ) { ranges.Insert( i, rng.CloneSettings( blockEnd, rng.End ) ); } if(action == Runtime.Memory.Range.SubstractionAction.RemoveMiddle || action == Runtime.Memory.Range.SubstractionAction.RemoveEnd ) { ranges.Insert( i, rng.CloneSettings( rng.Start, blockStart ) ); } } } } foreach(var rng in ranges) { AddMemoryBlock( rng ); } } } //--// public override void GetListOfMemoryBlocks( List< Runtime.Memory.Range > lst ) { lst.AddRange( m_memoryBlocks ); } public override ZeligIR.Abstractions.PlacementRequirements GetMemoryRequirements( object obj ) { if(m_fGotVectorTable == false) { m_fGotVectorTable = true; m_vectorTable = m_typeSystem.TryGetHandler( Runtime.HardwareException.VectorTable ); } // // TODO: Based on profiling data, we could decide to put some code or data in RAM. // MethodRepresentation md = null; if(obj is ZeligIR.ControlFlowGraphStateForCodeTransformation) { md = ((ZeligIR.ControlFlowGraphStateForCodeTransformation)obj).Method; } else if(obj is ZeligIR.BasicBlock) { md = ((ZeligIR.BasicBlock)obj).Owner.Method; } if(md != null) { ZeligIR.Abstractions.PlacementRequirements pr = m_typeSystem.GetPlacementRequirements( md ); if(pr != null) { return pr; } if(md == m_vectorTable) { return m_memoryRequirement_VectorTable; } switch(m_typeSystem.ExtractHardwareExceptionSettingsForMethod( md )) { case Runtime.HardwareException.Bootstrap: case Runtime.HardwareException.Reset: return m_memoryRequirement_Bootstrap; } return m_memoryRequirement_Code; } else if(obj is ZeligIR.DataManager.DataDescriptor) { ZeligIR.DataManager.DataDescriptor dd = (ZeligIR.DataManager.DataDescriptor)obj; ZeligIR.Abstractions.PlacementRequirements pr = dd.PlacementRequirements; if(pr != null) { return pr; } if(dd.IsMutable) { pr = m_memoryRequirement_Data_RW; } else { pr = m_memoryRequirement_Data_RO; } return pr; } throw TypeConsistencyErrorException.Create( "Unable to determine the memory requirements for {0}", obj ); } public override ZeligIR.ImageBuilders.CompilationState CreateCompilationState( ZeligIR.ImageBuilders.Core core , ZeligIR.ControlFlowGraphStateForCodeTransformation cfg ) { return new ArmCompilationState( core, cfg ); } // // Access Methods // public override string PlatformName { get { return InstructionSetVersion.Platform_ARM; } } public override string PlatformVersion { get { string ver = InstructionSetVersion.PlatformVersion_4; if(0 != (m_processorCapabilities & Capabilities.ARMv4)) { ver = InstructionSetVersion.PlatformVersion_4; } else if(0 != ( m_processorCapabilities & Capabilities.ARMv5 )) { ver = InstructionSetVersion.PlatformVersion_5; } return ver; } } public override string PlatformVFP { get { string vfp = InstructionSetVersion.PlatformVFP_NoVFP; if(0 != ( m_processorCapabilities & Capabilities.VFPv2 )) { vfp = InstructionSetVersion.PlatformVFP_VFP; } return vfp; } } public override bool PlatformBigEndian { get { return false; } } public override bool CanUseMultipleConditionCodes { get { return false; } } public override int EstimatedCostOfLoadOperation { get { return 1 + 3; } } public override int EstimatedCostOfStoreOperation { get { return 1 + 2; } } public override uint MemoryAlignment { get { return sizeof(uint); } } public Capabilities ProcessorCapabilities { get { return m_processorCapabilities; } } public bool HasVFPv2 { get { return (m_processorCapabilities & ArmPlatform.Capabilities.VFPv2) != 0; } } } }
using System; using System.Collections.Generic; using System.Text; using FlatRedBall.Graphics.Animation; using FlatRedBall.Instructions; using Microsoft.Xna.Framework.Graphics; namespace FlatRedBall.Graphics.Particle { #region XML Docs /// <summary> /// Defines the state of Sprites immediately after being created by the containing Emitter. /// </summary> #endregion public class EmissionSettings { #region Fields #region Velocity RangeType mVelocityRangeType; float mRadialVelocity = 1; float mRadialVelocityRange = 0; float mXVelocity = -1; float mYVelocity = -1; float mZVelocity = -1; float mXVelocityRange = 2; float mYVelocityRange = 2; float mZVelocityRange = 2; float mWedgeAngle = 0; float mWedgeSpread = (float)System.Math.PI/4.0f; #endregion #region Rotation float mRotationX; float mRotationY; float mRotationZ; float mRotationXVelocity; float mRotationYVelocity; float mRotationZVelocity; float mRotationXRange; float mRotationYRange; float mRotationZRange; float mRotationXVelocityRange; float mRotationYVelocityRange; float mRotationZVelocityRange; bool mBillboarded; #endregion #region Acceleration float mXAcceleration; float mYAcceleration; float mZAcceleration; float mXAccelerationRange; float mYAccelerationRange; float mZAccelerationRange; #endregion #region Scale float mScaleX; float mScaleY; float mScaleXRange; float mScaleYRange; float mScaleXVelocity; float mScaleYVelocity; float mScaleXVelocityRange; float mScaleYVelocityRange; bool mMatchScaleXToY = false; #endregion float mAlpha; float mRed; float mGreen; float mBlue; float mAlphaRate; float mRedRate; float mGreenRate; float mBlueRate; InstructionBlueprintList mInstructions; BlendOperation mBlendOperation; #if FRB_MDX Microsoft.DirectX.Direct3D.TextureOperation mColorOperation; #else ColorOperation mColorOperation; #endif bool mAnimate; AnimationChain mAnimationChain; string mCurrentChainName; float mDrag = 0; #endregion #region Properties #region Velocity /// <summary> /// Sets the type of velocity to use. This impacts which Velocity values are /// applied to emitted Sprites. /// </summary> public RangeType VelocityRangeType { get { return mVelocityRangeType; } set { mVelocityRangeType = value; } } public float RadialVelocity { get { return mRadialVelocity; } set { mRadialVelocity = value; } } public float RadialVelocityRange { get { return mRadialVelocityRange; } set { mRadialVelocityRange = value; } } public float XVelocity { get { return mXVelocity; } set { mXVelocity = value; } } public float YVelocity { get { return mYVelocity; } set { mYVelocity = value; } } public float ZVelocity { get { return mZVelocity; } set { mZVelocity = value; } } public float XVelocityRange { get { return mXVelocityRange; } set { mXVelocityRange = value; } } public float YVelocityRange { get { return mYVelocityRange; } set { mYVelocityRange = value; } } public float ZVelocityRange { get { return mZVelocityRange; } set { mZVelocityRange = value; } } public float WedgeAngle { get { return mWedgeAngle; } set { mWedgeAngle = value; } } public float WedgeSpread { get { return mWedgeSpread; } set { mWedgeSpread = value; } } #endregion #region Rotation public float RotationX { get { return mRotationX; } set { mRotationX = value; } } public float RotationY { get { return mRotationY; } set { mRotationY = value; } } public float RotationZ { get { return mRotationZ; } set { mRotationZ = value; } } public float RotationXVelocity { get { return mRotationXVelocity; } set { mRotationXVelocity = value; } } public float RotationYVelocity { get { return mRotationYVelocity; } set { mRotationYVelocity = value; } } public float RotationZVelocity { get { return mRotationZVelocity; } set { mRotationZVelocity = value; } } public float RotationXRange { get { return mRotationXRange; } set { mRotationXRange = value; } } public float RotationYRange { get { return mRotationYRange; } set { mRotationYRange = value; } } public float RotationZRange { get { return mRotationZRange; } set { mRotationZRange = value; } } public float RotationXVelocityRange { get { return mRotationXVelocityRange; } set { mRotationXVelocityRange = value; } } public float RotationYVelocityRange { get { return mRotationYVelocityRange; } set { mRotationYVelocityRange = value; } } public float RotationZVelocityRange { get { return mRotationZVelocityRange; } set { mRotationZVelocityRange = value; } } public bool Billboarded { get { return mBillboarded; } set { mBillboarded = value; } } #endregion #region Acceleration / Drag public float XAcceleration { get { return mXAcceleration; } set { mXAcceleration = value; } } public float YAcceleration { get { return mYAcceleration; } set { mYAcceleration = value; } } public float ZAcceleration { get { return mZAcceleration; } set { mZAcceleration = value; } } public float XAccelerationRange { get { return mXAccelerationRange; } set { mXAccelerationRange = value; } } public float YAccelerationRange { get { return mYAccelerationRange; } set { mYAccelerationRange = value; } } public float ZAccelerationRange { get { return mZAccelerationRange; } set { mZAccelerationRange = value; } } public float Drag { get { return mDrag; } set { mDrag = value; } } #endregion #region Scale public float ScaleX { get { return mScaleX; } set { mScaleX = value; } } public float ScaleY { get { return mScaleY; } set { mScaleY = value; } } public float ScaleXRange { get { return mScaleXRange; } set { mScaleXRange = value; } } public float ScaleYRange { get { return mScaleYRange; } set { mScaleYRange = value; } } public float ScaleXVelocity { get { return mScaleXVelocity; } set { mScaleXVelocity = value; } } public float ScaleYVelocity { get { return mScaleYVelocity; } set { mScaleYVelocity = value; } } public float ScaleXVelocityRange { get { return mScaleXVelocityRange; } set { mScaleXVelocityRange = value; } } public float ScaleYVelocityRange { get { return mScaleYVelocityRange; } set { mScaleYVelocityRange = value; } } public bool MatchScaleXToY { get { return mMatchScaleXToY; } set { mMatchScaleXToY = value; } } [Obsolete("Use TextureScale instead. TextureScale = PixelSize * 2")] public float PixelSize { get; set; } public float TextureScale { get { return PixelSize * 2.0f; } set { PixelSize = value / 2.0f; } } #endregion #region Tint/Fade/Blend/Color public float Alpha { get { return mAlpha; } set { mAlpha = value; } } public float Red { get { return mRed; } set { mRed = value; } } public float Green { get { return mGreen; } set { mGreen = value; } } public float Blue { get { return mBlue; } set { mBlue = value; } } public float AlphaRate { get { return mAlphaRate; } set { mAlphaRate = value; } } public float RedRate { get { return mRedRate; } set { mRedRate = value; } } public float GreenRate { get { return mGreenRate; } set { mGreenRate = value; } } public float BlueRate { get { return mBlueRate; } set { mBlueRate = value; } } public BlendOperation BlendOperation { get { return mBlendOperation; } set { mBlendOperation = value; } } #if FRB_MDX public Microsoft.DirectX.Direct3D.TextureOperation ColorOperation #else public ColorOperation ColorOperation #endif { get { return mColorOperation; } set { mColorOperation = value; } } #endregion #region Texture/Animation /// <summary> /// Whether or not the emitted particle should automatically animate /// </summary> public bool Animate { get { return mAnimate; } set { mAnimate = value; } } /// <summary> /// The animation chains to use for the particle animation /// </summary> public AnimationChainList AnimationChains { get; set; } /// <summary> /// The currently set animation chain /// </summary> public AnimationChain AnimationChain { get { return mAnimationChain; } set { mAnimationChain = value; } } /// <summary> /// The chain that is currently animating /// </summary> public string CurrentChainName { get { return mCurrentChainName; } set { mCurrentChainName = value; if (AnimationChains != null && AnimationChains[mCurrentChainName] != null) { AnimationChain = AnimationChains[mCurrentChainName]; } } } /// <summary> /// The particle texture. /// If animation chains are set, they should override this. /// </summary> public Texture2D Texture { get; set; } #endregion public InstructionBlueprintList Instructions { get { return mInstructions; } set { mInstructions = value; } } #endregion #region Methods public EmissionSettings() { mInstructions = new InstructionBlueprintList(); mVelocityRangeType = RangeType.Radial; mScaleX = 1; mScaleY = 1; PixelSize = -1; mAlpha = GraphicalEnumerations.MaxColorComponentValue; #if FRB_MDX mColorOperation = Microsoft.DirectX.Direct3D.TextureOperation.SelectArg1; #else mColorOperation = ColorOperation.Texture; #endif mBlendOperation = BlendOperation.Regular; } public EmissionSettings Clone() { return (EmissionSettings)this.MemberwiseClone(); } #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 gagve = Google.Ads.GoogleAds.V9.Enums; using gagvr = Google.Ads.GoogleAds.V9.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using gr = Google.Rpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V9.Services; namespace Google.Ads.GoogleAds.Tests.V9.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedCustomerExtensionSettingServiceClientTest { [Category("Autogenerated")][Test] public void GetCustomerExtensionSettingRequestObject() { moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient>(moq::MockBehavior.Strict); GetCustomerExtensionSettingRequest request = new GetCustomerExtensionSettingRequest { ResourceNameAsCustomerExtensionSettingName = gagvr::CustomerExtensionSettingName.FromCustomerExtensionType("[CUSTOMER_ID]", "[EXTENSION_TYPE]"), }; gagvr::CustomerExtensionSetting expectedResponse = new gagvr::CustomerExtensionSetting { ResourceNameAsCustomerExtensionSettingName = gagvr::CustomerExtensionSettingName.FromCustomerExtensionType("[CUSTOMER_ID]", "[EXTENSION_TYPE]"), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown, ExtensionFeedItemsAsExtensionFeedItemNames = { gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }, }; mockGrpcClient.Setup(x => x.GetCustomerExtensionSetting(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerExtensionSettingServiceClient client = new CustomerExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerExtensionSetting response = client.GetCustomerExtensionSetting(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCustomerExtensionSettingRequestObjectAsync() { moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient>(moq::MockBehavior.Strict); GetCustomerExtensionSettingRequest request = new GetCustomerExtensionSettingRequest { ResourceNameAsCustomerExtensionSettingName = gagvr::CustomerExtensionSettingName.FromCustomerExtensionType("[CUSTOMER_ID]", "[EXTENSION_TYPE]"), }; gagvr::CustomerExtensionSetting expectedResponse = new gagvr::CustomerExtensionSetting { ResourceNameAsCustomerExtensionSettingName = gagvr::CustomerExtensionSettingName.FromCustomerExtensionType("[CUSTOMER_ID]", "[EXTENSION_TYPE]"), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown, ExtensionFeedItemsAsExtensionFeedItemNames = { gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }, }; mockGrpcClient.Setup(x => x.GetCustomerExtensionSettingAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerExtensionSetting>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerExtensionSettingServiceClient client = new CustomerExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerExtensionSetting responseCallSettings = await client.GetCustomerExtensionSettingAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CustomerExtensionSetting responseCancellationToken = await client.GetCustomerExtensionSettingAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetCustomerExtensionSetting() { moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient>(moq::MockBehavior.Strict); GetCustomerExtensionSettingRequest request = new GetCustomerExtensionSettingRequest { ResourceNameAsCustomerExtensionSettingName = gagvr::CustomerExtensionSettingName.FromCustomerExtensionType("[CUSTOMER_ID]", "[EXTENSION_TYPE]"), }; gagvr::CustomerExtensionSetting expectedResponse = new gagvr::CustomerExtensionSetting { ResourceNameAsCustomerExtensionSettingName = gagvr::CustomerExtensionSettingName.FromCustomerExtensionType("[CUSTOMER_ID]", "[EXTENSION_TYPE]"), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown, ExtensionFeedItemsAsExtensionFeedItemNames = { gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }, }; mockGrpcClient.Setup(x => x.GetCustomerExtensionSetting(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerExtensionSettingServiceClient client = new CustomerExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerExtensionSetting response = client.GetCustomerExtensionSetting(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCustomerExtensionSettingAsync() { moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient>(moq::MockBehavior.Strict); GetCustomerExtensionSettingRequest request = new GetCustomerExtensionSettingRequest { ResourceNameAsCustomerExtensionSettingName = gagvr::CustomerExtensionSettingName.FromCustomerExtensionType("[CUSTOMER_ID]", "[EXTENSION_TYPE]"), }; gagvr::CustomerExtensionSetting expectedResponse = new gagvr::CustomerExtensionSetting { ResourceNameAsCustomerExtensionSettingName = gagvr::CustomerExtensionSettingName.FromCustomerExtensionType("[CUSTOMER_ID]", "[EXTENSION_TYPE]"), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown, ExtensionFeedItemsAsExtensionFeedItemNames = { gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }, }; mockGrpcClient.Setup(x => x.GetCustomerExtensionSettingAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerExtensionSetting>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerExtensionSettingServiceClient client = new CustomerExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerExtensionSetting responseCallSettings = await client.GetCustomerExtensionSettingAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CustomerExtensionSetting responseCancellationToken = await client.GetCustomerExtensionSettingAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetCustomerExtensionSettingResourceNames() { moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient>(moq::MockBehavior.Strict); GetCustomerExtensionSettingRequest request = new GetCustomerExtensionSettingRequest { ResourceNameAsCustomerExtensionSettingName = gagvr::CustomerExtensionSettingName.FromCustomerExtensionType("[CUSTOMER_ID]", "[EXTENSION_TYPE]"), }; gagvr::CustomerExtensionSetting expectedResponse = new gagvr::CustomerExtensionSetting { ResourceNameAsCustomerExtensionSettingName = gagvr::CustomerExtensionSettingName.FromCustomerExtensionType("[CUSTOMER_ID]", "[EXTENSION_TYPE]"), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown, ExtensionFeedItemsAsExtensionFeedItemNames = { gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }, }; mockGrpcClient.Setup(x => x.GetCustomerExtensionSetting(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerExtensionSettingServiceClient client = new CustomerExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerExtensionSetting response = client.GetCustomerExtensionSetting(request.ResourceNameAsCustomerExtensionSettingName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCustomerExtensionSettingResourceNamesAsync() { moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient>(moq::MockBehavior.Strict); GetCustomerExtensionSettingRequest request = new GetCustomerExtensionSettingRequest { ResourceNameAsCustomerExtensionSettingName = gagvr::CustomerExtensionSettingName.FromCustomerExtensionType("[CUSTOMER_ID]", "[EXTENSION_TYPE]"), }; gagvr::CustomerExtensionSetting expectedResponse = new gagvr::CustomerExtensionSetting { ResourceNameAsCustomerExtensionSettingName = gagvr::CustomerExtensionSettingName.FromCustomerExtensionType("[CUSTOMER_ID]", "[EXTENSION_TYPE]"), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown, ExtensionFeedItemsAsExtensionFeedItemNames = { gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }, }; mockGrpcClient.Setup(x => x.GetCustomerExtensionSettingAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerExtensionSetting>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerExtensionSettingServiceClient client = new CustomerExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerExtensionSetting responseCallSettings = await client.GetCustomerExtensionSettingAsync(request.ResourceNameAsCustomerExtensionSettingName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CustomerExtensionSetting responseCancellationToken = await client.GetCustomerExtensionSettingAsync(request.ResourceNameAsCustomerExtensionSettingName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateCustomerExtensionSettingsRequestObject() { moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient>(moq::MockBehavior.Strict); MutateCustomerExtensionSettingsRequest request = new MutateCustomerExtensionSettingsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CustomerExtensionSettingOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateCustomerExtensionSettingsResponse expectedResponse = new MutateCustomerExtensionSettingsResponse { Results = { new MutateCustomerExtensionSettingResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCustomerExtensionSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerExtensionSettingServiceClient client = new CustomerExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); MutateCustomerExtensionSettingsResponse response = client.MutateCustomerExtensionSettings(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateCustomerExtensionSettingsRequestObjectAsync() { moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient>(moq::MockBehavior.Strict); MutateCustomerExtensionSettingsRequest request = new MutateCustomerExtensionSettingsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CustomerExtensionSettingOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateCustomerExtensionSettingsResponse expectedResponse = new MutateCustomerExtensionSettingsResponse { Results = { new MutateCustomerExtensionSettingResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCustomerExtensionSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCustomerExtensionSettingsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerExtensionSettingServiceClient client = new CustomerExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); MutateCustomerExtensionSettingsResponse responseCallSettings = await client.MutateCustomerExtensionSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateCustomerExtensionSettingsResponse responseCancellationToken = await client.MutateCustomerExtensionSettingsAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateCustomerExtensionSettings() { moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient>(moq::MockBehavior.Strict); MutateCustomerExtensionSettingsRequest request = new MutateCustomerExtensionSettingsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CustomerExtensionSettingOperation(), }, }; MutateCustomerExtensionSettingsResponse expectedResponse = new MutateCustomerExtensionSettingsResponse { Results = { new MutateCustomerExtensionSettingResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCustomerExtensionSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerExtensionSettingServiceClient client = new CustomerExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); MutateCustomerExtensionSettingsResponse response = client.MutateCustomerExtensionSettings(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateCustomerExtensionSettingsAsync() { moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient>(moq::MockBehavior.Strict); MutateCustomerExtensionSettingsRequest request = new MutateCustomerExtensionSettingsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CustomerExtensionSettingOperation(), }, }; MutateCustomerExtensionSettingsResponse expectedResponse = new MutateCustomerExtensionSettingsResponse { Results = { new MutateCustomerExtensionSettingResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCustomerExtensionSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCustomerExtensionSettingsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerExtensionSettingServiceClient client = new CustomerExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); MutateCustomerExtensionSettingsResponse responseCallSettings = await client.MutateCustomerExtensionSettingsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateCustomerExtensionSettingsResponse responseCancellationToken = await client.MutateCustomerExtensionSettingsAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
#region license // Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Boo.Lang.Compiler.Ast; using Boo.Lang.Compiler.TypeSystem; using Boo.Lang.Compiler.TypeSystem.Core; using Boo.Lang.Compiler.TypeSystem.Internal; using Boo.Lang.Compiler.TypeSystem.Reflection; using Boo.Lang.Compiler.Util; using Boo.Lang.Environments; namespace Boo.Lang.Compiler.Steps.MacroProcessing { public sealed class MacroExpander : AbstractNamespaceSensitiveTransformerCompilerStep { private int _expanded; private Set<Node> _visited = new Set<Node>(); private Queue<Statement> _pendingExpansions = new Queue<Statement>(); private DynamicVariable<bool> _ignoringUnknownMacros = new DynamicVariable<bool>(false); public bool ExpandAll() { Reset(); Run(); BubbleUpPendingTypeMembers(); return _expanded > 0; } private void Reset() { _pendingExpansions.Clear(); _visited.Clear(); _expanded = 0; } override public void Run() { ExpandModuleGlobalsIgnoringUnknownMacros(); ExpandModules(); } private void ExpandModules() { foreach (Module module in CompileUnit.Modules) ExpandOnModuleNamespace(module, VisitModule); } private void ExpandModuleGlobalsIgnoringUnknownMacros() { foreach (Module module in CompileUnit.Modules) ExpandModuleGlobalsIgnoringUnknownMacros(module); } private void ExpandModuleGlobalsIgnoringUnknownMacros(Module current) { _ignoringUnknownMacros.With(true, ()=> ExpandOnModuleNamespace(current, VisitGlobalsAllowingCancellation)); } private void VisitGlobalsAllowingCancellation(Module module) { var globals = module.Globals.Statements; foreach (var stmt in globals.ToArray()) { Node resultingNode; if (VisitAllowingCancellation(stmt, out resultingNode) && resultingNode != stmt) globals.Replace(stmt, (Statement) resultingNode); BubbleUpPendingTypeMembers(); } } private void VisitModule(Module module) { Visit(module.Globals); Visit(module.Members); } void ExpandOnModuleNamespace(Module module, Action<Module> action) { EnterModuleNamespace(module); try { action(module); } finally { LeaveNamespace(); } } private void EnterModuleNamespace(Module module) { EnterNamespace(InternalModule.ScopeFor(module)); } public override bool EnterClassDefinition(ClassDefinition node) { if (WasVisited(node)) return false; _visited.Add(node); return true; } bool _referenced; internal void EnsureCompilerAssemblyReference(CompilerContext context) { if (_referenced) return; if (null != context.References.Find("Boo.Lang.Compiler")) { _referenced = true; return; } context.References.Add(typeof(CompilerContext).Assembly); _referenced = true; } override public void OnMacroStatement(MacroStatement node) { EnsureCompilerAssemblyReference(Context); var macroType = ResolveMacroName(node) as IType; if (null != macroType) { ExpandKnownMacro(node, macroType); return; } if (_ignoringUnknownMacros.Value) Cancel(); ExpandUnknownMacro(node); } private bool IsTopLevelExpansion() { return _expansionDepth == 0; } private void BubbleUpPendingTypeMembers() { while (_pendingExpansions.Count > 0) TypeMemberStatementBubbler.BubbleTypeMemberStatementsUp(_pendingExpansions.Dequeue()); } private void ExpandKnownMacro(MacroStatement node, IType macroType) { ExpandChildrenOfMacroOnMacroNamespace(node, macroType); ProcessMacro(macroType, node); } private void ExpandChildrenOfMacroOnMacroNamespace(MacroStatement node, IType macroType) { EnterMacroNamespace(macroType); try { ExpandChildrenOf(node); } finally { LeaveNamespace(); } } private void EnterMacroNamespace(IType macroType) { EnsureNestedMacrosCanBeSeenAsMembers(macroType); EnterNamespace(new NamespaceDelegator(CurrentNamespace, macroType)); } private static void EnsureNestedMacrosCanBeSeenAsMembers(IType macroType) { var internalMacroType = macroType as InternalClass; if (null != internalMacroType) TypeMemberStatementBubbler.BubbleTypeMemberStatementsUp(internalMacroType.TypeDefinition); } private void ExpandUnknownMacro(MacroStatement node) { ExpandChildrenOf(node); if (IsTypeMemberMacro(node)) UnknownTypeMemberMacro(node); else TreatMacroAsMethodInvocation(node); } private static bool IsTypeMemberMacro(MacroStatement node) { return node.ParentNode.NodeType == NodeType.StatementTypeMember; } private void UnknownTypeMemberMacro(MacroStatement node) { var error = LooksLikeOldStyleFieldDeclaration(node) ? CompilerErrorFactory.UnknownClassMacroWithFieldHint(node, node.Name) : CompilerErrorFactory.UnknownMacro(node, node.Name); ProcessingError(error); } private static bool LooksLikeOldStyleFieldDeclaration(MacroStatement node) { return node.Arguments.Count == 0 && node.Body.IsEmpty; } private void ExpandChildrenOf(MacroStatement node) { EnterExpansion(); try { Visit(node.Body); Visit(node.Arguments); } finally { LeaveExpansion(); } } private void LeaveExpansion() { --_expansionDepth; } private void EnterExpansion() { ++_expansionDepth; } private void ProcessMacro(IType macroType, MacroStatement node) { var externalType = macroType as ExternalType; if (externalType == null) { InternalClass internalType = (InternalClass) macroType; ProcessInternalMacro(internalType, node); return; } ProcessMacro(externalType.ActualType, node); } private void ProcessInternalMacro(InternalClass klass, MacroStatement node) { TypeDefinition macroDefinition = klass.TypeDefinition; if (MacroDefinitionContainsMacroApplication(macroDefinition, node)) { ProcessingError(CompilerErrorFactory.InvalidMacro(node, klass)); return; } var macroCompiler = My<MacroCompiler>.Instance; bool firstTry = !macroCompiler.AlreadyCompiled(macroDefinition); Type macroType = macroCompiler.Compile(macroDefinition); if (macroType == null) { if (firstTry) ProcessingError(CompilerErrorFactory.AstMacroMustBeExternal(node, klass)); else RemoveCurrentNode(); return; } ProcessMacro(macroType, node); } private static bool MacroDefinitionContainsMacroApplication(TypeDefinition definition, MacroStatement statement) { return statement.GetAncestors<TypeDefinition>().Any(ancestor => ancestor == definition); } private int _expansionDepth; private bool WasVisited(TypeDefinition node) { return _visited.Contains(node); } private void ProcessingError(CompilerError error) { Errors.Add(error); RemoveCurrentNode(); } private void ProcessMacro(Type actualType, MacroStatement node) { if (!typeof(IAstMacro).IsAssignableFrom(actualType)) { ProcessingError(CompilerErrorFactory.InvalidMacro(node, Map(actualType))); return; } ++_expanded; try { var macroExpansion = ExpandMacro(actualType, node); var completeExpansion = ExpandMacroExpansion(node, macroExpansion); ReplaceCurrentNode(completeExpansion); if (completeExpansion != null && IsTopLevelExpansion()) _pendingExpansions.Enqueue(completeExpansion); } catch (LongJumpException) { throw; } catch (Exception error) { ProcessingError(CompilerErrorFactory.MacroExpansionError(node, error)); } } private IType Map(Type actualType) { return TypeSystemServices.Map(actualType); } private Statement ExpandMacroExpansion(MacroStatement node, Statement expansion) { if (null == expansion) return null; Statement modifiedExpansion = ApplyMacroModifierToExpansion(node, expansion); modifiedExpansion.InitializeParent(node.ParentNode); return Visit(modifiedExpansion); } private static Statement ApplyMacroModifierToExpansion(MacroStatement node, Statement expansion) { if (node.Modifier == null) return expansion; return NormalizeStatementModifiers.CreateModifiedStatement(node.Modifier, expansion); } private void TreatMacroAsMethodInvocation(MacroStatement node) { var invocation = new MethodInvocationExpression(node.LexicalInfo, new ReferenceExpression(node.LexicalInfo, node.Name)) { Arguments = node.Arguments }; if (node.ContainsAnnotation("compound") || !IsNullOrEmpty(node.Body)) invocation.Arguments.Add(new BlockExpression(node.Body)); ReplaceCurrentNode(new ExpressionStatement(node.LexicalInfo, invocation, node.Modifier)); } private static bool IsNullOrEmpty(Block block) { return block == null || block.IsEmpty; } private Statement ExpandMacro(Type macroType, MacroStatement node) { var macro = (IAstMacro) Activator.CreateInstance(macroType); macro.Initialize(Context); //use new-style BOO-1077 generator macro interface if available var gm = macro as IAstGeneratorMacro; if (gm != null) return ExpandGeneratorMacro(gm, node); return macro.Expand(node); } private static Statement ExpandGeneratorMacro(IAstGeneratorMacro macroType, MacroStatement node) { IEnumerable<Node> generatedNodes = macroType.ExpandGenerator(node); if (null == generatedNodes) return null; return new NodeGeneratorExpander(node).Expand(generatedNodes); } private IEntity ResolveMacroName(MacroStatement node) { var macroTypeName = BuildMacroTypeName(node.Name); var entity = ResolvePreferringInternalMacros(macroTypeName) ?? ResolvePreferringInternalMacros(node.Name); if (entity is IType) return entity; if (entity == null) return null; //we got something interesting, check if it is/has an extension method //that resolves a nested macro extension return ResolveMacroExtensionType(node, entity as IMethod) ?? ResolveMacroExtensionType(node, entity as Ambiguous) ?? entity; //return as-is } private IEntity ResolvePreferringInternalMacros(string macroTypeName) { IEntity resolved = NameResolutionService.ResolveQualifiedName(macroTypeName); Ambiguous ambiguous = resolved as Ambiguous; if (null != ambiguous && ambiguous.AllEntitiesAre(EntityType.Type)) return Entities.PreferInternalEntitiesOverExternalOnes(ambiguous); return resolved; } IEntity ResolveMacroExtensionType(MacroStatement node, Ambiguous extensions) { if (null == extensions) return null; foreach (var entity in extensions.Entities) { var extensionType = ResolveMacroExtensionType(node, entity as IMethod); if (null != extensionType) return extensionType; } return null; } IEntity ResolveMacroExtensionType(MacroStatement node, IMethod extension) { if (null == extension) return null; IType extendedMacroType = GetExtendedMacroType(extension); if (null == extendedMacroType) return null; //ok now check if extension is correctly nested under parent foreach (MacroStatement parent in node.GetAncestors<MacroStatement>()) if (ResolveMacroName(parent) == extendedMacroType) return GetExtensionMacroType(extension); return null; } IType GetExtendedMacroType(IMethod method) { InternalMethod internalMethod = method as InternalMethod; if (null != internalMethod) { Method extension = internalMethod.Method; if (!extension.Attributes.Contains(Types.BooExtensionAttribute.FullName) || !extension.Attributes.Contains(Types.CompilerGeneratedAttribute.FullName)) return null; SimpleTypeReference sref = extension.Parameters[0].Type as SimpleTypeReference; if (null != sref && extension.Parameters.Count == 2) { IType type = NameResolutionService.ResolveQualifiedName(sref.Name) as IType; if (type != null && type.Name.EndsWith("Macro")) //no entity yet return type; } } else if (method is ExternalMethod && method.IsExtension) { var parameters = method.GetParameters(); if (parameters.Length == 2 && TypeSystemServices.IsMacro(parameters[0].Type)) return parameters[0].Type; } return null; } IType GetExtensionMacroType(IMethod method) { InternalMethod internalMethod = method as InternalMethod; if (null != internalMethod) { Method extension = internalMethod.Method; SimpleTypeReference sref = extension.ReturnType as SimpleTypeReference; if (null != sref) { IType type = NameResolutionService.ResolveQualifiedName(sref.Name) as IType; if (type != null && type.Name.EndsWith("Macro"))//no entity yet return type; } } else if (method is ExternalMethod) return method.ReturnType; return null; } private StringBuilder _buffer = new StringBuilder(); private string BuildMacroTypeName(string name) { _buffer.Length = 0; if (!char.IsUpper(name[0])) { _buffer.Append(char.ToUpper(name[0])); _buffer.Append(name.Substring(1)); _buffer.Append("Macro"); } else { _buffer.Append(name); _buffer.Append("Macro"); } return _buffer.ToString(); } } }
using XenAdmin.Commands; using XenAPI; namespace XenAdmin.TabPages { partial class SrStoragePage { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; #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(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SrStoragePage)); this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); this.rescanToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.addToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.moveVirtualDiskToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.deleteVirtualDiskToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.editVirtualDiskToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.TitleLabel = new System.Windows.Forms.Label(); this.RemoveButtonContainer = new XenAdmin.Controls.ToolTipContainer(); this.RemoveButton = new System.Windows.Forms.Button(); this.EditButtonContainer = new XenAdmin.Controls.ToolTipContainer(); this.EditButton = new System.Windows.Forms.Button(); this.addVirtualDiskButton = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.toolTipContainerRescan = new XenAdmin.Controls.ToolTipContainer(); this.buttonRescan = new System.Windows.Forms.Button(); this.toolTipContainerMove = new XenAdmin.Controls.ToolTipContainer(); this.buttonMove = new System.Windows.Forms.Button(); this.dataGridViewVDIs = new XenAdmin.Controls.DataGridViewEx.DataGridViewEx(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.ColumnName = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnVolume = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnDesc = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnSize = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnVM = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnCBT = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.pageContainerPanel.SuspendLayout(); this.contextMenuStrip1.SuspendLayout(); this.RemoveButtonContainer.SuspendLayout(); this.EditButtonContainer.SuspendLayout(); this.flowLayoutPanel1.SuspendLayout(); this.toolTipContainerRescan.SuspendLayout(); this.toolTipContainerMove.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridViewVDIs)).BeginInit(); this.tableLayoutPanel1.SuspendLayout(); this.SuspendLayout(); // // pageContainerPanel // this.pageContainerPanel.Controls.Add(this.tableLayoutPanel1); resources.ApplyResources(this.pageContainerPanel, "pageContainerPanel"); // // contextMenuStrip1 // this.contextMenuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20); this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.rescanToolStripMenuItem, this.addToolStripMenuItem, this.moveVirtualDiskToolStripMenuItem, this.deleteVirtualDiskToolStripMenuItem, this.toolStripSeparator1, this.editVirtualDiskToolStripMenuItem}); this.contextMenuStrip1.Name = "contextMenuStrip1"; resources.ApplyResources(this.contextMenuStrip1, "contextMenuStrip1"); this.contextMenuStrip1.Opening += new System.ComponentModel.CancelEventHandler(this.contextMenuStrip_Opening); // // rescanToolStripMenuItem // this.rescanToolStripMenuItem.Name = "rescanToolStripMenuItem"; resources.ApplyResources(this.rescanToolStripMenuItem, "rescanToolStripMenuItem"); this.rescanToolStripMenuItem.Click += new System.EventHandler(this.rescanToolStripMenuItem_Click); // // addToolStripMenuItem // this.addToolStripMenuItem.Name = "addToolStripMenuItem"; resources.ApplyResources(this.addToolStripMenuItem, "addToolStripMenuItem"); this.addToolStripMenuItem.Click += new System.EventHandler(this.addToolStripMenuItem_Click); // // moveVirtualDiskToolStripMenuItem // this.moveVirtualDiskToolStripMenuItem.Name = "moveVirtualDiskToolStripMenuItem"; resources.ApplyResources(this.moveVirtualDiskToolStripMenuItem, "moveVirtualDiskToolStripMenuItem"); this.moveVirtualDiskToolStripMenuItem.Click += new System.EventHandler(this.moveVirtualDiskToolStripMenuItem_Click); // // deleteVirtualDiskToolStripMenuItem // this.deleteVirtualDiskToolStripMenuItem.Name = "deleteVirtualDiskToolStripMenuItem"; resources.ApplyResources(this.deleteVirtualDiskToolStripMenuItem, "deleteVirtualDiskToolStripMenuItem"); this.deleteVirtualDiskToolStripMenuItem.Click += new System.EventHandler(this.deleteVirtualDiskToolStripMenuItem_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1"); // // editVirtualDiskToolStripMenuItem // this.editVirtualDiskToolStripMenuItem.Image = global::XenAdmin.Properties.Resources.edit_16; resources.ApplyResources(this.editVirtualDiskToolStripMenuItem, "editVirtualDiskToolStripMenuItem"); this.editVirtualDiskToolStripMenuItem.Name = "editVirtualDiskToolStripMenuItem"; this.editVirtualDiskToolStripMenuItem.Click += new System.EventHandler(this.editVirtualDiskToolStripMenuItem_Click); // // TitleLabel // resources.ApplyResources(this.TitleLabel, "TitleLabel"); this.TitleLabel.ForeColor = System.Drawing.Color.White; this.TitleLabel.Name = "TitleLabel"; // // RemoveButtonContainer // this.RemoveButtonContainer.Controls.Add(this.RemoveButton); resources.ApplyResources(this.RemoveButtonContainer, "RemoveButtonContainer"); this.RemoveButtonContainer.Name = "RemoveButtonContainer"; // // RemoveButton // resources.ApplyResources(this.RemoveButton, "RemoveButton"); this.RemoveButton.Name = "RemoveButton"; this.RemoveButton.UseVisualStyleBackColor = true; this.RemoveButton.Click += new System.EventHandler(this.RemoveButton_Click); // // EditButtonContainer // resources.ApplyResources(this.EditButtonContainer, "EditButtonContainer"); this.EditButtonContainer.Controls.Add(this.EditButton); this.EditButtonContainer.Name = "EditButtonContainer"; // // EditButton // resources.ApplyResources(this.EditButton, "EditButton"); this.EditButton.Name = "EditButton"; this.EditButton.UseVisualStyleBackColor = true; this.EditButton.Click += new System.EventHandler(this.EditButton_Click); // // addVirtualDiskButton // resources.ApplyResources(this.addVirtualDiskButton, "addVirtualDiskButton"); this.addVirtualDiskButton.Name = "addVirtualDiskButton"; this.addVirtualDiskButton.UseVisualStyleBackColor = true; this.addVirtualDiskButton.Click += new System.EventHandler(this.addVirtualDiskButton_Click); // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // flowLayoutPanel1 // this.flowLayoutPanel1.Controls.Add(this.toolTipContainerRescan); this.flowLayoutPanel1.Controls.Add(this.addVirtualDiskButton); this.flowLayoutPanel1.Controls.Add(this.EditButtonContainer); this.flowLayoutPanel1.Controls.Add(this.toolTipContainerMove); this.flowLayoutPanel1.Controls.Add(this.RemoveButtonContainer); resources.ApplyResources(this.flowLayoutPanel1, "flowLayoutPanel1"); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; // // toolTipContainerRescan // this.toolTipContainerRescan.Controls.Add(this.buttonRescan); resources.ApplyResources(this.toolTipContainerRescan, "toolTipContainerRescan"); this.toolTipContainerRescan.Name = "toolTipContainerRescan"; // // buttonRescan // resources.ApplyResources(this.buttonRescan, "buttonRescan"); this.buttonRescan.Name = "buttonRescan"; this.buttonRescan.UseVisualStyleBackColor = true; this.buttonRescan.Click += new System.EventHandler(this.buttonRescan_Click); // // toolTipContainerMove // this.toolTipContainerMove.Controls.Add(this.buttonMove); resources.ApplyResources(this.toolTipContainerMove, "toolTipContainerMove"); this.toolTipContainerMove.Name = "toolTipContainerMove"; // // buttonMove // resources.ApplyResources(this.buttonMove, "buttonMove"); this.buttonMove.Name = "buttonMove"; this.buttonMove.UseVisualStyleBackColor = true; this.buttonMove.Click += new System.EventHandler(this.buttonMove_Click); // // dataGridViewVDIs // this.dataGridViewVDIs.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells; this.dataGridViewVDIs.BackgroundColor = System.Drawing.SystemColors.Window; this.dataGridViewVDIs.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; this.dataGridViewVDIs.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridViewVDIs.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.ColumnName, this.ColumnVolume, this.ColumnDesc, this.ColumnSize, this.ColumnVM, this.ColumnCBT}); resources.ApplyResources(this.dataGridViewVDIs, "dataGridViewVDIs"); this.dataGridViewVDIs.MultiSelect = true; this.dataGridViewVDIs.Name = "dataGridViewVDIs"; this.dataGridViewVDIs.ReadOnly = true; this.dataGridViewVDIs.SelectionChanged += new System.EventHandler(this.dataGridViewVDIs_SelectedIndexChanged); this.dataGridViewVDIs.SortCompare += new System.Windows.Forms.DataGridViewSortCompareEventHandler(this.DataGridViewObject_SortCompare); this.dataGridViewVDIs.KeyUp += new System.Windows.Forms.KeyEventHandler(this.dataGridViewVDIs_KeyUp); this.dataGridViewVDIs.MouseUp += new System.Windows.Forms.MouseEventHandler(this.dataGridViewVDIs_MouseUp); // // tableLayoutPanel1 // resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1"); this.tableLayoutPanel1.Controls.Add(this.flowLayoutPanel1, 0, 2); this.tableLayoutPanel1.Controls.Add(this.dataGridViewVDIs, 0, 1); this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; // // ColumnName // this.ColumnName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.ColumnName, "ColumnName"); this.ColumnName.Name = "ColumnName"; this.ColumnName.ReadOnly = true; // // ColumnVolume // this.ColumnVolume.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.ColumnVolume, "ColumnVolume"); this.ColumnVolume.Name = "ColumnVolume"; this.ColumnVolume.ReadOnly = true; // // ColumnDesc // this.ColumnDesc.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.ColumnDesc, "ColumnDesc"); this.ColumnDesc.Name = "ColumnDesc"; this.ColumnDesc.ReadOnly = true; // // ColumnSize // this.ColumnSize.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.ColumnSize, "ColumnSize"); this.ColumnSize.Name = "ColumnSize"; this.ColumnSize.ReadOnly = true; // // ColumnVM // this.ColumnVM.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.ColumnVM, "ColumnVM"); this.ColumnVM.Name = "ColumnVM"; this.ColumnVM.ReadOnly = true; // // ColumnCBT // this.ColumnCBT.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.ColumnCBT, "ColumnCBT"); this.ColumnCBT.Name = "ColumnCBT"; this.ColumnCBT.ReadOnly = true; // // SrStoragePage // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.BackColor = System.Drawing.Color.Transparent; this.DoubleBuffered = true; this.Name = "SrStoragePage"; this.Controls.SetChildIndex(this.pageContainerPanel, 0); this.pageContainerPanel.ResumeLayout(false); this.contextMenuStrip1.ResumeLayout(false); this.RemoveButtonContainer.ResumeLayout(false); this.EditButtonContainer.ResumeLayout(false); this.flowLayoutPanel1.ResumeLayout(false); this.toolTipContainerRescan.ResumeLayout(false); this.toolTipContainerMove.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dataGridViewVDIs)).EndInit(); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ContextMenuStrip contextMenuStrip1; private System.Windows.Forms.ToolStripMenuItem editVirtualDiskToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem deleteVirtualDiskToolStripMenuItem; private System.Windows.Forms.Button addVirtualDiskButton; private System.Windows.Forms.Label TitleLabel; private XenAdmin.Controls.ToolTipContainer EditButtonContainer; private System.Windows.Forms.Button EditButton; private XenAdmin.Controls.ToolTipContainer RemoveButtonContainer; private System.Windows.Forms.Button RemoveButton; private System.Windows.Forms.Label label1; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private System.Windows.Forms.Button buttonRescan; private XenAdmin.Controls.ToolTipContainer toolTipContainerRescan; private XenAdmin.Controls.ToolTipContainer toolTipContainerMove; private System.Windows.Forms.Button buttonMove; private System.Windows.Forms.ToolStripMenuItem moveVirtualDiskToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private XenAdmin.Controls.DataGridViewEx.DataGridViewEx dataGridViewVDIs; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.ToolStripMenuItem rescanToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem addToolStripMenuItem; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnName; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnVolume; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDesc; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnSize; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnVM; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnCBT; } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; #if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1 using System.Numerics; #endif using System.Text; using Newtonsoft.Json.Converters; #if DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; #endif using Newtonsoft.Json.Linq; using System.IO; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; using Newtonsoft.Json.Utilities; #endif namespace Newtonsoft.Json.Tests.Linq { [TestFixture] public class JTokenTests : TestFixtureBase { [Test] public void DeepEqualsObjectOrder() { string ob1 = @"{""key1"":""1"",""key2"":""2""}"; string ob2 = @"{""key2"":""2"",""key1"":""1""}"; JObject j1 = JObject.Parse(ob1); JObject j2 = JObject.Parse(ob2); Assert.IsTrue(j1.DeepEquals(j2)); } [Test] public void ReadFrom() { JObject o = (JObject)JToken.ReadFrom(new JsonTextReader(new StringReader("{'pie':true}"))); Assert.AreEqual(true, (bool)o["pie"]); JArray a = (JArray)JToken.ReadFrom(new JsonTextReader(new StringReader("[1,2,3]"))); Assert.AreEqual(1, (int)a[0]); Assert.AreEqual(2, (int)a[1]); Assert.AreEqual(3, (int)a[2]); JsonReader reader = new JsonTextReader(new StringReader("{'pie':true}")); reader.Read(); reader.Read(); JProperty p = (JProperty)JToken.ReadFrom(reader); Assert.AreEqual("pie", p.Name); Assert.AreEqual(true, (bool)p.Value); JConstructor c = (JConstructor)JToken.ReadFrom(new JsonTextReader(new StringReader("new Date(1)"))); Assert.AreEqual("Date", c.Name); Assert.IsTrue(JToken.DeepEquals(new JValue(1), c.Values().ElementAt(0))); JValue v; v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"""stringvalue"""))); Assert.AreEqual("stringvalue", (string)v); v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"1"))); Assert.AreEqual(1, (int)v); v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"1.1"))); Assert.AreEqual(1.1, (double)v); #if !NET20 v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"""1970-01-01T00:00:00+12:31""")) { DateParseHandling = DateParseHandling.DateTimeOffset }); Assert.AreEqual(typeof(DateTimeOffset), v.Value.GetType()); Assert.AreEqual(new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, new TimeSpan(12, 31, 0)), v.Value); #endif } [Test] public void Load() { JObject o = (JObject)JToken.Load(new JsonTextReader(new StringReader("{'pie':true}"))); Assert.AreEqual(true, (bool)o["pie"]); } [Test] public void Parse() { JObject o = (JObject)JToken.Parse("{'pie':true}"); Assert.AreEqual(true, (bool)o["pie"]); } [Test] public void Parent() { JArray v = new JArray(new JConstructor("TestConstructor"), new JValue(new DateTime(2000, 12, 20))); Assert.AreEqual(null, v.Parent); JObject o = new JObject( new JProperty("Test1", v), new JProperty("Test2", "Test2Value"), new JProperty("Test3", "Test3Value"), new JProperty("Test4", null) ); Assert.AreEqual(o.Property("Test1"), v.Parent); JProperty p = new JProperty("NewProperty", v); // existing value should still have same parent Assert.AreEqual(o.Property("Test1"), v.Parent); // new value should be cloned Assert.AreNotSame(p.Value, v); Assert.AreEqual((DateTime)((JValue)p.Value[1]).Value, (DateTime)((JValue)v[1]).Value); Assert.AreEqual(v, o["Test1"]); Assert.AreEqual(null, o.Parent); JProperty o1 = new JProperty("O1", o); Assert.AreEqual(o, o1.Value); Assert.AreNotEqual(null, o.Parent); JProperty o2 = new JProperty("O2", o); Assert.AreNotSame(o1.Value, o2.Value); Assert.AreEqual(o1.Value.Children().Count(), o2.Value.Children().Count()); Assert.AreEqual(false, JToken.DeepEquals(o1, o2)); Assert.AreEqual(true, JToken.DeepEquals(o1.Value, o2.Value)); } [Test] public void Next() { JArray a = new JArray( 5, 6, new JArray(7, 8), new JArray(9, 10) ); JToken next = a[0].Next; Assert.AreEqual(6, (int)next); next = next.Next; Assert.IsTrue(JToken.DeepEquals(new JArray(7, 8), next)); next = next.Next; Assert.IsTrue(JToken.DeepEquals(new JArray(9, 10), next)); next = next.Next; Assert.IsNull(next); } [Test] public void Previous() { JArray a = new JArray( 5, 6, new JArray(7, 8), new JArray(9, 10) ); JToken previous = a[3].Previous; Assert.IsTrue(JToken.DeepEquals(new JArray(7, 8), previous)); previous = previous.Previous; Assert.AreEqual(6, (int)previous); previous = previous.Previous; Assert.AreEqual(5, (int)previous); previous = previous.Previous; Assert.IsNull(previous); } [Test] public void Children() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); Assert.AreEqual(4, a.Count()); Assert.AreEqual(3, a.Children<JArray>().Count()); } [Test] public void BeforeAfter() { JArray a = new JArray( 5, new JArray(1, 2, 3), new JArray(1, 2, 3), new JArray(1, 2, 3) ); Assert.AreEqual(5, (int)a[1].Previous); Assert.AreEqual(2, a[2].BeforeSelf().Count()); //Assert.AreEqual(2, a[2].AfterSelf().Count()); } [Test] public void Casting() { Assert.AreEqual(1L, (long)(new JValue(1))); Assert.AreEqual(2L, (long)new JArray(1, 2, 3)[1]); Assert.AreEqual(new DateTime(2000, 12, 20), (DateTime)new JValue(new DateTime(2000, 12, 20))); #if !NET20 Assert.AreEqual(new DateTimeOffset(2000, 12, 20, 0, 0, 0, TimeSpan.Zero), (DateTimeOffset)new JValue(new DateTime(2000, 12, 20, 0, 0, 0, DateTimeKind.Utc))); Assert.AreEqual(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero), (DateTimeOffset)new JValue(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero))); Assert.AreEqual(null, (DateTimeOffset?)new JValue((DateTimeOffset?)null)); Assert.AreEqual(null, (DateTimeOffset?)(JValue)null); #endif Assert.AreEqual(true, (bool)new JValue(true)); Assert.AreEqual(true, (bool?)new JValue(true)); Assert.AreEqual(null, (bool?)((JValue)null)); Assert.AreEqual(null, (bool?)JValue.CreateNull()); Assert.AreEqual(10, (long)new JValue(10)); Assert.AreEqual(null, (long?)new JValue((long?)null)); Assert.AreEqual(null, (long?)(JValue)null); Assert.AreEqual(null, (int?)new JValue((int?)null)); Assert.AreEqual(null, (int?)(JValue)null); Assert.AreEqual(null, (DateTime?)new JValue((DateTime?)null)); Assert.AreEqual(null, (DateTime?)(JValue)null); Assert.AreEqual(null, (short?)new JValue((short?)null)); Assert.AreEqual(null, (short?)(JValue)null); Assert.AreEqual(null, (float?)new JValue((float?)null)); Assert.AreEqual(null, (float?)(JValue)null); Assert.AreEqual(null, (double?)new JValue((double?)null)); Assert.AreEqual(null, (double?)(JValue)null); Assert.AreEqual(null, (decimal?)new JValue((decimal?)null)); Assert.AreEqual(null, (decimal?)(JValue)null); Assert.AreEqual(null, (uint?)new JValue((uint?)null)); Assert.AreEqual(null, (uint?)(JValue)null); Assert.AreEqual(null, (sbyte?)new JValue((sbyte?)null)); Assert.AreEqual(null, (sbyte?)(JValue)null); Assert.AreEqual(null, (byte?)new JValue((byte?)null)); Assert.AreEqual(null, (byte?)(JValue)null); Assert.AreEqual(null, (ulong?)new JValue((ulong?)null)); Assert.AreEqual(null, (ulong?)(JValue)null); Assert.AreEqual(null, (uint?)new JValue((uint?)null)); Assert.AreEqual(null, (uint?)(JValue)null); Assert.AreEqual(11.1f, (float)new JValue(11.1)); Assert.AreEqual(float.MinValue, (float)new JValue(float.MinValue)); Assert.AreEqual(1.1, (double)new JValue(1.1)); Assert.AreEqual(uint.MaxValue, (uint)new JValue(uint.MaxValue)); Assert.AreEqual(ulong.MaxValue, (ulong)new JValue(ulong.MaxValue)); Assert.AreEqual(ulong.MaxValue, (ulong)new JProperty("Test", new JValue(ulong.MaxValue))); Assert.AreEqual(null, (string)new JValue((string)null)); Assert.AreEqual(5m, (decimal)(new JValue(5L))); Assert.AreEqual(5m, (decimal?)(new JValue(5L))); Assert.AreEqual(5f, (float)(new JValue(5L))); Assert.AreEqual(5f, (float)(new JValue(5m))); Assert.AreEqual(5f, (float?)(new JValue(5m))); Assert.AreEqual(5, (byte)(new JValue(5))); Assert.AreEqual(SByte.MinValue, (sbyte?)(new JValue(SByte.MinValue))); Assert.AreEqual(SByte.MinValue, (sbyte)(new JValue(SByte.MinValue))); Assert.AreEqual(null, (sbyte?)JValue.CreateNull()); Assert.AreEqual("1", (string)(new JValue(1))); Assert.AreEqual("1", (string)(new JValue(1.0))); Assert.AreEqual("1.0", (string)(new JValue(1.0m))); Assert.AreEqual("True", (string)(new JValue(true))); Assert.AreEqual(null, (string)(JValue.CreateNull())); Assert.AreEqual(null, (string)(JValue)null); Assert.AreEqual("12/12/2000 12:12:12", (string)(new JValue(new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc)))); #if !NET20 Assert.AreEqual("12/12/2000 12:12:12 +00:00", (string)(new JValue(new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.Zero)))); #endif Assert.AreEqual(true, (bool)(new JValue(1))); Assert.AreEqual(true, (bool)(new JValue(1.0))); Assert.AreEqual(true, (bool)(new JValue("true"))); Assert.AreEqual(true, (bool)(new JValue(true))); Assert.AreEqual(1, (int)(new JValue(1))); Assert.AreEqual(1, (int)(new JValue(1.0))); Assert.AreEqual(1, (int)(new JValue("1"))); Assert.AreEqual(1, (int)(new JValue(true))); Assert.AreEqual(1m, (decimal)(new JValue(1))); Assert.AreEqual(1m, (decimal)(new JValue(1.0))); Assert.AreEqual(1m, (decimal)(new JValue("1"))); Assert.AreEqual(1m, (decimal)(new JValue(true))); Assert.AreEqual(TimeSpan.FromMinutes(1), (TimeSpan)(new JValue(TimeSpan.FromMinutes(1)))); Assert.AreEqual("00:01:00", (string)(new JValue(TimeSpan.FromMinutes(1)))); Assert.AreEqual(TimeSpan.FromMinutes(1), (TimeSpan)(new JValue("00:01:00"))); Assert.AreEqual("46efe013-b56a-4e83-99e4-4dce7678a5bc", (string)(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC")))); Assert.AreEqual("http://www.google.com/", (string)(new JValue(new Uri("http://www.google.com")))); Assert.AreEqual(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"), (Guid)(new JValue("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"))); Assert.AreEqual(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"), (Guid)(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC")))); Assert.AreEqual(new Uri("http://www.google.com"), (Uri)(new JValue("http://www.google.com"))); Assert.AreEqual(new Uri("http://www.google.com"), (Uri)(new JValue(new Uri("http://www.google.com")))); Assert.AreEqual(null, (Uri)(JValue.CreateNull())); Assert.AreEqual(Convert.ToBase64String(Encoding.UTF8.GetBytes("hi")), (string)(new JValue(Encoding.UTF8.GetBytes("hi")))); CollectionAssert.AreEquivalent((byte[])Encoding.UTF8.GetBytes("hi"), (byte[])(new JValue(Convert.ToBase64String(Encoding.UTF8.GetBytes("hi"))))); Assert.AreEqual(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"), (Guid)(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC").ToByteArray()))); Assert.AreEqual(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"), (Guid?)(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC").ToByteArray()))); Assert.AreEqual((sbyte?)1, (sbyte?)(new JValue((short?)1))); Assert.AreEqual(null, (Uri)(JValue)null); Assert.AreEqual(null, (int?)(JValue)null); Assert.AreEqual(null, (uint?)(JValue)null); Assert.AreEqual(null, (Guid?)(JValue)null); Assert.AreEqual(null, (TimeSpan?)(JValue)null); Assert.AreEqual(null, (byte[])(JValue)null); Assert.AreEqual(null, (bool?)(JValue)null); Assert.AreEqual(null, (char?)(JValue)null); Assert.AreEqual(null, (DateTime?)(JValue)null); #if !NET20 Assert.AreEqual(null, (DateTimeOffset?)(JValue)null); #endif Assert.AreEqual(null, (short?)(JValue)null); Assert.AreEqual(null, (ushort?)(JValue)null); Assert.AreEqual(null, (byte?)(JValue)null); Assert.AreEqual(null, (byte?)(JValue)null); Assert.AreEqual(null, (sbyte?)(JValue)null); Assert.AreEqual(null, (sbyte?)(JValue)null); Assert.AreEqual(null, (long?)(JValue)null); Assert.AreEqual(null, (ulong?)(JValue)null); Assert.AreEqual(null, (double?)(JValue)null); Assert.AreEqual(null, (float?)(JValue)null); byte[] data = new byte[0]; Assert.AreEqual(data, (byte[])(new JValue(data))); Assert.AreEqual(5, (int)(new JValue(StringComparison.OrdinalIgnoreCase))); #if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1 string bigIntegerText = "1234567899999999999999999999999999999999999999999999999999999999999990"; Assert.AreEqual(BigInteger.Parse(bigIntegerText), (new JValue(BigInteger.Parse(bigIntegerText))).Value); Assert.AreEqual(BigInteger.Parse(bigIntegerText), (new JValue(bigIntegerText)).ToObject<BigInteger>()); Assert.AreEqual(new BigInteger(long.MaxValue), (new JValue(long.MaxValue)).ToObject<BigInteger>()); Assert.AreEqual(new BigInteger(4.5d), (new JValue((4.5d))).ToObject<BigInteger>()); Assert.AreEqual(new BigInteger(4.5f), (new JValue((4.5f))).ToObject<BigInteger>()); Assert.AreEqual(new BigInteger(byte.MaxValue), (new JValue(byte.MaxValue)).ToObject<BigInteger>()); Assert.AreEqual(new BigInteger(123), (new JValue(123)).ToObject<BigInteger>()); Assert.AreEqual(new BigInteger(123), (new JValue(123)).ToObject<BigInteger?>()); Assert.AreEqual(null, (JValue.CreateNull()).ToObject<BigInteger?>()); byte[] intData = BigInteger.Parse(bigIntegerText).ToByteArray(); Assert.AreEqual(BigInteger.Parse(bigIntegerText), (new JValue(intData)).ToObject<BigInteger>()); Assert.AreEqual(4.0d, (double)(new JValue(new BigInteger(4.5d)))); Assert.AreEqual(true, (bool)(new JValue(new BigInteger(1)))); Assert.AreEqual(long.MaxValue, (long)(new JValue(new BigInteger(long.MaxValue)))); Assert.AreEqual(long.MaxValue, (long)(new JValue(new BigInteger(new byte[] { 255, 255, 255, 255, 255, 255, 255, 127 })))); Assert.AreEqual("9223372036854775807", (string)(new JValue(new BigInteger(long.MaxValue)))); intData = (byte[])(new JValue(new BigInteger(long.MaxValue))); CollectionAssert.AreEqual(new byte[] { 255, 255, 255, 255, 255, 255, 255, 127 }, intData); #endif } [Test] public void FailedCasting() { ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(true); }, "Can not convert Boolean to DateTime."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(1); }, "Can not convert Integer to DateTime."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(1.1); }, "Can not convert Float to DateTime."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(1.1m); }, "Can not convert Float to DateTime."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(TimeSpan.Zero); }, "Can not convert TimeSpan to DateTime."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(new Uri("http://www.google.com")); }, "Can not convert Uri to DateTime."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)JValue.CreateNull(); }, "Can not convert Null to DateTime."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(Guid.NewGuid()); }, "Can not convert Guid to DateTime."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(true); }, "Can not convert Boolean to Uri."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(1); }, "Can not convert Integer to Uri."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(1.1); }, "Can not convert Float to Uri."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(1.1m); }, "Can not convert Float to Uri."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(TimeSpan.Zero); }, "Can not convert TimeSpan to Uri."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(Guid.NewGuid()); }, "Can not convert Guid to Uri."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(DateTime.Now); }, "Can not convert Date to Uri."); #if !NET20 ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(DateTimeOffset.Now); }, "Can not convert Date to Uri."); #endif ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(true); }, "Can not convert Boolean to TimeSpan."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(1); }, "Can not convert Integer to TimeSpan."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(1.1); }, "Can not convert Float to TimeSpan."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(1.1m); }, "Can not convert Float to TimeSpan."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)JValue.CreateNull(); }, "Can not convert Null to TimeSpan."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(Guid.NewGuid()); }, "Can not convert Guid to TimeSpan."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(DateTime.Now); }, "Can not convert Date to TimeSpan."); #if !NET20 ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(DateTimeOffset.Now); }, "Can not convert Date to TimeSpan."); #endif ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(new Uri("http://www.google.com")); }, "Can not convert Uri to TimeSpan."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(true); }, "Can not convert Boolean to Guid."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(1); }, "Can not convert Integer to Guid."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(1.1); }, "Can not convert Float to Guid."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(1.1m); }, "Can not convert Float to Guid."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)JValue.CreateNull(); }, "Can not convert Null to Guid."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(DateTime.Now); }, "Can not convert Date to Guid."); #if !NET20 ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(DateTimeOffset.Now); }, "Can not convert Date to Guid."); #endif ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(TimeSpan.FromMinutes(1)); }, "Can not convert TimeSpan to Guid."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(new Uri("http://www.google.com")); }, "Can not convert Uri to Guid."); #if !NET20 ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTimeOffset)new JValue(true); }, "Can not convert Boolean to DateTimeOffset."); #endif ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(true); }, "Can not convert Boolean to Uri."); #if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1 ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue(new Uri("http://www.google.com"))).ToObject<BigInteger>(); }, "Can not convert Uri to BigInteger."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (JValue.CreateNull()).ToObject<BigInteger>(); }, "Can not convert Null to BigInteger."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue(Guid.NewGuid())).ToObject<BigInteger>(); }, "Can not convert Guid to BigInteger."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue(Guid.NewGuid())).ToObject<BigInteger?>(); }, "Can not convert Guid to BigInteger."); #endif ExceptionAssert.Throws<ArgumentException>(() => { var i = (sbyte?)new JValue(DateTime.Now); }, "Can not convert Date to SByte."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (sbyte)new JValue(DateTime.Now); }, "Can not convert Date to SByte."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue("Ordinal1")).ToObject<StringComparison>(); }, "Could not convert 'Ordinal1' to StringComparison."); ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue("Ordinal1")).ToObject<StringComparison?>(); }, "Could not convert 'Ordinal1' to StringComparison."); } [Test] public void ToObject() { #if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1 Assert.AreEqual((BigInteger)1, (new JValue(1).ToObject(typeof(BigInteger)))); Assert.AreEqual((BigInteger)1, (new JValue(1).ToObject(typeof(BigInteger?)))); Assert.AreEqual((BigInteger?)null, (JValue.CreateNull().ToObject(typeof(BigInteger?)))); #endif Assert.AreEqual((ushort)1, (new JValue(1).ToObject(typeof(ushort)))); Assert.AreEqual((ushort)1, (new JValue(1).ToObject(typeof(ushort?)))); Assert.AreEqual((uint)1L, (new JValue(1).ToObject(typeof(uint)))); Assert.AreEqual((uint)1L, (new JValue(1).ToObject(typeof(uint?)))); Assert.AreEqual((ulong)1L, (new JValue(1).ToObject(typeof(ulong)))); Assert.AreEqual((ulong)1L, (new JValue(1).ToObject(typeof(ulong?)))); Assert.AreEqual((sbyte)1L, (new JValue(1).ToObject(typeof(sbyte)))); Assert.AreEqual((sbyte)1L, (new JValue(1).ToObject(typeof(sbyte?)))); Assert.AreEqual(null, (JValue.CreateNull().ToObject(typeof(sbyte?)))); Assert.AreEqual((byte)1L, (new JValue(1).ToObject(typeof(byte)))); Assert.AreEqual((byte)1L, (new JValue(1).ToObject(typeof(byte?)))); Assert.AreEqual((short)1L, (new JValue(1).ToObject(typeof(short)))); Assert.AreEqual((short)1L, (new JValue(1).ToObject(typeof(short?)))); Assert.AreEqual(1, (new JValue(1).ToObject(typeof(int)))); Assert.AreEqual(1, (new JValue(1).ToObject(typeof(int?)))); Assert.AreEqual(1L, (new JValue(1).ToObject(typeof(long)))); Assert.AreEqual(1L, (new JValue(1).ToObject(typeof(long?)))); Assert.AreEqual((float)1, (new JValue(1.0).ToObject(typeof(float)))); Assert.AreEqual((float)1, (new JValue(1.0).ToObject(typeof(float?)))); Assert.AreEqual((double)1, (new JValue(1.0).ToObject(typeof(double)))); Assert.AreEqual((double)1, (new JValue(1.0).ToObject(typeof(double?)))); Assert.AreEqual(1m, (new JValue(1).ToObject(typeof(decimal)))); Assert.AreEqual(1m, (new JValue(1).ToObject(typeof(decimal?)))); Assert.AreEqual(true, (new JValue(true).ToObject(typeof(bool)))); Assert.AreEqual(true, (new JValue(true).ToObject(typeof(bool?)))); Assert.AreEqual('b', (new JValue('b').ToObject(typeof(char)))); Assert.AreEqual('b', (new JValue('b').ToObject(typeof(char?)))); Assert.AreEqual(TimeSpan.MaxValue, (new JValue(TimeSpan.MaxValue).ToObject(typeof(TimeSpan)))); Assert.AreEqual(TimeSpan.MaxValue, (new JValue(TimeSpan.MaxValue).ToObject(typeof(TimeSpan?)))); Assert.AreEqual(DateTime.MaxValue, (new JValue(DateTime.MaxValue).ToObject(typeof(DateTime)))); Assert.AreEqual(DateTime.MaxValue, (new JValue(DateTime.MaxValue).ToObject(typeof(DateTime?)))); #if !NET20 Assert.AreEqual(DateTimeOffset.MaxValue, (new JValue(DateTimeOffset.MaxValue).ToObject(typeof(DateTimeOffset)))); Assert.AreEqual(DateTimeOffset.MaxValue, (new JValue(DateTimeOffset.MaxValue).ToObject(typeof(DateTimeOffset?)))); #endif Assert.AreEqual("b", (new JValue("b").ToObject(typeof(string)))); Assert.AreEqual(new Guid("A34B2080-B5F0-488E-834D-45D44ECB9E5C"), (new JValue(new Guid("A34B2080-B5F0-488E-834D-45D44ECB9E5C")).ToObject(typeof(Guid)))); Assert.AreEqual(new Guid("A34B2080-B5F0-488E-834D-45D44ECB9E5C"), (new JValue(new Guid("A34B2080-B5F0-488E-834D-45D44ECB9E5C")).ToObject(typeof(Guid?)))); Assert.AreEqual(new Uri("http://www.google.com/"), (new JValue(new Uri("http://www.google.com/")).ToObject(typeof(Uri)))); Assert.AreEqual(StringComparison.Ordinal, (new JValue("Ordinal").ToObject(typeof(StringComparison)))); Assert.AreEqual(StringComparison.Ordinal, (new JValue("Ordinal").ToObject(typeof(StringComparison?)))); Assert.AreEqual(null, (JValue.CreateNull().ToObject(typeof(StringComparison?)))); } [Test] public void ImplicitCastingTo() { Assert.IsTrue(JToken.DeepEquals(new JValue(new DateTime(2000, 12, 20)), (JValue)new DateTime(2000, 12, 20))); #if !NET20 Assert.IsTrue(JToken.DeepEquals(new JValue(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero)), (JValue)new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero))); Assert.IsTrue(JToken.DeepEquals(new JValue((DateTimeOffset?)null), (JValue)(DateTimeOffset?)null)); #endif #if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1 // had to remove implicit casting to avoid user reference to System.Numerics.dll Assert.IsTrue(JToken.DeepEquals(new JValue(new BigInteger(1)), new JValue(new BigInteger(1)))); Assert.IsTrue(JToken.DeepEquals(new JValue((BigInteger?)null), new JValue((BigInteger?)null))); #endif Assert.IsTrue(JToken.DeepEquals(new JValue(true), (JValue)true)); Assert.IsTrue(JToken.DeepEquals(new JValue(true), (JValue)true)); Assert.IsTrue(JToken.DeepEquals(new JValue(true), (JValue)(bool?)true)); Assert.IsTrue(JToken.DeepEquals(new JValue((bool?)null), (JValue)(bool?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue(10), (JValue)10)); Assert.IsTrue(JToken.DeepEquals(new JValue((long?)null), (JValue)(long?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue((DateTime?)null), (JValue)(DateTime?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue(long.MaxValue), (JValue)long.MaxValue)); Assert.IsTrue(JToken.DeepEquals(new JValue((int?)null), (JValue)(int?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue((short?)null), (JValue)(short?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue((double?)null), (JValue)(double?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue((uint?)null), (JValue)(uint?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue((decimal?)null), (JValue)(decimal?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue((ulong?)null), (JValue)(ulong?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue((sbyte?)null), (JValue)(sbyte?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue((sbyte)1), (JValue)(sbyte)1)); Assert.IsTrue(JToken.DeepEquals(new JValue((byte?)null), (JValue)(byte?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue((byte)1), (JValue)(byte)1)); Assert.IsTrue(JToken.DeepEquals(new JValue((ushort?)null), (JValue)(ushort?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue(short.MaxValue), (JValue)short.MaxValue)); Assert.IsTrue(JToken.DeepEquals(new JValue(ushort.MaxValue), (JValue)ushort.MaxValue)); Assert.IsTrue(JToken.DeepEquals(new JValue(11.1f), (JValue)11.1f)); Assert.IsTrue(JToken.DeepEquals(new JValue(float.MinValue), (JValue)float.MinValue)); Assert.IsTrue(JToken.DeepEquals(new JValue(double.MinValue), (JValue)double.MinValue)); Assert.IsTrue(JToken.DeepEquals(new JValue(uint.MaxValue), (JValue)uint.MaxValue)); Assert.IsTrue(JToken.DeepEquals(new JValue(ulong.MaxValue), (JValue)ulong.MaxValue)); Assert.IsTrue(JToken.DeepEquals(new JValue(ulong.MinValue), (JValue)ulong.MinValue)); Assert.IsTrue(JToken.DeepEquals(new JValue((string)null), (JValue)(string)null)); Assert.IsTrue(JToken.DeepEquals(new JValue((DateTime?)null), (JValue)(DateTime?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue(decimal.MaxValue), (JValue)decimal.MaxValue)); Assert.IsTrue(JToken.DeepEquals(new JValue(decimal.MaxValue), (JValue)(decimal?)decimal.MaxValue)); Assert.IsTrue(JToken.DeepEquals(new JValue(decimal.MinValue), (JValue)decimal.MinValue)); Assert.IsTrue(JToken.DeepEquals(new JValue(float.MaxValue), (JValue)(float?)float.MaxValue)); Assert.IsTrue(JToken.DeepEquals(new JValue(double.MaxValue), (JValue)(double?)double.MaxValue)); Assert.IsTrue(JToken.DeepEquals(JValue.CreateNull(), (JValue)(double?)null)); Assert.IsFalse(JToken.DeepEquals(new JValue(true), (JValue)(bool?)null)); Assert.IsFalse(JToken.DeepEquals(JValue.CreateNull(), (JValue)(object)null)); byte[] emptyData = new byte[0]; Assert.IsTrue(JToken.DeepEquals(new JValue(emptyData), (JValue)emptyData)); Assert.IsFalse(JToken.DeepEquals(new JValue(emptyData), (JValue)new byte[1])); Assert.IsTrue(JToken.DeepEquals(new JValue(Encoding.UTF8.GetBytes("Hi")), (JValue)Encoding.UTF8.GetBytes("Hi"))); Assert.IsTrue(JToken.DeepEquals(new JValue(TimeSpan.FromMinutes(1)), (JValue)TimeSpan.FromMinutes(1))); Assert.IsTrue(JToken.DeepEquals(JValue.CreateNull(), (JValue)(TimeSpan?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue(TimeSpan.FromMinutes(1)), (JValue)(TimeSpan?)TimeSpan.FromMinutes(1))); Assert.IsTrue(JToken.DeepEquals(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC")), (JValue)new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"))); Assert.IsTrue(JToken.DeepEquals(new JValue(new Uri("http://www.google.com")), (JValue)new Uri("http://www.google.com"))); Assert.IsTrue(JToken.DeepEquals(JValue.CreateNull(), (JValue)(Uri)null)); Assert.IsTrue(JToken.DeepEquals(JValue.CreateNull(), (JValue)(Guid?)null)); } [Test] public void Root() { JArray a = new JArray( 5, 6, new JArray(7, 8), new JArray(9, 10) ); Assert.AreEqual(a, a.Root); Assert.AreEqual(a, a[0].Root); Assert.AreEqual(a, ((JArray)a[2])[0].Root); } [Test] public void Remove() { JToken t; JArray a = new JArray( 5, 6, new JArray(7, 8), new JArray(9, 10) ); a[0].Remove(); Assert.AreEqual(6, (int)a[0]); a[1].Remove(); Assert.AreEqual(6, (int)a[0]); Assert.IsTrue(JToken.DeepEquals(new JArray(9, 10), a[1])); Assert.AreEqual(2, a.Count()); t = a[1]; t.Remove(); Assert.AreEqual(6, (int)a[0]); Assert.IsNull(t.Next); Assert.IsNull(t.Previous); Assert.IsNull(t.Parent); t = a[0]; t.Remove(); Assert.AreEqual(0, a.Count()); Assert.IsNull(t.Next); Assert.IsNull(t.Previous); Assert.IsNull(t.Parent); } [Test] public void AfterSelf() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); JToken t = a[1]; List<JToken> afterTokens = t.AfterSelf().ToList(); Assert.AreEqual(2, afterTokens.Count); Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2), afterTokens[0])); Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), afterTokens[1])); } [Test] public void BeforeSelf() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); JToken t = a[2]; List<JToken> beforeTokens = t.BeforeSelf().ToList(); Assert.AreEqual(2, beforeTokens.Count); Assert.IsTrue(JToken.DeepEquals(new JValue(5), beforeTokens[0])); Assert.IsTrue(JToken.DeepEquals(new JArray(1), beforeTokens[1])); } [Test] public void HasValues() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); Assert.IsTrue(a.HasValues); } [Test] public void Ancestors() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); JToken t = a[1][0]; List<JToken> ancestors = t.Ancestors().ToList(); Assert.AreEqual(2, ancestors.Count()); Assert.AreEqual(a[1], ancestors[0]); Assert.AreEqual(a, ancestors[1]); } [Test] public void AncestorsAndSelf() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); JToken t = a[1][0]; List<JToken> ancestors = t.AncestorsAndSelf().ToList(); Assert.AreEqual(3, ancestors.Count()); Assert.AreEqual(t, ancestors[0]); Assert.AreEqual(a[1], ancestors[1]); Assert.AreEqual(a, ancestors[2]); } [Test] public void AncestorsAndSelf_Many() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); JObject o = new JObject { { "prop1", "value1" } }; JToken t1 = a[1][0]; JToken t2 = o["prop1"]; List<JToken> source = new List<JToken> { t1, t2 }; List<JToken> ancestors = source.AncestorsAndSelf().ToList(); Assert.AreEqual(6, ancestors.Count()); Assert.AreEqual(t1, ancestors[0]); Assert.AreEqual(a[1], ancestors[1]); Assert.AreEqual(a, ancestors[2]); Assert.AreEqual(t2, ancestors[3]); Assert.AreEqual(o.Property("prop1"), ancestors[4]); Assert.AreEqual(o, ancestors[5]); } [Test] public void Ancestors_Many() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); JObject o = new JObject { { "prop1", "value1" } }; JToken t1 = a[1][0]; JToken t2 = o["prop1"]; List<JToken> source = new List<JToken> { t1, t2 }; List<JToken> ancestors = source.Ancestors().ToList(); Assert.AreEqual(4, ancestors.Count()); Assert.AreEqual(a[1], ancestors[0]); Assert.AreEqual(a, ancestors[1]); Assert.AreEqual(o.Property("prop1"), ancestors[2]); Assert.AreEqual(o, ancestors[3]); } [Test] public void Descendants() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); List<JToken> descendants = a.Descendants().ToList(); Assert.AreEqual(10, descendants.Count()); Assert.AreEqual(5, (int)descendants[0]); Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), descendants[descendants.Count - 4])); Assert.AreEqual(1, (int)descendants[descendants.Count - 3]); Assert.AreEqual(2, (int)descendants[descendants.Count - 2]); Assert.AreEqual(3, (int)descendants[descendants.Count - 1]); } [Test] public void Descendants_Many() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); JObject o = new JObject { { "prop1", "value1" } }; List<JContainer> source = new List<JContainer> { a, o }; List<JToken> descendants = source.Descendants().ToList(); Assert.AreEqual(12, descendants.Count()); Assert.AreEqual(5, (int)descendants[0]); Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), descendants[descendants.Count - 6])); Assert.AreEqual(1, (int)descendants[descendants.Count - 5]); Assert.AreEqual(2, (int)descendants[descendants.Count - 4]); Assert.AreEqual(3, (int)descendants[descendants.Count - 3]); Assert.AreEqual(o.Property("prop1"), descendants[descendants.Count - 2]); Assert.AreEqual(o["prop1"], descendants[descendants.Count - 1]); } [Test] public void DescendantsAndSelf() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); List<JToken> descendantsAndSelf = a.DescendantsAndSelf().ToList(); Assert.AreEqual(11, descendantsAndSelf.Count()); Assert.AreEqual(a, descendantsAndSelf[0]); Assert.AreEqual(5, (int)descendantsAndSelf[1]); Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), descendantsAndSelf[descendantsAndSelf.Count - 4])); Assert.AreEqual(1, (int)descendantsAndSelf[descendantsAndSelf.Count - 3]); Assert.AreEqual(2, (int)descendantsAndSelf[descendantsAndSelf.Count - 2]); Assert.AreEqual(3, (int)descendantsAndSelf[descendantsAndSelf.Count - 1]); } [Test] public void DescendantsAndSelf_Many() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); JObject o = new JObject { { "prop1", "value1" } }; List<JContainer> source = new List<JContainer> { a, o }; List<JToken> descendantsAndSelf = source.DescendantsAndSelf().ToList(); Assert.AreEqual(14, descendantsAndSelf.Count()); Assert.AreEqual(a, descendantsAndSelf[0]); Assert.AreEqual(5, (int)descendantsAndSelf[1]); Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), descendantsAndSelf[descendantsAndSelf.Count - 7])); Assert.AreEqual(1, (int)descendantsAndSelf[descendantsAndSelf.Count - 6]); Assert.AreEqual(2, (int)descendantsAndSelf[descendantsAndSelf.Count - 5]); Assert.AreEqual(3, (int)descendantsAndSelf[descendantsAndSelf.Count - 4]); Assert.AreEqual(o, descendantsAndSelf[descendantsAndSelf.Count - 3]); Assert.AreEqual(o.Property("prop1"), descendantsAndSelf[descendantsAndSelf.Count - 2]); Assert.AreEqual(o["prop1"], descendantsAndSelf[descendantsAndSelf.Count - 1]); } [Test] public void CreateWriter() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); JsonWriter writer = a.CreateWriter(); Assert.IsNotNull(writer); Assert.AreEqual(4, a.Count()); writer.WriteValue("String"); Assert.AreEqual(5, a.Count()); Assert.AreEqual("String", (string)a[4]); writer.WriteStartObject(); writer.WritePropertyName("Property"); writer.WriteValue("PropertyValue"); writer.WriteEnd(); Assert.AreEqual(6, a.Count()); Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("Property", "PropertyValue")), a[5])); } [Test] public void AddFirst() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); a.AddFirst("First"); Assert.AreEqual("First", (string)a[0]); Assert.AreEqual(a, a[0].Parent); Assert.AreEqual(a[1], a[0].Next); Assert.AreEqual(5, a.Count()); a.AddFirst("NewFirst"); Assert.AreEqual("NewFirst", (string)a[0]); Assert.AreEqual(a, a[0].Parent); Assert.AreEqual(a[1], a[0].Next); Assert.AreEqual(6, a.Count()); Assert.AreEqual(a[0], a[0].Next.Previous); } [Test] public void RemoveAll() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); JToken first = a.First; Assert.AreEqual(5, (int)first); a.RemoveAll(); Assert.AreEqual(0, a.Count()); Assert.IsNull(first.Parent); Assert.IsNull(first.Next); } [Test] public void AddPropertyToArray() { ExceptionAssert.Throws<ArgumentException>(() => { JArray a = new JArray(); a.Add(new JProperty("PropertyName")); }, "Can not add Newtonsoft.Json.Linq.JProperty to Newtonsoft.Json.Linq.JArray."); } [Test] public void AddValueToObject() { ExceptionAssert.Throws<ArgumentException>(() => { JObject o = new JObject(); o.Add(5); }, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject."); } [Test] public void Replace() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); a[0].Replace(new JValue(int.MaxValue)); Assert.AreEqual(int.MaxValue, (int)a[0]); Assert.AreEqual(4, a.Count()); a[1][0].Replace(new JValue("Test")); Assert.AreEqual("Test", (string)a[1][0]); a[2].Replace(new JValue(int.MaxValue)); Assert.AreEqual(int.MaxValue, (int)a[2]); Assert.AreEqual(4, a.Count()); Assert.IsTrue(JToken.DeepEquals(new JArray(int.MaxValue, new JArray("Test"), int.MaxValue, new JArray(1, 2, 3)), a)); } [Test] public void ToStringWithConverters() { JArray a = new JArray( new JValue(new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc)) ); string json = a.ToString(Formatting.Indented, new IsoDateTimeConverter()); StringAssert.AreEqual(@"[ ""2009-02-15T00:00:00Z"" ]", json); json = JsonConvert.SerializeObject(a, new IsoDateTimeConverter()); Assert.AreEqual(@"[""2009-02-15T00:00:00Z""]", json); } [Test] public void ToStringWithNoIndenting() { JArray a = new JArray( new JValue(new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc)) ); string json = a.ToString(Formatting.None, new IsoDateTimeConverter()); Assert.AreEqual(@"[""2009-02-15T00:00:00Z""]", json); } [Test] public void AddAfterSelf() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); a[1].AddAfterSelf("pie"); Assert.AreEqual(5, (int)a[0]); Assert.AreEqual(1, a[1].Count()); Assert.AreEqual("pie", (string)a[2]); Assert.AreEqual(5, a.Count()); a[4].AddAfterSelf("lastpie"); Assert.AreEqual("lastpie", (string)a[5]); Assert.AreEqual("lastpie", (string)a.Last); } [Test] public void AddBeforeSelf() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); a[1].AddBeforeSelf("pie"); Assert.AreEqual(5, (int)a[0]); Assert.AreEqual("pie", (string)a[1]); Assert.AreEqual(a, a[1].Parent); Assert.AreEqual(a[2], a[1].Next); Assert.AreEqual(5, a.Count()); a[0].AddBeforeSelf("firstpie"); Assert.AreEqual("firstpie", (string)a[0]); Assert.AreEqual(5, (int)a[1]); Assert.AreEqual("pie", (string)a[2]); Assert.AreEqual(a, a[0].Parent); Assert.AreEqual(a[1], a[0].Next); Assert.AreEqual(6, a.Count()); a.Last.AddBeforeSelf("secondlastpie"); Assert.AreEqual("secondlastpie", (string)a[5]); Assert.AreEqual(7, a.Count()); } [Test] public void DeepClone() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3), new JObject( new JProperty("First", new JValue(Encoding.UTF8.GetBytes("Hi"))), new JProperty("Second", 1), new JProperty("Third", null), new JProperty("Fourth", new JConstructor("Date", 12345)), new JProperty("Fifth", double.PositiveInfinity), new JProperty("Sixth", double.NaN) ) ); JArray a2 = (JArray)a.DeepClone(); StringAssert.AreEqual(@"[ 5, [ 1 ], [ 1, 2 ], [ 1, 2, 3 ], { ""First"": ""SGk="", ""Second"": 1, ""Third"": null, ""Fourth"": new Date( 12345 ), ""Fifth"": ""Infinity"", ""Sixth"": ""NaN"" } ]", a2.ToString(Formatting.Indented)); Assert.IsTrue(a.DeepEquals(a2)); } #if !(PORTABLE || DNXCORE50 || PORTABLE40) [Test] public void Clone() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3), new JObject( new JProperty("First", new JValue(Encoding.UTF8.GetBytes("Hi"))), new JProperty("Second", 1), new JProperty("Third", null), new JProperty("Fourth", new JConstructor("Date", 12345)), new JProperty("Fifth", double.PositiveInfinity), new JProperty("Sixth", double.NaN) ) ); ICloneable c = a; JArray a2 = (JArray)c.Clone(); Assert.IsTrue(a.DeepEquals(a2)); } #endif [Test] public void DoubleDeepEquals() { JArray a = new JArray( double.NaN, double.PositiveInfinity, double.NegativeInfinity ); JArray a2 = (JArray)a.DeepClone(); Assert.IsTrue(a.DeepEquals(a2)); double d = 1 + 0.1 + 0.1 + 0.1; JValue v1 = new JValue(d); JValue v2 = new JValue(1.3); Assert.IsTrue(v1.DeepEquals(v2)); } [Test] public void ParseAdditionalContent() { ExceptionAssert.Throws<JsonReaderException>(() => { string json = @"[ ""Small"", ""Medium"", ""Large"" ],"; JToken.Parse(json); }, "Additional text encountered after finished reading JSON content: ,. Path '', line 5, position 1."); } [Test] public void Path() { JObject o = new JObject( new JProperty("Test1", new JArray(1, 2, 3)), new JProperty("Test2", "Test2Value"), new JProperty("Test3", new JObject(new JProperty("Test1", new JArray(1, new JObject(new JProperty("Test1", 1)), 3)))), new JProperty("Test4", new JConstructor("Date", new JArray(1, 2, 3))) ); JToken t = o.SelectToken("Test1[0]"); Assert.AreEqual("Test1[0]", t.Path); t = o.SelectToken("Test2"); Assert.AreEqual("Test2", t.Path); t = o.SelectToken(""); Assert.AreEqual("", t.Path); t = o.SelectToken("Test4[0][0]"); Assert.AreEqual("Test4[0][0]", t.Path); t = o.SelectToken("Test4[0]"); Assert.AreEqual("Test4[0]", t.Path); t = t.DeepClone(); Assert.AreEqual("", t.Path); t = o.SelectToken("Test3.Test1[1].Test1"); Assert.AreEqual("Test3.Test1[1].Test1", t.Path); JArray a = new JArray(1); Assert.AreEqual("", a.Path); Assert.AreEqual("[0]", a[0].Path); } [Test] public void Parse_NoComments() { string json = "{'prop':[1,2/*comment*/,3]}"; JToken o = JToken.Parse(json, new JsonLoadSettings { CommentHandling = CommentHandling.Ignore }); Assert.AreEqual(3, o["prop"].Count()); Assert.AreEqual(1, (int)o["prop"][0]); Assert.AreEqual(2, (int)o["prop"][1]); Assert.AreEqual(3, (int)o["prop"][2]); } } }
// ReSharper disable RedundantArgumentDefaultValue namespace Gu.State.Tests { using System.Collections.Generic; using NUnit.Framework; using static ChangeTrackerTypes; public static partial class DirtyTrackerTests { public static class ReferenceLoops { [Test] public static void ParentChildCreateWhenParentDirtyLoop() { var changes = new List<string>(); var expectedChanges = new List<string>(); var x = new Parent { Name = "p1", Child = new Child("c") }; x.Child.Parent = x; var y = new Parent { Name = "p2", Child = new Child("c") }; y.Child.Parent = y; using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(true, tracker.IsDirty); CollectionAssert.IsEmpty(changes); var expected = "Parent Child Parent ... Name x: p1 y: p2"; var actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); x.Name = y.Name; y.Name = x.Name; expectedChanges.Add("Diff", "IsDirty"); CollectionAssert.AreEqual(expectedChanges, changes); Assert.AreEqual(false, tracker.IsDirty); } [Test] public static void ParentChildRenameParentLast() { var changes = new List<string>(); var expectedChanges = new List<string>(); var x = new Parent(); var y = new Parent(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); x.Name = "Poppa"; Assert.AreEqual(true, tracker.IsDirty); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); var expected = "Parent Name x: Poppa y: null"; var actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); x.Child = new Child("Child"); Assert.AreEqual(true, tracker.IsDirty); expectedChanges.Add("Diff"); CollectionAssert.AreEqual(expectedChanges, changes); expected = "Parent Child x: Gu.State.Tests.ChangeTrackerTypes+Child y: null Name x: Poppa y: null"; actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); x.Child.Parent = x; Assert.AreEqual(true, tracker.IsDirty); CollectionAssert.AreEqual(expectedChanges, changes); expected = "Parent Child x: Gu.State.Tests.ChangeTrackerTypes+Child y: null Name x: Poppa y: null"; actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); y.Child = new Child("Child"); Assert.AreEqual(true, tracker.IsDirty); expectedChanges.Add("Diff"); CollectionAssert.AreEqual(expectedChanges, changes); expected = "Parent Child Parent x: Gu.State.Tests.ChangeTrackerTypes+Parent y: null Name x: Poppa y: null"; actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); y.Child.Parent = y; Assert.AreEqual(true, tracker.IsDirty); expectedChanges.Add("Diff"); CollectionAssert.AreEqual(expectedChanges, changes); expected = "Parent Child Parent ... Name x: Poppa y: null"; actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); y.Name = x.Name; Assert.AreEqual(false, tracker.IsDirty); expectedChanges.Add("Diff", "IsDirty"); CollectionAssert.AreEqual(expectedChanges, changes); Assert.AreEqual(null, tracker.Diff); Assert.AreSame(x.Child, x.Child.Parent.Child); Assert.AreSame(x, x.Child.Parent); Assert.AreSame(y.Child, y.Child.Parent.Child); Assert.AreSame(y, y.Child.Parent); } [Test] public static void WithParentChildRenameParentLast() { var changes = new List<string>(); var expectedChanges = new List<string>(); var x = new With<Parent>(); var y = new With<Parent>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); x.Name = "Root"; Assert.AreEqual(true, tracker.IsDirty); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); var expected = "With<Parent> Name x: Root y: null"; var actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); x.Value = new Parent("Poppa1", null); Assert.AreEqual(true, tracker.IsDirty); expectedChanges.Add("Diff"); CollectionAssert.AreEqual(expectedChanges, changes); expected = "With<Parent> Name x: Root y: null Value x: Gu.State.Tests.ChangeTrackerTypes+Parent y: null"; actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); y.Value = new Parent("Poppa2", null); Assert.AreEqual(true, tracker.IsDirty); expectedChanges.Add("Diff"); CollectionAssert.AreEqual(expectedChanges, changes); expected = "With<Parent> Name x: Root y: null Value Name x: Poppa1 y: Poppa2"; actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); x.Value.Child = new Child("Child1"); Assert.AreEqual(true, tracker.IsDirty); expectedChanges.Add("Diff"); CollectionAssert.AreEqual(expectedChanges, changes); expected = "With<Parent> Name x: Root y: null Value Child x: Gu.State.Tests.ChangeTrackerTypes+Child y: null Name x: Poppa1 y: Poppa2"; actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); y.Value.Child = new Child("Child2"); Assert.AreEqual(true, tracker.IsDirty); expectedChanges.Add("Diff"); CollectionAssert.AreEqual(expectedChanges, changes); expected = "With<Parent> Name x: Root y: null Value Child Name x: Child1 y: Child2 Name x: Poppa1 y: Poppa2"; actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); x.Value.Child.Parent = x.Value; Assert.AreEqual(true, tracker.IsDirty); expectedChanges.Add("Diff"); CollectionAssert.AreEqual(expectedChanges, changes); expected = "With<Parent> Name x: Root y: null Value Child Name x: Child1 y: Child2 Parent x: Gu.State.Tests.ChangeTrackerTypes+Parent y: null Name x: Poppa1 y: Poppa2"; actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); y.Value.Child.Parent = y.Value; Assert.AreEqual(true, tracker.IsDirty); expectedChanges.Add("Diff"); CollectionAssert.AreEqual(expectedChanges, changes); expected = "With<Parent> Name x: Root y: null Value Child Name x: Child1 y: Child2 Parent ... Name x: Poppa1 y: Poppa2"; actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); y.Value.Child.Name = x.Value.Child.Name; Assert.AreEqual(true, tracker.IsDirty); expectedChanges.Add("Diff"); CollectionAssert.AreEqual(expectedChanges, changes); expected = "With<Parent> Name x: Root y: null Value Child Parent ... Name x: Poppa1 y: Poppa2"; actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); y.Name = x.Name; Assert.AreEqual(true, tracker.IsDirty); expectedChanges.Add("Diff"); CollectionAssert.AreEqual(expectedChanges, changes); expected = "With<Parent> Value Child Parent ... Name x: Poppa1 y: Poppa2"; actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); y.Value.Name = x.Value.Name; Assert.AreEqual(false, tracker.IsDirty); expectedChanges.Add("Diff", "IsDirty"); CollectionAssert.AreEqual(expectedChanges, changes); Assert.AreEqual(null, tracker.Diff); } [Test] public static void ParentChildRenameChildLast() { var changes = new List<string>(); var expectedChanges = new List<string>(); var x = new Parent(); var y = new Parent(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); x.Name = "Poppa"; Assert.AreEqual(true, tracker.IsDirty); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); var expected = "Parent Name x: Poppa y: null"; var actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); x.Child = new Child("ChildX"); expectedChanges.Add("Diff"); CollectionAssert.AreEqual(expectedChanges, changes); expected = "Parent Child x: Gu.State.Tests.ChangeTrackerTypes+Child y: null Name x: Poppa y: null"; actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); x.Child.Parent = x; CollectionAssert.AreEqual(expectedChanges, changes); expected = "Parent Child x: Gu.State.Tests.ChangeTrackerTypes+Child y: null Name x: Poppa y: null"; actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); y.Child = new Child("ChildY"); expectedChanges.Add("Diff"); CollectionAssert.AreEqual(expectedChanges, changes); expected = "Parent Child Name x: ChildX y: ChildY Parent x: Gu.State.Tests.ChangeTrackerTypes+Parent y: null Name x: Poppa y: null"; actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); y.Child.Parent = y; expectedChanges.Add("Diff"); CollectionAssert.AreEqual(expectedChanges, changes); expected = "Parent Child Name x: ChildX y: ChildY Parent ... Name x: Poppa y: null"; actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); y.Name = x.Name; expectedChanges.Add("Diff"); CollectionAssert.AreEqual(expectedChanges, changes); expected = "Parent Child Name x: ChildX y: ChildY Parent ..."; actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); y.Child.Name = x.Child.Name; expectedChanges.Add("Diff", "IsDirty"); CollectionAssert.AreEqual(expectedChanges, changes); Assert.AreEqual(null, tracker.Diff); } } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Archiver.Codecs { public class StopReplayRequestEncoder { public const ushort BLOCK_LENGTH = 24; public const ushort TEMPLATE_ID = 7; public const ushort SCHEMA_ID = 101; public const ushort SCHEMA_VERSION = 6; private StopReplayRequestEncoder _parentMessage; private IMutableDirectBuffer _buffer; protected int _offset; protected int _limit; public StopReplayRequestEncoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IMutableDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public StopReplayRequestEncoder Wrap(IMutableDirectBuffer buffer, int offset) { this._buffer = buffer; this._offset = offset; Limit(offset + BLOCK_LENGTH); return this; } public StopReplayRequestEncoder WrapAndApplyHeader( IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder) { headerEncoder .Wrap(buffer, offset) .BlockLength(BLOCK_LENGTH) .TemplateId(TEMPLATE_ID) .SchemaId(SCHEMA_ID) .Version(SCHEMA_VERSION); return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH); } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int ControlSessionIdEncodingOffset() { return 0; } public static int ControlSessionIdEncodingLength() { return 8; } public static long ControlSessionIdNullValue() { return -9223372036854775808L; } public static long ControlSessionIdMinValue() { return -9223372036854775807L; } public static long ControlSessionIdMaxValue() { return 9223372036854775807L; } public StopReplayRequestEncoder ControlSessionId(long value) { _buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian); return this; } public static int CorrelationIdEncodingOffset() { return 8; } public static int CorrelationIdEncodingLength() { return 8; } public static long CorrelationIdNullValue() { return -9223372036854775808L; } public static long CorrelationIdMinValue() { return -9223372036854775807L; } public static long CorrelationIdMaxValue() { return 9223372036854775807L; } public StopReplayRequestEncoder CorrelationId(long value) { _buffer.PutLong(_offset + 8, value, ByteOrder.LittleEndian); return this; } public static int ReplaySessionIdEncodingOffset() { return 16; } public static int ReplaySessionIdEncodingLength() { return 8; } public static long ReplaySessionIdNullValue() { return -9223372036854775808L; } public static long ReplaySessionIdMinValue() { return -9223372036854775807L; } public static long ReplaySessionIdMaxValue() { return 9223372036854775807L; } public StopReplayRequestEncoder ReplaySessionId(long value) { _buffer.PutLong(_offset + 16, value, ByteOrder.LittleEndian); return this; } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { StopReplayRequestDecoder writer = new StopReplayRequestDecoder(); writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION); return writer.AppendTo(builder); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32.SafeHandles; using System.Security; namespace System.IO.MemoryMappedFiles { public partial class MemoryMappedFile { /// <summary> /// Used by the 2 Create factory method groups. A null fileHandle specifies that the /// memory mapped file should not be associated with an existing file on disk (ie start /// out empty). /// </summary> [SecurityCritical] private static unsafe SafeMemoryMappedFileHandle CreateCore( FileStream fileStream, string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) { if (mapName != null) { // Named maps are not supported in our Unix implementation. We could support named maps on Linux using // shared memory segments (shmget/shmat/shmdt/shmctl/etc.), but that doesn't work on OSX by default due // to very low default limits on OSX for the size of such objects; it also doesn't support behaviors // like copy-on-write or the ability to control handle inheritability, and reliably cleaning them up // relies on some non-conforming behaviors around shared memory IDs remaining valid even after they've // been marked for deletion (IPC_RMID). We could also support named maps using the current implementation // by not unlinking after creating the backing store, but then the backing stores would remain around // and accessible even after process exit, with no good way to appropriately clean them up. // (File-backed maps may still be used for cross-process communication.) throw CreateNamedMapsNotSupportedException(); } bool ownsFileStream = false; if (fileStream != null) { // This map is backed by a file. Make sure the file's size is increased to be // at least as big as the requested capacity of the map. if (fileStream.Length < capacity) { try { fileStream.SetLength(capacity); } catch (ArgumentException exc) { // If the capacity is too large, we'll get an ArgumentException from SetLength, // but on Windows this same condition is represented by an IOException. throw new IOException(exc.Message, exc); } } } else { // This map is backed by memory-only. With files, multiple views over the same map // will end up being able to share data through the same file-based backing store; // for anonymous maps, we need a similar backing store, or else multiple views would logically // each be their own map and wouldn't share any data. To achieve this, we create a backing object // (either memory or on disk, depending on the system) and use its file descriptor as the file handle. // However, we only do this when the permission is more than read-only. We can't change the size // of an object that has read-only permissions, but we also don't need to worry about sharing // views over a read-only, anonymous, memory-backed map, because the data will never change, so all views // will always see zero and can't change that. In that case, we just use the built-in anonymous support of // the map by leaving fileStream as null. Interop.Sys.MemoryMappedProtections protections = MemoryMappedView.GetProtections(access, forVerification: false); if ((protections & Interop.Sys.MemoryMappedProtections.PROT_WRITE) != 0 && capacity > 0) { ownsFileStream = true; fileStream = CreateSharedBackingObject(protections, capacity); } } return new SafeMemoryMappedFileHandle(fileStream, ownsFileStream, inheritability, access, options, capacity); } /// <summary> /// Used by the CreateOrOpen factory method groups. /// </summary> [SecurityCritical] private static SafeMemoryMappedFileHandle CreateOrOpenCore( string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) { // Since we don't support mapName != null, CreateOrOpenCore can't // be used to Open an existing map, and thus is identical to CreateCore. return CreateCore(null, mapName, inheritability, access, options, capacity); } /// <summary> /// Used by the OpenExisting factory method group and by CreateOrOpen if access is write. /// We'll throw an ArgumentException if the file mapping object didn't exist and the /// caller used CreateOrOpen since Create isn't valid with Write access /// </summary> [SecurityCritical] private static SafeMemoryMappedFileHandle OpenCore( string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, bool createOrOpen) { throw CreateNamedMapsNotSupportedException(); } /// <summary> /// Used by the OpenExisting factory method group and by CreateOrOpen if access is write. /// We'll throw an ArgumentException if the file mapping object didn't exist and the /// caller used CreateOrOpen since Create isn't valid with Write access /// </summary> [SecurityCritical] private static SafeMemoryMappedFileHandle OpenCore( string mapName, HandleInheritability inheritability, MemoryMappedFileRights rights, bool createOrOpen) { throw CreateNamedMapsNotSupportedException(); } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- /// <summary>Gets an exception indicating that named maps are not supported on this platform.</summary> private static Exception CreateNamedMapsNotSupportedException() { return new PlatformNotSupportedException(SR.PlatformNotSupported_NamedMaps); } private static FileAccess TranslateProtectionsToFileAccess(Interop.Sys.MemoryMappedProtections protections) { return (protections & (Interop.Sys.MemoryMappedProtections.PROT_READ | Interop.Sys.MemoryMappedProtections.PROT_WRITE)) != 0 ? FileAccess.ReadWrite : (protections & (Interop.Sys.MemoryMappedProtections.PROT_WRITE)) != 0 ? FileAccess.Write : FileAccess.Read; } private static FileStream CreateSharedBackingObject(Interop.Sys.MemoryMappedProtections protections, long capacity) { return CreateSharedBackingObjectUsingMemory(protections, capacity) ?? CreateSharedBackingObjectUsingFile(protections, capacity); } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- private static FileStream CreateSharedBackingObjectUsingMemory( Interop.Sys.MemoryMappedProtections protections, long capacity) { // The POSIX shared memory object name must begin with '/'. After that we just want something short and unique. string mapName = "/corefx_map_" + Guid.NewGuid().ToString("N"); // Determine the flags to use when creating the shared memory object Interop.Sys.OpenFlags flags = (protections & Interop.Sys.MemoryMappedProtections.PROT_WRITE) != 0 ? Interop.Sys.OpenFlags.O_RDWR : Interop.Sys.OpenFlags.O_RDONLY; flags |= Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_EXCL; // CreateNew // Determine the permissions with which to create the file Interop.Sys.Permissions perms = default(Interop.Sys.Permissions); if ((protections & Interop.Sys.MemoryMappedProtections.PROT_READ) != 0) perms |= Interop.Sys.Permissions.S_IRUSR; if ((protections & Interop.Sys.MemoryMappedProtections.PROT_WRITE) != 0) perms |= Interop.Sys.Permissions.S_IWUSR; if ((protections & Interop.Sys.MemoryMappedProtections.PROT_EXEC) != 0) perms |= Interop.Sys.Permissions.S_IXUSR; // Create the shared memory object. SafeFileHandle fd = Interop.Sys.ShmOpen(mapName, flags, (int)perms); if (fd.IsInvalid) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.ENOTSUP) { // If ShmOpen is not supported, fall back to file backing object. // Note that the System.Native shim will force this failure on platforms where // the result of native shm_open does not work well with our subsequent call // to mmap. return null; } throw Interop.GetExceptionForIoErrno(errorInfo); } try { // Unlink the shared memory object immediatley so that it'll go away once all handles // to it are closed (as with opened then unlinked files, it'll remain usable via // the open handles even though it's unlinked and can't be opened anew via its name). Interop.CheckIo(Interop.Sys.ShmUnlink(mapName)); // Give it the right capacity. We do this directly with ftruncate rather // than via FileStream.SetLength after the FileStream is created because, on some systems, // lseek fails on shared memory objects, causing the FileStream to think it's unseekable, // causing it to preemptively throw from SetLength. Interop.CheckIo(Interop.Sys.FTruncate(fd, capacity)); // Wrap the file descriptor in a stream and return it. return new FileStream(fd, TranslateProtectionsToFileAccess(protections)); } catch { fd.Dispose(); throw; } } private static string s_tempMapsDirectory; private static FileStream CreateSharedBackingObjectUsingFile(Interop.Sys.MemoryMappedProtections protections, long capacity) { string tempMapsDirectory = s_tempMapsDirectory ?? (s_tempMapsDirectory = PersistedFiles.GetTempFeatureDirectory("maps")); Directory.CreateDirectory(tempMapsDirectory); string path = Path.Combine(tempMapsDirectory, Guid.NewGuid().ToString("N")); FileAccess access = (protections & (Interop.Sys.MemoryMappedProtections.PROT_READ | Interop.Sys.MemoryMappedProtections.PROT_WRITE)) != 0 ? FileAccess.ReadWrite : (protections & (Interop.Sys.MemoryMappedProtections.PROT_WRITE)) != 0 ? FileAccess.Write : FileAccess.Read; // Create the backing file, then immediately unlink it so that it'll be cleaned up when no longer in use. // Then enlarge it to the requested capacity. const int DefaultBufferSize = 0x1000; var fs = new FileStream(path, FileMode.CreateNew, TranslateProtectionsToFileAccess(protections), FileShare.ReadWrite, DefaultBufferSize); try { Interop.CheckIo(Interop.Sys.Unlink(path)); fs.SetLength(capacity); } catch { fs.Dispose(); throw; } return fs; } } }
// **************************************************************** // Copyright 2007, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** using System; using System.Collections; using NUnit.Framework; namespace NUnit.Core.Tests { /// <summary> /// Summary description for PlatformHelperTests. /// </summary> [TestFixture] public class PlatformDetectionTests { private static readonly PlatformHelper win95Helper = new PlatformHelper( new OSPlatform( PlatformID.Win32Windows , new Version( 4, 0 ) ), new RuntimeFramework( RuntimeType.Net, new Version( 1, 1, 4322, 0 ) ) ); private static readonly PlatformHelper winXPHelper = new PlatformHelper( new OSPlatform( PlatformID.Win32NT , new Version( 5,1 ) ), new RuntimeFramework( RuntimeType.Net, new Version( 1, 1, 4322, 0 ) ) ); private void CheckOSPlatforms( OSPlatform os, string expectedPlatforms ) { CheckPlatforms( new PlatformHelper( os, RuntimeFramework.CurrentFramework ), expectedPlatforms, PlatformHelper.OSPlatforms ); } private void CheckRuntimePlatforms( RuntimeFramework runtimeFramework, string expectedPlatforms ) { CheckPlatforms( new PlatformHelper( OSPlatform.CurrentPlatform, runtimeFramework ), expectedPlatforms, PlatformHelper.RuntimePlatforms + ",NET-1.0,NET-1.1,NET-2.0,NET-3.0,NET-3.5,NET-4.0,MONO-1.0,MONO-2.0,MONO-3.0,MONO-3.5,MONO-4.0" ); } private void CheckPlatforms( PlatformHelper helper, string expectedPlatforms, string checkPlatforms ) { string[] expected = expectedPlatforms.Split( new char[] { ',' } ); string[] check = checkPlatforms.Split( new char[] { ',' } ); foreach( string testPlatform in check ) { bool shouldPass = false; foreach( string platform in expected ) if ( shouldPass = platform.ToLower() == testPlatform.ToLower() ) break; bool didPass = helper.IsPlatformSupported( testPlatform ); if ( shouldPass && !didPass ) Assert.Fail( "Failed to detect {0}", testPlatform ); else if ( didPass && !shouldPass ) Assert.Fail( "False positive on {0}", testPlatform ); else if ( !shouldPass && !didPass ) Assert.AreEqual( "Only supported on " + testPlatform, helper.Reason ); } } [Test] public void DetectWin95() { CheckOSPlatforms( new OSPlatform( PlatformID.Win32Windows, new Version( 4, 0 ) ), "Win95,Win32Windows,Win32,Win" ); } [Test] public void DetectWin98() { CheckOSPlatforms( new OSPlatform( PlatformID.Win32Windows, new Version( 4, 10 ) ), "Win98,Win32Windows,Win32,Win" ); } [Test] public void DetectWinMe() { CheckOSPlatforms( new OSPlatform( PlatformID.Win32Windows, new Version( 4, 90 ) ), "WinMe,Win32Windows,Win32,Win" ); } // WinCE isn't defined in .NET 1.0. [Test, Platform(Exclude="Net-1.0")] public void DetectWinCE() { PlatformID winCE = (PlatformID)Enum.Parse(typeof(PlatformID), "WinCE"); CheckOSPlatforms( new OSPlatform(winCE, new Version(1, 0)), "WinCE,Win32,Win" ); } [Test] public void DetectNT3() { CheckOSPlatforms( new OSPlatform( PlatformID.Win32NT, new Version( 3, 51 ) ), "NT3,Win32NT,Win32,Win" ); } [Test] public void DetectNT4() { CheckOSPlatforms( new OSPlatform( PlatformID.Win32NT, new Version( 4, 0 ) ), "NT4,Win32NT,Win32,Win,Win-4.0" ); } [Test] public void DetectWin2K() { CheckOSPlatforms( new OSPlatform( PlatformID.Win32NT, new Version( 5, 0 ) ), "Win2K,NT5,Win32NT,Win32,Win,Win-5.0" ); } [Test] public void DetectWinXP() { CheckOSPlatforms( new OSPlatform( PlatformID.Win32NT, new Version( 5, 1 ) ), "WinXP,NT5,Win32NT,Win32,Win,Win-5.1" ); } [Test] public void DetectWinXPProfessionalX64() { CheckOSPlatforms( new OSPlatform( PlatformID.Win32NT, new Version( 5, 2 ), OSPlatform.ProductType.WorkStation ), "WinXP,NT5,Win32NT,Win32,Win,Win-5.1" ); } [Test] public void DetectWin2003Server() { CheckOSPlatforms( new OSPlatform(PlatformID.Win32NT, new Version(5, 2), OSPlatform.ProductType.Server), "Win2003Server,NT5,Win32NT,Win32,Win,Win-5.2"); } [Test] public void DetectVista() { CheckOSPlatforms( new OSPlatform(PlatformID.Win32NT, new Version(6, 0), OSPlatform.ProductType.WorkStation), "Vista,NT6,Win32NT,Win32,Win,Win-6.0"); } [Test] public void DetectWin2008ServerOriginal() { CheckOSPlatforms( new OSPlatform(PlatformID.Win32NT, new Version(6, 0), OSPlatform.ProductType.Server), "Win2008Server,NT6,Win32NT,Win32,Win,Win-6.0"); } [Test] public void DetectWin2008ServerR2() { CheckOSPlatforms( new OSPlatform(PlatformID.Win32NT, new Version(6, 1), OSPlatform.ProductType.Server), "Win2008Server,Win2008ServerR2,NT6,Win32NT,Win32,Win,Win-6.1"); } [Test] public void DetectWindows7() { CheckOSPlatforms( new OSPlatform(PlatformID.Win32NT, new Version(6, 1), OSPlatform.ProductType.WorkStation), "Windows7,NT6,Win32NT,Win32,Win,Win-6.1"); } [Test] public void DetectUnixUnderMicrosoftDotNet() { CheckOSPlatforms( new OSPlatform(OSPlatform.UnixPlatformID_Microsoft, new Version()), "UNIX,Linux"); } // This throws under Microsoft .Net due to the invlaid enumeration value of 128 [Test, Platform(Exclude="Net")] public void DetectUnixUnderMono() { CheckOSPlatforms( new OSPlatform(OSPlatform.UnixPlatformID_Mono, new Version()), "UNIX,Linux"); } [Test] public void DetectNet10() { CheckRuntimePlatforms( new RuntimeFramework( RuntimeType.Net, new Version( 1, 0, 3705, 0 ) ), "NET,NET-1.0" ); } [Test] public void DetectNet11() { CheckRuntimePlatforms( new RuntimeFramework( RuntimeType.Net, new Version( 1, 1, 4322, 0 ) ), "NET,NET-1.1" ); } [Test] public void DetectNet20() { CheckRuntimePlatforms( new RuntimeFramework(RuntimeType.Net, new Version(2, 0, 50727, 0)), "Net,Net-2.0"); } [Test] public void DetectNet30() { CheckRuntimePlatforms( new RuntimeFramework(RuntimeType.Net, new Version(3, 0)), "Net,Net-2.0,Net-3.0"); } [Test] public void DetectNet35() { CheckRuntimePlatforms( new RuntimeFramework(RuntimeType.Net, new Version(3, 5)), "Net,Net-2.0,Net-3.0,Net-3.5"); } [Test] public void DetectNet40() { CheckRuntimePlatforms( new RuntimeFramework(RuntimeType.Net, new Version(4, 0, 30319, 0)), "Net,Net-4.0"); } [Test] public void DetectNetCF() { CheckRuntimePlatforms( new RuntimeFramework( RuntimeType.NetCF, new Version( 1, 1, 4322, 0 ) ), "NetCF" ); } [Test] public void DetectSSCLI() { CheckRuntimePlatforms( new RuntimeFramework( RuntimeType.SSCLI, new Version( 1, 0, 3, 0 ) ), "SSCLI,Rotor" ); } [Test] public void DetectMono10() { CheckRuntimePlatforms( new RuntimeFramework( RuntimeType.Mono, new Version( 1, 1, 4322, 0 ) ), "Mono,Mono-1.0" ); } [Test] public void DetectMono20() { CheckRuntimePlatforms( new RuntimeFramework(RuntimeType.Mono, new Version(2, 0, 50727, 0)), "Mono,Mono-2.0"); } [Test] public void DetectMono30() { CheckRuntimePlatforms( new RuntimeFramework(RuntimeType.Mono, new Version(3, 0)), "Mono,Mono-2.0,Mono-3.0"); } [Test] public void DetectMono35() { CheckRuntimePlatforms( new RuntimeFramework(RuntimeType.Mono, new Version(3, 5)), "Mono,Mono-2.0,Mono-3.0,Mono-3.5"); } [Test] public void DetectMono40() { CheckRuntimePlatforms( new RuntimeFramework(RuntimeType.Mono, new Version(4, 0, 30319)), "Mono,Mono-4.0"); } [Test] public void DetectExactVersion() { Assert.IsTrue( winXPHelper.IsPlatformSupported( "net-1.1.4322" ) ); Assert.IsTrue( winXPHelper.IsPlatformSupported( "net-1.1.4322.0" ) ); Assert.IsFalse( winXPHelper.IsPlatformSupported( "net-1.1.4323.0" ) ); Assert.IsFalse( winXPHelper.IsPlatformSupported( "net-1.1.4322.1" ) ); } [Test] public void ArrayOfPlatforms() { string[] platforms = new string[] { "NT4", "Win2K", "WinXP" }; Assert.IsTrue( winXPHelper.IsPlatformSupported( platforms ) ); Assert.IsFalse( win95Helper.IsPlatformSupported( platforms ) ); } [Test] public void PlatformAttribute_Include() { PlatformAttribute attr = new PlatformAttribute( "Win2K,WinXP,NT4" ); Assert.IsTrue( winXPHelper.IsPlatformSupported( attr ) ); Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) ); Assert.AreEqual("Only supported on Win2K,WinXP,NT4", win95Helper.Reason); } [Test] public void PlatformAttribute_Exclude() { PlatformAttribute attr = new PlatformAttribute(); attr.Exclude = "Win2K,WinXP,NT4"; Assert.IsFalse( winXPHelper.IsPlatformSupported( attr ) ); Assert.AreEqual( "Not supported on Win2K,WinXP,NT4", winXPHelper.Reason ); Assert.IsTrue( win95Helper.IsPlatformSupported( attr ) ); } [Test] public void PlatformAttribute_IncludeAndExclude() { PlatformAttribute attr = new PlatformAttribute( "Win2K,WinXP,NT4" ); attr.Exclude = "Mono"; Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) ); Assert.AreEqual( "Only supported on Win2K,WinXP,NT4", win95Helper.Reason ); Assert.IsTrue( winXPHelper.IsPlatformSupported( attr ) ); attr.Exclude = "Net"; Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) ); Assert.AreEqual( "Only supported on Win2K,WinXP,NT4", win95Helper.Reason ); Assert.IsFalse( winXPHelper.IsPlatformSupported( attr ) ); Assert.AreEqual( "Not supported on Net", winXPHelper.Reason ); } [Test] public void PlatformAttribute_InvalidPlatform() { PlatformAttribute attr = new PlatformAttribute( "Net-1.0,Net11,Mono" ); Assert.IsFalse( winXPHelper.IsPlatformSupported( attr ) ); Assert.AreEqual( "Invalid platform name: Net11", winXPHelper.Reason ); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Billing.Budgets.V1Beta1.Snippets { using Google.Api.Gax; using Google.Api.Gax.ResourceNames; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedBudgetServiceClientSnippets { /// <summary>Snippet for CreateBudget</summary> public void CreateBudgetRequestObject() { // Snippet: CreateBudget(CreateBudgetRequest, CallSettings) // Create client BudgetServiceClient budgetServiceClient = BudgetServiceClient.Create(); // Initialize request argument(s) CreateBudgetRequest request = new CreateBudgetRequest { ParentAsBillingAccountName = BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"), Budget = new Budget(), }; // Make the request Budget response = budgetServiceClient.CreateBudget(request); // End snippet } /// <summary>Snippet for CreateBudgetAsync</summary> public async Task CreateBudgetRequestObjectAsync() { // Snippet: CreateBudgetAsync(CreateBudgetRequest, CallSettings) // Additional: CreateBudgetAsync(CreateBudgetRequest, CancellationToken) // Create client BudgetServiceClient budgetServiceClient = await BudgetServiceClient.CreateAsync(); // Initialize request argument(s) CreateBudgetRequest request = new CreateBudgetRequest { ParentAsBillingAccountName = BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"), Budget = new Budget(), }; // Make the request Budget response = await budgetServiceClient.CreateBudgetAsync(request); // End snippet } /// <summary>Snippet for UpdateBudget</summary> public void UpdateBudgetRequestObject() { // Snippet: UpdateBudget(UpdateBudgetRequest, CallSettings) // Create client BudgetServiceClient budgetServiceClient = BudgetServiceClient.Create(); // Initialize request argument(s) UpdateBudgetRequest request = new UpdateBudgetRequest { Budget = new Budget(), UpdateMask = new FieldMask(), }; // Make the request Budget response = budgetServiceClient.UpdateBudget(request); // End snippet } /// <summary>Snippet for UpdateBudgetAsync</summary> public async Task UpdateBudgetRequestObjectAsync() { // Snippet: UpdateBudgetAsync(UpdateBudgetRequest, CallSettings) // Additional: UpdateBudgetAsync(UpdateBudgetRequest, CancellationToken) // Create client BudgetServiceClient budgetServiceClient = await BudgetServiceClient.CreateAsync(); // Initialize request argument(s) UpdateBudgetRequest request = new UpdateBudgetRequest { Budget = new Budget(), UpdateMask = new FieldMask(), }; // Make the request Budget response = await budgetServiceClient.UpdateBudgetAsync(request); // End snippet } /// <summary>Snippet for GetBudget</summary> public void GetBudgetRequestObject() { // Snippet: GetBudget(GetBudgetRequest, CallSettings) // Create client BudgetServiceClient budgetServiceClient = BudgetServiceClient.Create(); // Initialize request argument(s) GetBudgetRequest request = new GetBudgetRequest { BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"), }; // Make the request Budget response = budgetServiceClient.GetBudget(request); // End snippet } /// <summary>Snippet for GetBudgetAsync</summary> public async Task GetBudgetRequestObjectAsync() { // Snippet: GetBudgetAsync(GetBudgetRequest, CallSettings) // Additional: GetBudgetAsync(GetBudgetRequest, CancellationToken) // Create client BudgetServiceClient budgetServiceClient = await BudgetServiceClient.CreateAsync(); // Initialize request argument(s) GetBudgetRequest request = new GetBudgetRequest { BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"), }; // Make the request Budget response = await budgetServiceClient.GetBudgetAsync(request); // End snippet } /// <summary>Snippet for ListBudgets</summary> public void ListBudgetsRequestObject() { // Snippet: ListBudgets(ListBudgetsRequest, CallSettings) // Create client BudgetServiceClient budgetServiceClient = BudgetServiceClient.Create(); // Initialize request argument(s) ListBudgetsRequest request = new ListBudgetsRequest { ParentAsBillingAccountName = BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"), }; // Make the request PagedEnumerable<ListBudgetsResponse, Budget> response = budgetServiceClient.ListBudgets(request); // Iterate over all response items, lazily performing RPCs as required foreach (Budget item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListBudgetsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Budget item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Budget> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Budget item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListBudgetsAsync</summary> public async Task ListBudgetsRequestObjectAsync() { // Snippet: ListBudgetsAsync(ListBudgetsRequest, CallSettings) // Create client BudgetServiceClient budgetServiceClient = await BudgetServiceClient.CreateAsync(); // Initialize request argument(s) ListBudgetsRequest request = new ListBudgetsRequest { ParentAsBillingAccountName = BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"), }; // Make the request PagedAsyncEnumerable<ListBudgetsResponse, Budget> response = budgetServiceClient.ListBudgetsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Budget item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListBudgetsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Budget item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Budget> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Budget item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for DeleteBudget</summary> public void DeleteBudgetRequestObject() { // Snippet: DeleteBudget(DeleteBudgetRequest, CallSettings) // Create client BudgetServiceClient budgetServiceClient = BudgetServiceClient.Create(); // Initialize request argument(s) DeleteBudgetRequest request = new DeleteBudgetRequest { BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"), }; // Make the request budgetServiceClient.DeleteBudget(request); // End snippet } /// <summary>Snippet for DeleteBudgetAsync</summary> public async Task DeleteBudgetRequestObjectAsync() { // Snippet: DeleteBudgetAsync(DeleteBudgetRequest, CallSettings) // Additional: DeleteBudgetAsync(DeleteBudgetRequest, CancellationToken) // Create client BudgetServiceClient budgetServiceClient = await BudgetServiceClient.CreateAsync(); // Initialize request argument(s) DeleteBudgetRequest request = new DeleteBudgetRequest { BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"), }; // Make the request await budgetServiceClient.DeleteBudgetAsync(request); // End snippet } } }
using System; using NUnit.Framework; using Braintree; using Braintree.Exceptions; namespace Braintree.Tests { [TestFixture] public class SubscriptionSearchRequestTest { [Test] [Category("Unit")] public void ToXml_BillingCyclesRemainingIs() { SubscriptionSearchRequest request = new SubscriptionSearchRequest().BillingCyclesRemaining.Is(1); var xml = "<search><billing-cycles-remaining><is>1</is></billing-cycles-remaining></search>"; Assert.AreEqual(xml, request.ToXml()); } [Test] [Category("Unit")] public void ToXml_BillingCyclesRemainingBetween() { SubscriptionSearchRequest request = new SubscriptionSearchRequest().BillingCyclesRemaining.Between(1, 2); var xml = "<search><billing-cycles-remaining><min>1</min><max>2</max></billing-cycles-remaining></search>"; Assert.AreEqual(xml, request.ToXml()); } [Test] [Category("Unit")] public void ToXml_BillingCyclesRemainingGreaterThanOrEqualTo() { SubscriptionSearchRequest request = new SubscriptionSearchRequest().BillingCyclesRemaining.GreaterThanOrEqualTo(12.34); var xml = "<search><billing-cycles-remaining><min>12.34</min></billing-cycles-remaining></search>"; Assert.AreEqual(xml, request.ToXml()); } [Test] [Category("Unit")] public void ToXml_BillingCyclesRemainingLessThanOrEqualTo() { SubscriptionSearchRequest request = new SubscriptionSearchRequest().BillingCyclesRemaining.LessThanOrEqualTo(12.34); var xml = "<search><billing-cycles-remaining><max>12.34</max></billing-cycles-remaining></search>"; Assert.AreEqual(xml, request.ToXml()); } [Test] [Category("Unit")] public void ToXml_IdIs() { SubscriptionSearchRequest request = new SubscriptionSearchRequest().Id.Is("30"); var xml = "<search><id><is>30</is></id></search>"; Assert.AreEqual(xml, request.ToXml()); } [Test] [Category("Unit")] public void ToXml_IdIsNot() { SubscriptionSearchRequest request = new SubscriptionSearchRequest().Id.IsNot("30"); var xml = "<search><id><is-not>30</is-not></id></search>"; Assert.AreEqual(xml, request.ToXml()); } [Test] [Category("Unit")] public void ToXml_IdStartsWith() { SubscriptionSearchRequest request = new SubscriptionSearchRequest().Id.StartsWith("30"); var xml = "<search><id><starts-with>30</starts-with></id></search>"; Assert.AreEqual(xml, request.ToXml()); } [Test] [Category("Unit")] public void ToXml_IdEndsWith() { SubscriptionSearchRequest request = new SubscriptionSearchRequest().Id.EndsWith("30"); var xml = "<search><id><ends-with>30</ends-with></id></search>"; Assert.AreEqual(xml, request.ToXml()); } [Test] [Category("Unit")] public void ToXml_IdContains() { SubscriptionSearchRequest request = new SubscriptionSearchRequest().Id.Contains("30"); var xml = "<search><id><contains>30</contains></id></search>"; Assert.AreEqual(xml, request.ToXml()); } [Test] [Category("Unit")] public void ToXml_MerchantAccountIdIncludedIn() { SubscriptionSearchRequest request = new SubscriptionSearchRequest().MerchantAccountId.IncludedIn("abc", "def"); var xml = "<search><merchant-account-id type=\"array\"><item>abc</item><item>def</item></merchant-account-id></search>"; Assert.AreEqual(xml, request.ToXml()); } [Test] [Category("Unit")] public void ToXml_MerchantAccountIdIncludedInWithExplicitArray() { SubscriptionSearchRequest request = new SubscriptionSearchRequest().MerchantAccountId.IncludedIn(new string[] {"abc", "def"}); var xml = "<search><merchant-account-id type=\"array\"><item>abc</item><item>def</item></merchant-account-id></search>"; Assert.AreEqual(xml, request.ToXml()); } [Test] [Category("Unit")] public void ToXml_MerchantAccountIdIs() { SubscriptionSearchRequest request = new SubscriptionSearchRequest().MerchantAccountId.Is("abc"); var xml = "<search><merchant-account-id type=\"array\"><item>abc</item></merchant-account-id></search>"; Assert.AreEqual(xml, request.ToXml()); } [Test] [Category("Unit")] public void ToXml_PlanIdIs() { SubscriptionSearchRequest request = new SubscriptionSearchRequest().PlanId.Is("abc"); var xml = "<search><plan-id><is>abc</is></plan-id></search>"; Assert.AreEqual(xml, request.ToXml()); } [Test] [Category("Unit")] public void ToXml_PlanIdIsNot() { SubscriptionSearchRequest request = new SubscriptionSearchRequest().PlanId.IsNot("30"); var xml = "<search><plan-id><is-not>30</is-not></plan-id></search>"; Assert.AreEqual(xml, request.ToXml()); } [Test] [Category("Unit")] public void ToXml_PlanIdStartsWith() { SubscriptionSearchRequest request = new SubscriptionSearchRequest().PlanId.StartsWith("30"); var xml = "<search><plan-id><starts-with>30</starts-with></plan-id></search>"; Assert.AreEqual(xml, request.ToXml()); } [Test] [Category("Unit")] public void ToXml_PlanIdEndsWith() { SubscriptionSearchRequest request = new SubscriptionSearchRequest().PlanId.EndsWith("30"); var xml = "<search><plan-id><ends-with>30</ends-with></plan-id></search>"; Assert.AreEqual(xml, request.ToXml()); } [Test] [Category("Unit")] public void ToXml_PlanIdContains() { SubscriptionSearchRequest request = new SubscriptionSearchRequest().PlanId.Contains("30"); var xml = "<search><plan-id><contains>30</contains></plan-id></search>"; Assert.AreEqual(xml, request.ToXml()); } [Test] [Category("Unit")] public void ToXml_PlanIdIncludedIn() { SubscriptionSearchRequest request = new SubscriptionSearchRequest().PlanId.IncludedIn("abc", "def"); var xml = "<search><plan-id type=\"array\"><item>abc</item><item>def</item></plan-id></search>"; Assert.AreEqual(xml, request.ToXml()); } [Test] [Category("Unit")] public void ToXml_DaysPastDueIs() { SubscriptionSearchRequest request = new SubscriptionSearchRequest().DaysPastDue.Is("30"); var xml = "<search><days-past-due><is>30</is></days-past-due></search>"; Assert.AreEqual(xml, request.ToXml()); } [Test] [Category("Unit")] public void ToXml_DaysPastDueBetween() { SubscriptionSearchRequest request = new SubscriptionSearchRequest().DaysPastDue.Between(2, 3); var xml = "<search><days-past-due><min>2</min><max>3</max></days-past-due></search>"; Assert.AreEqual(xml, request.ToXml()); } [Test] [Category("Unit")] public void ToXml_DaysPastDueGreaterThanOrEqualTo() { SubscriptionSearchRequest request = new SubscriptionSearchRequest().DaysPastDue.GreaterThanOrEqualTo(3); var xml = "<search><days-past-due><min>3</min></days-past-due></search>"; Assert.AreEqual(xml, request.ToXml()); } [Test] [Category("Unit")] public void ToXml_DaysPastDueLessThanOrEqualTo() { SubscriptionSearchRequest request = new SubscriptionSearchRequest().DaysPastDue.LessThanOrEqualTo(4); var xml = "<search><days-past-due><max>4</max></days-past-due></search>"; Assert.AreEqual(xml, request.ToXml()); } [Test] [Category("Unit")] public void ToXml_PriceIs() { SubscriptionSearchRequest request = new SubscriptionSearchRequest().Price.Is(1M); var xml = "<search><price><is>1</is></price></search>"; Assert.AreEqual(xml, request.ToXml()); } [Test] [Category("Unit")] public void ToXml_PriceBetween() { SubscriptionSearchRequest request = new SubscriptionSearchRequest().Price.Between(1M, 2M); var xml = "<search><price><min>1</min><max>2</max></price></search>"; Assert.AreEqual(xml, request.ToXml()); } [Test] [Category("Unit")] public void ToXml_PriceGreaterThanOrEqualTo() { SubscriptionSearchRequest request = new SubscriptionSearchRequest().Price.GreaterThanOrEqualTo(12.34M); var xml = "<search><price><min>12.34</min></price></search>"; Assert.AreEqual(xml, request.ToXml()); } [Test] [Category("Unit")] public void ToXml_PriceLessThanOrEqualTo() { SubscriptionSearchRequest request = new SubscriptionSearchRequest().Price.LessThanOrEqualTo(12.34M); var xml = "<search><price><max>12.34</max></price></search>"; Assert.AreEqual(xml, request.ToXml()); } } }
/******************************************************************************* * Copyright 2008-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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET * API Version: 2012-11-05 */ using System; using System.Xml.Serialization; using System.Collections.Generic; using System.Net; using System.Runtime.Serialization; using System.Security.Permissions; using Amazon.SQS.Model; namespace Amazon.SQS { /// <summary> /// Amazon SQS Exception provides details of errors /// returned by Amazon SQS service /// </summary> [Serializable] public class AmazonSQSException : Exception, ISerializable { private string message = null; private HttpStatusCode statusCode = default(HttpStatusCode); private string errorCode = null; private string errorType = null; private string requestId = null; private string xml = null; /// <summary> /// Initializes a new AmazonSQSException with default values. /// </summary> public AmazonSQSException() : base() { } /// <summary> /// Initializes a new AmazonSQSException with a specified /// error message /// </summary> /// <param name="message">A message that describes the error</param> public AmazonSQSException(string message) { this.message = message; } /// <summary> /// Initializes a new AmazonSQSException with a specified error message /// and HTTP status code /// </summary> /// <param name="message">A message that describes the error</param> /// <param name="statusCode">HTTP status code for error response</param> public AmazonSQSException(string message, HttpStatusCode statusCode) : this (message) { this.statusCode = statusCode; } /// <summary> /// Initializes a new AmazonSQSException from the inner exception that is /// the cause of this exception. /// </summary> /// <param name="innerException">The nested exception that caused the AmazonSQSException</param> public AmazonSQSException(Exception innerException) : this(innerException.Message, innerException) { } /// <summary> /// Initializes a new AmazonSQSException with serialized data. /// </summary> /// <param name="info">The object that holds the serialized object data. /// </param> /// <param name="context">The contextual information about the source or destination. /// </param> protected AmazonSQSException(SerializationInfo info, StreamingContext context) : base(info, context) { this.message = info.GetString("message"); this.statusCode = (HttpStatusCode)info.GetValue("statusCode", typeof(HttpStatusCode)); this.errorCode = info.GetString("errorCode"); this.errorType = info.GetString("errorType");; this.requestId = info.GetString("requestId"); this.xml = info.GetString("xml"); } /// <summary> /// Serializes this instance of AmazonSQSException. /// </summary> /// <param name="info">The object that holds the serialized object data.</param> /// <param name="context">The contextual information about the source or destination. /// </param> [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("message", message, typeof(string)); info.AddValue("statusCode", statusCode, typeof(HttpStatusCode)); info.AddValue("errorCode", errorCode, typeof(string)); info.AddValue("errorType", errorType, typeof(string)); info.AddValue("requestId", requestId, typeof(string)); info.AddValue("xml", xml, typeof(string)); base.GetObjectData(info, context); } /// <summary> /// Initializes a new AmazonSQSException with a specified error message /// and HTTP status code /// </summary> /// <param name="message">A message that describes the error</param> /// <param name="statusCode">HTTP status code for error response</param> /// <param name="innerException">The nested exception that caused the AmazonSQSException</param> public AmazonSQSException(string message, HttpStatusCode statusCode, Exception innerException) : this(message, innerException) { this.statusCode = statusCode; } /// <summary> /// Constructs AmazonSQSException with message and wrapped exception /// </summary> /// <param name="message">A message that describes the error</param> /// <param name="innerException">The nested exception that caused the AmazonSQSException</param> public AmazonSQSException(string message, Exception innerException) : base (message, innerException) { this.message = message; AmazonSQSException ex = innerException as AmazonSQSException; if (ex != null) { this.statusCode = ex.StatusCode; this.errorCode = ex.ErrorCode; this.errorType = ex.ErrorType; this.requestId = ex.RequestId; this.xml = ex.XML; } } /// <summary> /// Initializes an AmazonSQSException with error information provided in an /// AmazonSQS response. /// </summary> /// <param name="message">A message that describes the error</param> /// <param name="statusCode">HTTP status code for error response</param> /// <param name="errorCode">Error Code returned by the service</param> /// <param name="errorType">Error type. Possible types: Sender, Receiver or Unknown</param> /// <param name="requestId">Request ID returned by the service</param> /// <param name="xml">Compete xml found in response</param> public AmazonSQSException(string message, HttpStatusCode statusCode, string errorCode, string errorType, string requestId, string xml) : this (message, statusCode) { this.errorCode = errorCode; this.errorType = errorType; this.requestId = requestId; this.xml = xml; } /// <summary> /// Gets and sets of the ErrorCode property. /// </summary> public string ErrorCode { get { return this.errorCode; } } /// <summary> /// Gets and sets of the ErrorType property. /// </summary> public string ErrorType { get { return this.errorType; } } /// <summary> /// Gets error message /// </summary> public override string Message { get { return this.message; } } /// <summary> /// Gets status code returned by the service if available. If status /// code is set to -1, it means that status code was unavailable at the /// time exception was thrown /// </summary> public HttpStatusCode StatusCode { get { return this.statusCode; } } /// <summary> /// Gets XML returned by the service if available. /// </summary> public string XML { get { return this.xml; } } /// <summary> /// Gets Request ID returned by the service if available. /// </summary> public string RequestId { get { return this.requestId; } } } }
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\CheatManager.h:69 namespace UnrealEngine { public partial class UCheatManager : UObject { public UCheatManager(IntPtr adress) : base(adress) { } public UCheatManager(UObject Parent = null, string Name = "CheatManager") : base(IntPtr.Zero) { NativePointer = E_NewObject_UCheatManager(Parent, Name); NativeManager.AddNativeWrapper(NativePointer, this); } [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_PROP_UCheatManager_bDebugCapsuleSweepPawn_GET(); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern int E_PROP_UCheatManager_CurrentTraceIndex_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UCheatManager_CurrentTraceIndex_SET(IntPtr Ptr, int Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern int E_PROP_UCheatManager_CurrentTracePawnIndex_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UCheatManager_CurrentTracePawnIndex_SET(IntPtr Ptr, int Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_UCheatManager_DebugCapsuleHalfHeight_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UCheatManager_DebugCapsuleHalfHeight_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_UCheatManager_DebugCapsuleRadius_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UCheatManager_DebugCapsuleRadius_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_UCheatManager_DebugTraceDistance_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UCheatManager_DebugTraceDistance_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_UCheatManager_DebugTraceDrawNormalLength_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UCheatManager_DebugTraceDrawNormalLength_SET(IntPtr Ptr, float Value); #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_NewObject_UCheatManager(IntPtr Parent, string Name); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_AddCapsuleSweepDebugInfo(IntPtr self, IntPtr lineTraceStart, IntPtr lineTraceEnd, IntPtr hitImpactLocation, IntPtr hitNormal, IntPtr hitImpactNormal, IntPtr hitLocation, float capsuleHalfheight, float capsuleRadius, bool bTracePawn, bool bInsideOfObject); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_BugIt(IntPtr self, string screenShotDescription); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_BugItGo(IntPtr self, float x, float y, float z, float pitch, float yaw, float roll); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_BugItGoString(IntPtr self, string theLocation, string theRotation); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_BugItStringCreator(IntPtr self, IntPtr viewLocation, IntPtr viewRotation, string goString, string locString); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_BugItWorker(IntPtr self, IntPtr theLocation, IntPtr theRotation); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_ChangeSize(IntPtr self, float f); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_CheatScript(IntPtr self, string scriptName); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_DamageTarget(IntPtr self, float damageAmount); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_DebugCapsuleSweep(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_DebugCapsuleSweepCapture(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_DebugCapsuleSweepChannel(IntPtr self, byte channel); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_DebugCapsuleSweepClear(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_DebugCapsuleSweepComplex(IntPtr self, bool bTraceComplex); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_DebugCapsuleSweepPawn(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_DebugCapsuleSweepSize(IntPtr self, float halfHeight, float radius); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_DestroyAllPawnsExceptTarget(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_DestroyServerStatReplicator(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_DestroyTarget(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_DisableDebugCamera(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_DumpChatState(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_DumpOnlineSessionState(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_DumpPartyState(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_DumpVoiceMutingState(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_EnableDebugCamera(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_FlushLog(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_Fly(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_FreezeFrame(IntPtr self, float delay); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern ObjectPointerDescription E_UCheatManager_GetTarget(IntPtr self, IntPtr playerController, IntPtr outHit); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_Ghost(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_God(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_InitCheatManager(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_InvertMouse(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UCheatManager_IsDebugCapsuleSweepPawnEnabled(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_LogLoc(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_LogOutBugItGoToLogFile(IntPtr self, string inScreenShotDesc, string inScreenShotPath, string inGoString, string inLocString); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_OnlyLoadLevel(IntPtr self, string packageName); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_PlayersOnly(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_ReceiveEndPlay(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_ReceiveInitCheatManager(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_ServerToggleAILogging(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_SetLevelStreamingStatus(IntPtr self, string packageName, bool bShouldBeLoaded, bool bShouldBeVisible); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_SetMouseSensitivityToDefault(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_SetWorldOrigin(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_Slomo(IntPtr self, float newTimeDilation); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_SpawnServerStatReplicator(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_StreamLevelIn(IntPtr self, string packageName); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_StreamLevelOut(IntPtr self, string packageName); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_Summon(IntPtr self, string className); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_Teleport(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_TestCollisionDistance(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_TickCollisionDebug(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_ToggleAILogging(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_ToggleDebugCamera(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_ToggleServerStatReplicatorClientOverwrite(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_ToggleServerStatReplicatorUpdateStatNet(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_UpdateSafeArea(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_ViewActor(IntPtr self, string actorName); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_ViewPlayer(IntPtr self, string s); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_ViewSelf(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UCheatManager_Walk(IntPtr self); #endregion #region Property /// <summary> /// If we should should perform a debug capsule trace for pawns and draw results. Toggled with DebugCapsuleSweepPawn() /// </summary> public static bool bDebugCapsuleSweepPawn { get => E_PROP_UCheatManager_bDebugCapsuleSweepPawn_GET(); } /// <summary> /// Index of the array for current trace to overwrite. Whenever you capture, this index will be increased /// </summary> public int CurrentTraceIndex { get => E_PROP_UCheatManager_CurrentTraceIndex_GET(NativePointer); set => E_PROP_UCheatManager_CurrentTraceIndex_SET(NativePointer, value); } /// <summary> /// Index of the array for current trace to overwrite. Whenever you capture, this index will be increased /// </summary> public int CurrentTracePawnIndex { get => E_PROP_UCheatManager_CurrentTracePawnIndex_GET(NativePointer); set => E_PROP_UCheatManager_CurrentTracePawnIndex_SET(NativePointer, value); } /// <summary> /// Half distance between debug capsule sphere ends. Total heigh of capsule is 2*(this + DebugCapsuleRadius). /// </summary> public float DebugCapsuleHalfHeight { get => E_PROP_UCheatManager_DebugCapsuleHalfHeight_GET(NativePointer); set => E_PROP_UCheatManager_DebugCapsuleHalfHeight_SET(NativePointer, value); } /// <summary> /// Radius of debug capsule /// </summary> public float DebugCapsuleRadius { get => E_PROP_UCheatManager_DebugCapsuleRadius_GET(NativePointer); set => E_PROP_UCheatManager_DebugCapsuleRadius_SET(NativePointer, value); } /// <summary> /// How far debug trace should go out from player viewpoint /// </summary> public float DebugTraceDistance { get => E_PROP_UCheatManager_DebugTraceDistance_GET(NativePointer); set => E_PROP_UCheatManager_DebugTraceDistance_SET(NativePointer, value); } /// <summary> /// How long to draw the normal result /// </summary> public float DebugTraceDrawNormalLength { get => E_PROP_UCheatManager_DebugTraceDrawNormalLength_GET(NativePointer); set => E_PROP_UCheatManager_DebugTraceDrawNormalLength_SET(NativePointer, value); } #endregion #region ExternMethods /// <summary> /// Add Debug Trace info into current index - used when DebugCapsuleSweepPawn is on /// </summary> public void AddCapsuleSweepDebugInfo(FVector lineTraceStart, FVector lineTraceEnd, FVector hitImpactLocation, FVector hitNormal, FVector hitImpactNormal, FVector hitLocation, float capsuleHalfheight, float capsuleRadius, bool bTracePawn, bool bInsideOfObject) => E_UCheatManager_AddCapsuleSweepDebugInfo(this, lineTraceStart, lineTraceEnd, hitImpactLocation, hitNormal, hitImpactNormal, hitLocation, capsuleHalfheight, capsuleRadius, bTracePawn, bInsideOfObject); public virtual void BugIt(string screenShotDescription) => E_UCheatManager_BugIt(this, screenShotDescription); public virtual void BugItGo(float x, float y, float z, float pitch, float yaw, float roll) => E_UCheatManager_BugItGo(this, x, y, z, pitch, yaw, roll); /// <summary> /// This will move the player and set their rotation to the passed in values. /// <para>We have this version of the BugIt family strings can be passed in from the game ?options easily </para> /// </summary> public virtual void BugItGoString(string theLocation, string theRotation) => E_UCheatManager_BugItGoString(this, theLocation, theRotation); public virtual void BugItStringCreator(FVector viewLocation, FRotator viewRotation, string goString, string locString) => E_UCheatManager_BugItStringCreator(this, viewLocation, viewRotation, goString, locString); /// <summary> /// This will move the player and set their rotation to the passed in values. /// <para>This actually does the location / rotation setting. Additionally it will set you as ghost as the level may have </para> /// changed since the last time you were here. And the bug may actually be inside of something. /// </summary> public virtual void BugItWorker(FVector theLocation, FRotator theRotation) => E_UCheatManager_BugItWorker(this, theLocation, theRotation); public virtual void ChangeSize(float f) => E_UCheatManager_ChangeSize(this, f); public void CheatScript(string scriptName) => E_UCheatManager_CheatScript(this, scriptName); /// <summary> /// Damage the actor you're looking at (sourced from the player). /// </summary> public virtual void DamageTarget(float damageAmount) => E_UCheatManager_DamageTarget(this, damageAmount); public virtual void DebugCapsuleSweep() => E_UCheatManager_DebugCapsuleSweep(this); public virtual void DebugCapsuleSweepCapture() => E_UCheatManager_DebugCapsuleSweepCapture(this); public virtual void DebugCapsuleSweepChannel(ECollisionChannel channel) => E_UCheatManager_DebugCapsuleSweepChannel(this, (byte)channel); public virtual void DebugCapsuleSweepClear() => E_UCheatManager_DebugCapsuleSweepClear(this); public virtual void DebugCapsuleSweepComplex(bool bTraceComplex) => E_UCheatManager_DebugCapsuleSweepComplex(this, bTraceComplex); public virtual void DebugCapsuleSweepPawn() => E_UCheatManager_DebugCapsuleSweepPawn(this); public virtual void DebugCapsuleSweepSize(float halfHeight, float radius) => E_UCheatManager_DebugCapsuleSweepSize(this, halfHeight, radius); public virtual void DestroyAllPawnsExceptTarget() => E_UCheatManager_DestroyAllPawnsExceptTarget(this); public void DestroyServerStatReplicator() => E_UCheatManager_DestroyServerStatReplicator(this); /// <summary> /// Destroy the actor you're looking at. /// </summary> public virtual void DestroyTarget() => E_UCheatManager_DestroyTarget(this); /// <summary> /// Switch controller from debug camera back to normal controller /// </summary> protected virtual void DisableDebugCamera() => E_UCheatManager_DisableDebugCamera(this); public virtual void DumpChatState() => E_UCheatManager_DumpChatState(this); public virtual void DumpOnlineSessionState() => E_UCheatManager_DumpOnlineSessionState(this); public virtual void DumpPartyState() => E_UCheatManager_DumpPartyState(this); public virtual void DumpVoiceMutingState() => E_UCheatManager_DumpVoiceMutingState(this); /// <summary> /// Switch controller to debug camera without locking gameplay and with locking local player controller input /// </summary> protected virtual void EnableDebugCamera() => E_UCheatManager_EnableDebugCamera(this); public virtual void FlushLog() => E_UCheatManager_FlushLog(this); /// <summary> /// Pawn can fly. /// </summary> public virtual void Fly() => E_UCheatManager_Fly(this); /// <summary> /// Pause the game for Delay seconds. /// </summary> public virtual void FreezeFrame(float delay) => E_UCheatManager_FreezeFrame(this, delay); /// <summary> /// Retrieve the given PlayerContoller's current "target" AActor. /// </summary> protected virtual AActor GetTarget(APlayerController playerController, FHitResult outHit) => E_UCheatManager_GetTarget(this, playerController, outHit); /// <summary> /// Pawn no longer collides with the world, and can fly /// </summary> public virtual void Ghost() => E_UCheatManager_Ghost(this); /// <summary> /// Invulnerability cheat. /// </summary> public virtual void God() => E_UCheatManager_God(this); /// <summary> /// Called when CheatManager is created to allow any needed initialization. /// </summary> public virtual void InitCheatManager() => E_UCheatManager_InitCheatManager(this); public virtual void InvertMouse() => E_UCheatManager_InvertMouse(this); /// <summary> /// Return true if debug sweeps are enabled for pawns. /// </summary> public bool IsDebugCapsuleSweepPawnEnabled() => E_UCheatManager_IsDebugCapsuleSweepPawnEnabled(this); public virtual void LogLoc() => E_UCheatManager_LogLoc(this); /// <summary> /// Bug it log to file /// </summary> public virtual void LogOutBugItGoToLogFile(string inScreenShotDesc, string inScreenShotPath, string inGoString, string inLocString) => E_UCheatManager_LogOutBugItGoToLogFile(this, inScreenShotDesc, inScreenShotPath, inGoString, inLocString); public virtual void OnlyLoadLevel(string packageName) => E_UCheatManager_OnlyLoadLevel(this, packageName); /// <summary> /// Freeze everything in the level except for players. /// </summary> public virtual void PlayersOnly() => E_UCheatManager_PlayersOnly(this); /// <summary> /// This is the End Play event for the CheatManager /// </summary> public void Shutdown() => E_UCheatManager_ReceiveEndPlay(this); /// <summary> /// BP implementable event for when CheatManager is created to allow any needed initialization. /// </summary> public void ReceiveInitCheatManager() => E_UCheatManager_ReceiveInitCheatManager(this); public virtual void ServerToggleAILogging() => E_UCheatManager_ServerToggleAILogging(this); /// <summary> /// streaming level debugging /// </summary> public virtual void SetLevelStreamingStatus(string packageName, bool bShouldBeLoaded, bool bShouldBeVisible) => E_UCheatManager_SetLevelStreamingStatus(this, packageName, bShouldBeLoaded, bShouldBeVisible); public virtual void SetMouseSensitivityToDefault() => E_UCheatManager_SetMouseSensitivityToDefault(this); public void SetWorldOrigin() => E_UCheatManager_SetWorldOrigin(this); /// <summary> /// Modify time dilation to change apparent speed of passage of time. e.g. "Slomo 0.1" makes everything move very slowly, while "Slomo 10" makes everything move very fast. /// </summary> public virtual void Slomo(float newTimeDilation) => E_UCheatManager_Slomo(this, newTimeDilation); public void SpawnServerStatReplicator() => E_UCheatManager_SpawnServerStatReplicator(this); public virtual void StreamLevelIn(string packageName) => E_UCheatManager_StreamLevelIn(this, packageName); public virtual void StreamLevelOut(string packageName) => E_UCheatManager_StreamLevelOut(this, packageName); public virtual void Summon(string className) => E_UCheatManager_Summon(this, className); public virtual void Teleport() => E_UCheatManager_Teleport(this); public virtual void TestCollisionDistance() => E_UCheatManager_TestCollisionDistance(this); /// <summary> /// Do any trace debugging that is currently enabled /// </summary> public void TickCollisionDebug() => E_UCheatManager_TickCollisionDebug(this); public virtual void ToggleAILogging() => E_UCheatManager_ToggleAILogging(this); public virtual void ToggleDebugCamera() => E_UCheatManager_ToggleDebugCamera(this); public void ToggleServerStatReplicatorClientOverwrite() => E_UCheatManager_ToggleServerStatReplicatorClientOverwrite(this); public void ToggleServerStatReplicatorUpdateStatNet() => E_UCheatManager_ToggleServerStatReplicatorUpdateStatNet(this); public void UpdateSafeArea() => E_UCheatManager_UpdateSafeArea(this); public virtual void ViewActor(string actorName) => E_UCheatManager_ViewActor(this, actorName); public virtual void ViewPlayer(string s) => E_UCheatManager_ViewPlayer(this, s); public virtual void ViewSelf() => E_UCheatManager_ViewSelf(this); /// <summary> /// Return to walking movement mode from Fly or Ghost cheat. /// </summary> public virtual void Walk() => E_UCheatManager_Walk(this); #endregion public static implicit operator IntPtr(UCheatManager self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator UCheatManager(ObjectPointerDescription PtrDesc) { return NativeManager.GetWrapper<UCheatManager>(PtrDesc); } } }
// 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.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using osu.Framework.Allocation; using osu.Framework.Audio; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.IO.Stores; using osu.Framework.Platform; using osu.Game.Beatmaps; using osu.Game.Configuration; using osu.Game.Graphics; using osu.Game.Graphics.Cursor; using osu.Game.Online.API; using osu.Framework.Graphics.Performance; using osu.Framework.Graphics.Textures; using osu.Framework.Input; using osu.Framework.Logging; using osu.Game.Audio; using osu.Game.Database; using osu.Game.Graphics.Containers; using osu.Game.Input; using osu.Game.Input.Bindings; using osu.Game.IO; using osu.Game.Rulesets; using osu.Game.Scoring; using osu.Game.Skinning; using osuTK.Input; using DebugUtils = osu.Game.Utils.DebugUtils; namespace osu.Game { /// <summary> /// The most basic <see cref="Game"/> that can be used to host osu! components and systems. /// Unlike <see cref="OsuGame"/>, this class will not load any kind of UI, allowing it to be used /// for provide dependencies to test cases without interfering with them. /// </summary> public class OsuGameBase : Framework.Game, ICanAcceptFiles { protected OsuConfigManager LocalConfig; protected BeatmapManager BeatmapManager; protected ScoreManager ScoreManager; protected SkinManager SkinManager; protected RulesetStore RulesetStore; protected FileStore FileStore; protected KeyBindingStore KeyBindingStore; protected SettingsStore SettingsStore; protected RulesetConfigCache RulesetConfigCache; protected APIAccess API; protected MenuCursorContainer MenuCursorContainer; private Container content; protected override Container<Drawable> Content => content; private Bindable<WorkingBeatmap> beatmap; protected Bindable<WorkingBeatmap> Beatmap => beatmap; private Bindable<bool> fpsDisplayVisible; public virtual Version AssemblyVersion => Assembly.GetEntryAssembly()?.GetName().Version ?? new Version(); public bool IsDeployedBuild => AssemblyVersion.Major > 0; public string Version { get { if (!IsDeployedBuild) return @"local " + (DebugUtils.IsDebug ? @"debug" : @"release"); var version = AssemblyVersion; return $@"{version.Major}.{version.Minor}.{version.Build}"; } } public OsuGameBase() { Name = @"osu!lazer"; } private DependencyContainer dependencies; protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) => dependencies = new DependencyContainer(base.CreateChildDependencies(parent)); private DatabaseContextFactory contextFactory; protected override UserInputManager CreateUserInputManager() => new OsuUserInputManager(); [BackgroundDependencyLoader] private void load() { Resources.AddStore(new DllResourceStore(@"osu.Game.Resources.dll")); dependencies.Cache(contextFactory = new DatabaseContextFactory(Host.Storage)); var largeStore = new LargeTextureStore(Host.CreateTextureLoaderStore(new NamespacedResourceStore<byte[]>(Resources, @"Textures"))); largeStore.AddStore(Host.CreateTextureLoaderStore(new OnlineStore())); dependencies.Cache(largeStore); dependencies.CacheAs(this); dependencies.Cache(LocalConfig); //this completely overrides the framework default. will need to change once we make a proper FontStore. dependencies.Cache(Fonts = new FontStore(new GlyphStore(Resources, @"Fonts/FontAwesome"))); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/osuFont")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Medium")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-MediumItalic")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-Basic")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-Hangul")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-CJK-Basic")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-CJK-Compatibility")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Regular")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-RegularItalic")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-SemiBold")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-SemiBoldItalic")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Bold")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-BoldItalic")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Light")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-LightItalic")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Black")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-BlackItalic")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Venera")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Venera-Light")); runMigrations(); dependencies.Cache(SkinManager = new SkinManager(Host.Storage, contextFactory, Host, Audio)); dependencies.CacheAs<ISkinSource>(SkinManager); API = new APIAccess(LocalConfig); dependencies.Cache(API); dependencies.CacheAs<IAPIProvider>(API); var defaultBeatmap = new DummyWorkingBeatmap(this); dependencies.Cache(RulesetStore = new RulesetStore(contextFactory)); dependencies.Cache(FileStore = new FileStore(contextFactory, Host.Storage)); dependencies.Cache(BeatmapManager = new BeatmapManager(Host.Storage, contextFactory, RulesetStore, API, Audio, Host, defaultBeatmap)); dependencies.Cache(ScoreManager = new ScoreManager(RulesetStore, BeatmapManager, Host.Storage, contextFactory, Host)); dependencies.Cache(KeyBindingStore = new KeyBindingStore(contextFactory, RulesetStore)); dependencies.Cache(SettingsStore = new SettingsStore(contextFactory)); dependencies.Cache(RulesetConfigCache = new RulesetConfigCache(SettingsStore)); dependencies.Cache(new OsuColour()); fileImporters.Add(BeatmapManager); fileImporters.Add(ScoreManager); fileImporters.Add(SkinManager); // tracks play so loud our samples can't keep up. // this adds a global reduction of track volume for the time being. Audio.Track.AddAdjustment(AdjustableProperty.Volume, new BindableDouble(0.8)); beatmap = new OsuBindableBeatmap(defaultBeatmap, Audio); dependencies.CacheAs<IBindable<WorkingBeatmap>>(beatmap); dependencies.CacheAs(beatmap); FileStore.Cleanup(); AddInternal(API); GlobalActionContainer globalBinding; MenuCursorContainer = new MenuCursorContainer { RelativeSizeAxes = Axes.Both }; MenuCursorContainer.Child = globalBinding = new GlobalActionContainer(this) { RelativeSizeAxes = Axes.Both, Child = content = new OsuTooltipContainer(MenuCursorContainer.Cursor) { RelativeSizeAxes = Axes.Both } }; base.Content.Add(new ScalingContainer(ScalingMode.Everything) { Child = MenuCursorContainer }); KeyBindingStore.Register(globalBinding); dependencies.Cache(globalBinding); PreviewTrackManager previewTrackManager; dependencies.Cache(previewTrackManager = new PreviewTrackManager()); Add(previewTrackManager); } protected override void LoadComplete() { base.LoadComplete(); // TODO: This is temporary until we reimplement the local FPS display. // It's just to allow end-users to access the framework FPS display without knowing the shortcut key. fpsDisplayVisible = LocalConfig.GetBindable<bool>(OsuSetting.ShowFpsDisplay); fpsDisplayVisible.ValueChanged += visible => { FrameStatisticsMode = visible.NewValue ? FrameStatisticsMode.Minimal : FrameStatisticsMode.None; }; fpsDisplayVisible.TriggerChange(); } private void runMigrations() { try { using (var db = contextFactory.GetForWrite(false)) db.Context.Migrate(); } catch (Exception e) { Logger.Error(e.InnerException ?? e, "Migration failed! We'll be starting with a fresh database.", LoggingTarget.Database); // if we failed, let's delete the database and start fresh. // todo: we probably want a better (non-destructive) migrations/recovery process at a later point than this. contextFactory.ResetDatabase(); Logger.Log("Database purged successfully.", LoggingTarget.Database); // only run once more, then hard bail. using (var db = contextFactory.GetForWrite(false)) db.Context.Migrate(); } } public override void SetHost(GameHost host) { if (LocalConfig == null) LocalConfig = new OsuConfigManager(host.Storage); base.SetHost(host); } private readonly List<ICanAcceptFiles> fileImporters = new List<ICanAcceptFiles>(); public void Import(params string[] paths) { var extension = Path.GetExtension(paths.First())?.ToLowerInvariant(); foreach (var importer in fileImporters) if (importer.HandledExtensions.Contains(extension)) importer.Import(paths); } public string[] HandledExtensions => fileImporters.SelectMany(i => i.HandledExtensions).ToArray(); private class OsuBindableBeatmap : BindableBeatmap { public OsuBindableBeatmap(WorkingBeatmap defaultValue, AudioManager audioManager) : this(defaultValue) { RegisterAudioManager(audioManager); } public OsuBindableBeatmap(WorkingBeatmap defaultValue) : base(defaultValue) { } public override BindableBeatmap GetBoundCopy() { var copy = new OsuBindableBeatmap(Default); copy.BindTo(this); return copy; } } private class OsuUserInputManager : UserInputManager { protected override MouseButtonEventManager CreateButtonManagerFor(MouseButton button) { switch (button) { case MouseButton.Right: return new RightMouseManager(button); } return base.CreateButtonManagerFor(button); } private class RightMouseManager : MouseButtonEventManager { public RightMouseManager(MouseButton button) : base(button) { } public override bool EnableDrag => true; // allow right-mouse dragging for absolute scroll in scroll containers. public override bool EnableClick => false; public override bool ChangeFocusOnClick => false; } } } }