context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* * Copyright (c) Contributors, http://aurora-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using Aurora.Framework; using Nini.Config; using OpenMetaverse; using OpenMetaverse.Packets; using OpenSim.Region.Framework.Interfaces; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace Aurora.Modules.Search { public class AuroraSearchModule : ISharedRegionModule { #region Declares //private static readonly ILog MainConsole.Instance = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private readonly List<IScene> m_Scenes = new List<IScene>(); private IGroupsModule GroupsModule; private IProfileConnector ProfileFrontend; private IDirectoryServiceConnector directoryService; private bool m_SearchEnabled; #endregion #region Client public void NewClient(IClientAPI client) { // Subscribe to messages client.OnDirPlacesQuery += DirPlacesQuery; client.OnDirFindQuery += DirFindQuery; client.OnDirPopularQuery += DirPopularQuery; client.OnDirLandQuery += DirLandQuery; client.OnDirClassifiedQuery += DirClassifiedQuery; // Response after Directory Queries client.OnEventInfoRequest += EventInfoRequest; client.OnMapItemRequest += HandleMapItemRequest; client.OnPlacesQuery += OnPlacesQueryRequest; client.OnAvatarPickerRequest += ProcessAvatarPickerRequest; } private void OnClosingClient(IClientAPI client) { client.OnDirPlacesQuery -= DirPlacesQuery; client.OnDirFindQuery -= DirFindQuery; client.OnDirPopularQuery -= DirPopularQuery; client.OnDirLandQuery -= DirLandQuery; client.OnDirClassifiedQuery -= DirClassifiedQuery; // Response after Directory Queries client.OnEventInfoRequest -= EventInfoRequest; client.OnMapItemRequest -= HandleMapItemRequest; client.OnPlacesQuery -= OnPlacesQueryRequest; client.OnAvatarPickerRequest -= ProcessAvatarPickerRequest; } #endregion #region Search Module #region Delegates public delegate void SendPacket<T>(T[] data); #endregion /// <summary> /// Parcel request /// </summary> /// <param name = "remoteClient"></param> /// <param name = "queryID"></param> /// <param name = "queryText">The thing to search for</param> /// <param name = "queryFlags"></param> /// <param name = "category"></param> /// <param name = "simName"></param> /// <param name = "queryStart"></param> protected void DirPlacesQuery(IClientAPI remoteClient, UUID queryID, string queryText, int queryFlags, int category, string simName, int queryStart) { List<DirPlacesReplyData> ReturnValues = directoryService.FindLand(queryText, category.ToString(), queryStart, (uint) queryFlags, remoteClient.ScopeID); #if (!ISWIN) SplitPackets<DirPlacesReplyData>(ReturnValues, delegate(DirPlacesReplyData[] data) { remoteClient.SendDirPlacesReply(queryID, data); }); #else SplitPackets(ReturnValues, data => remoteClient.SendDirPlacesReply(queryID, data)); #endif } public void DirPopularQuery(IClientAPI remoteClient, UUID queryID, uint queryFlags) { List<DirPopularReplyData> ReturnValues = directoryService.FindPopularPlaces(queryFlags, remoteClient.ScopeID); remoteClient.SendDirPopularReply(queryID, ReturnValues.ToArray()); } /// <summary> /// Land for sale request /// </summary> /// <param name = "remoteClient"></param> /// <param name = "queryID"></param> /// <param name = "queryFlags"></param> /// <param name = "searchType"></param> /// <param name = "price"></param> /// <param name = "area"></param> /// <param name = "queryStart"></param> public void DirLandQuery(IClientAPI remoteClient, UUID queryID, uint queryFlags, uint searchType, uint price, uint area, int queryStart) { List<DirLandReplyData> ReturnValues = new List<DirLandReplyData>(directoryService.FindLandForSale(searchType.ToString(), price, area, queryStart, queryFlags, remoteClient.ScopeID)); #if (!ISWIN) SplitPackets<DirLandReplyData>(ReturnValues, delegate(DirLandReplyData[] data) { remoteClient.SendDirLandReply(queryID, data); }); #else SplitPackets(ReturnValues, data => remoteClient.SendDirLandReply(queryID, data)); #endif } /// <summary> /// Finds either people or events /// </summary> /// <param name = "remoteClient"></param> /// <param name = "queryID">Just a UUID to send back to the client</param> /// <param name = "queryText">The term to search for</param> /// <param name = "queryFlags">Flags like maturity, etc</param> /// <param name = "queryStart">Where in the search should we start? 0, 10, 20, etc</param> public void DirFindQuery(IClientAPI remoteClient, UUID queryID, string queryText, uint queryFlags, int queryStart) { if ((queryFlags & 1) != 0) //People query { DirPeopleQuery(remoteClient, queryID, queryText, queryFlags, queryStart); return; } else if ((queryFlags & 32) != 0) //Events query { DirEventsQuery(remoteClient, queryID, queryText, queryFlags, queryStart); return; } } //TODO: Flagged to optimize public void DirPeopleQuery(IClientAPI remoteClient, UUID queryID, string queryText, uint queryFlags, int queryStart) { //Find the user accounts List<UserAccount> accounts = m_Scenes[0].UserAccountService.GetUserAccounts(remoteClient.ScopeID, queryText); List<DirPeopleReplyData> ReturnValues = new List<DirPeopleReplyData>(); foreach (UserAccount item in accounts) { //This is really bad, we should not be searching for all of these people again in the Profile service IUserProfileInfo UserProfile = ProfileFrontend.GetUserProfile(item.PrincipalID); if (UserProfile == null) { DirPeopleReplyData person = new DirPeopleReplyData { agentID = item.PrincipalID, firstName = item.FirstName, lastName = item.LastName }; if (GroupsModule == null) person.group = ""; else { person.group = ""; GroupMembershipData[] memberships = GroupsModule.GetMembershipData(item.PrincipalID); #if (!ISWIN) foreach (GroupMembershipData membership in memberships) { if (membership.Active) { person.group = membership.GroupName; } } #else foreach (GroupMembershipData membership in memberships.Where(membership => membership.Active)) { person.group = membership.GroupName; } #endif } //Then we have to pull the GUI to see if the user is online or not UserInfo Pinfo = m_Scenes[0].RequestModuleInterface<IAgentInfoService>().GetUserInfo(item.PrincipalID.ToString()); if (Pinfo != null && Pinfo.IsOnline) //If it is null, they are offline person.online = true; person.reputation = 0; ReturnValues.Add(person); } else if (UserProfile.AllowPublish) //Check whether they want to be in search or not { DirPeopleReplyData person = new DirPeopleReplyData { agentID = item.PrincipalID, firstName = item.FirstName, lastName = item.LastName }; if (GroupsModule == null) person.group = ""; else { person.group = ""; //Check what group they have set GroupMembershipData[] memberships = GroupsModule.GetMembershipData(item.PrincipalID); #if (!ISWIN) foreach (GroupMembershipData membership in memberships) { if (membership.Active) { person.group = membership.GroupName; } } #else foreach (GroupMembershipData membership in memberships.Where(membership => membership.Active)) { person.group = membership.GroupName; } #endif } //Then we have to pull the GUI to see if the user is online or not UserInfo Pinfo = m_Scenes[0].RequestModuleInterface<IAgentInfoService>().GetUserInfo(item.PrincipalID.ToString()); if (Pinfo != null && Pinfo.IsOnline) person.online = true; person.reputation = 0; ReturnValues.Add(person); } } #if (!ISWIN) SplitPackets<DirPeopleReplyData>(ReturnValues, delegate(DirPeopleReplyData[] data) { remoteClient.SendDirPeopleReply(queryID, data); }); #else SplitPackets(ReturnValues, data => remoteClient.SendDirPeopleReply(queryID, data)); #endif } public void DirEventsQuery(IClientAPI remoteClient, UUID queryID, string queryText, uint queryFlags, int queryStart) { List<DirEventsReplyData> ReturnValues = new List<DirEventsReplyData>(directoryService.FindEvents(queryText, queryFlags, queryStart, remoteClient.ScopeID)); #if (!ISWIN) SplitPackets<DirEventsReplyData>(ReturnValues, delegate(DirEventsReplyData[] data) { remoteClient.SendDirEventsReply(queryID, data); }); #else SplitPackets(ReturnValues, data => remoteClient.SendDirEventsReply(queryID, data)); #endif } public void DirClassifiedQuery(IClientAPI remoteClient, UUID queryID, string queryText, uint queryFlags, uint category, int queryStart) { List<DirClassifiedReplyData> ReturnValues = new List<DirClassifiedReplyData>(directoryService.FindClassifieds(queryText, category.ToString(), queryFlags, queryStart, remoteClient.ScopeID)); #if (!ISWIN) SplitPackets<DirClassifiedReplyData>(ReturnValues, delegate(DirClassifiedReplyData[] data) { remoteClient.SendDirClassifiedReply(queryID, data); }); #else SplitPackets(ReturnValues, data => remoteClient.SendDirClassifiedReply(queryID, data)); #endif } public void SplitPackets<T>(List<T> packets, SendPacket<T> send) { if (packets.Count == 0) { send(new T[0]); return; } int i = 0; while (i < packets.Count) { int count = Math.Min(10, packets.Count); //Split into sets of 10 packets T[] data = packets.GetRange(i, count).ToArray(); i += count; if (data.Length != 0) send(data); } } /// <summary> /// Tell the client about X event /// </summary> /// <param name = "remoteClient"></param> /// <param name = "queryEventID">ID of the event</param> public void EventInfoRequest(IClientAPI remoteClient, uint queryEventID) { //Find the event EventData data = directoryService.GetEventInfo(queryEventID); if (data == null) return; //Send the event remoteClient.SendEventInfoReply(data); } public virtual void HandleMapItemRequest(IClientAPI remoteClient, uint flags, uint EstateID, bool godlike, uint itemtype, ulong regionhandle) { //All the parts are in for this, except for popular places and those are not in as they are not reqested anymore. List<mapItemReply> mapitems = new List<mapItemReply>(); mapItemReply mapitem = new mapItemReply(); uint xstart = 0; uint ystart = 0; Utils.LongToUInts(remoteClient.Scene.RegionInfo.RegionHandle, out xstart, out ystart); GridRegion GR = null; GR = regionhandle == 0 ? new GridRegion(remoteClient.Scene.RegionInfo) : m_Scenes[0].GridService.GetRegionByPosition(UUID.Zero, (int) xstart, (int) ystart); if (GR == null) { //No region??? return; } #region Telehub if (itemtype == (uint) GridItemType.Telehub) { IRegionConnector GF = DataManager.DataManager.RequestPlugin<IRegionConnector>(); if (GF == null) return; int tc = Environment.TickCount; //Find the telehub Telehub telehub = GF.FindTelehub(GR.RegionID, GR.RegionHandle); if (telehub != null) { mapitem = new mapItemReply { x = (uint) (GR.RegionLocX + telehub.TelehubLocX), y = (uint) (GR.RegionLocY + telehub.TelehubLocY), id = GR.RegionID, name = Util.Md5Hash(GR.RegionName + tc.ToString()), Extra = 1, Extra2 = 0 }; //The position is in GLOBAL coordinates (in meters) //This is how the name is sent, go figure //Not sure, but this is what gets sent mapitems.Add(mapitem); remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags); mapitems.Clear(); } } #endregion #region Land for sale //PG land that is for sale if (itemtype == (uint) GridItemType.LandForSale) { if (directoryService == null) return; //Find all the land, use "0" for the flags so we get all land for sale, no price or area checking List<DirLandReplyData> Landdata = directoryService.FindLandForSaleInRegion("0", uint.MaxValue, 0, 0, 0, GR.RegionID); int locX = 0; int locY = 0; foreach (DirLandReplyData landDir in Landdata) { if (landDir == null) continue; LandData landdata = directoryService.GetParcelInfo(landDir.parcelID); if (landdata == null || landdata.Maturity != 0) continue; //Not a PG land #if (!ISWIN) foreach (IScene scene in m_Scenes) { if (scene.RegionInfo.RegionID == landdata.RegionID) { //Global coords, so add the meters locX = scene.RegionInfo.RegionLocX; locY = scene.RegionInfo.RegionLocY; } } #else foreach (IScene scene in m_Scenes.Where(scene => scene.RegionInfo.RegionID == landdata.RegionID)) { //Global coords, so add the meters locX = scene.RegionInfo.RegionLocX; locY = scene.RegionInfo.RegionLocY; } #endif if (locY == 0 && locX == 0) { //Ask the grid service for the coordinates if the region is not local GridRegion r = m_Scenes[0].GridService.GetRegionByUUID(UUID.Zero, landdata.RegionID); if (r != null) { locX = r.RegionLocX; locY = r.RegionLocY; } } if (locY == 0 && locX == 0) //Couldn't find the region, don't send continue; mapitem = new mapItemReply { x = (uint) (locX + landdata.UserLocation.X), y = (uint) (locY + landdata.UserLocation.Y), id = landDir.parcelID, name = landDir.name, Extra = landDir.actualArea, Extra2 = landDir.salePrice }; //Global coords, so make sure its in meters mapitems.Add(mapitem); } //Send all the map items if (mapitems.Count != 0) { remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags); mapitems.Clear(); } } //Adult or mature land that is for sale if (itemtype == (uint) GridItemType.AdultLandForSale) { if (directoryService == null) return; //Find all the land, use "0" for the flags so we get all land for sale, no price or area checking List<DirLandReplyData> Landdata = directoryService.FindLandForSale("0", uint.MaxValue, 0, 0, 0, remoteClient.ScopeID); int locX = 0; int locY = 0; foreach (DirLandReplyData landDir in Landdata) { LandData landdata = directoryService.GetParcelInfo(landDir.parcelID); if (landdata == null || landdata.Maturity == 0) continue; //Its PG #if (!ISWIN) foreach (IScene scene in m_Scenes) { if (scene.RegionInfo.RegionID == landdata.RegionID) { locX = scene.RegionInfo.RegionLocX; locY = scene.RegionInfo.RegionLocY; } } #else foreach (IScene scene in m_Scenes.Where(scene => scene.RegionInfo.RegionID == landdata.RegionID)) { locX = scene.RegionInfo.RegionLocX; locY = scene.RegionInfo.RegionLocY; } #endif if (locY == 0 && locX == 0) { //Ask the grid service for the coordinates if the region is not local GridRegion r = m_Scenes[0].GridService.GetRegionByUUID(UUID.Zero, landdata.RegionID); if (r != null) { locX = r.RegionLocX; locY = r.RegionLocY; } } if (locY == 0 && locX == 0) //Couldn't find the region, don't send continue; mapitem = new mapItemReply { x = (uint) (locX + landdata.UserLocation.X), y = (uint) (locY + landdata.UserLocation.Y), id = landDir.parcelID, name = landDir.name, Extra = landDir.actualArea, Extra2 = landDir.salePrice }; //Global coords, so make sure its in meters mapitems.Add(mapitem); } //Send the results if we have any if (mapitems.Count != 0) { remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags); mapitems.Clear(); } } #endregion #region Events if (itemtype == (uint) GridItemType.PgEvent || itemtype == (uint) GridItemType.MatureEvent || itemtype == (uint) GridItemType.AdultEvent) { if (directoryService == null) return; //Find the maturity level int maturity = itemtype == (uint) GridItemType.PgEvent ? (int) DirectoryManager.EventFlags.PG : (itemtype == (uint) GridItemType.MatureEvent) ? (int) DirectoryManager.EventFlags.Mature : (int) DirectoryManager.EventFlags.Adult; //Gets all the events occuring in the given region by maturity level List<DirEventsReplyData> Eventdata = directoryService.FindAllEventsInRegion(GR.RegionName, maturity); foreach (DirEventsReplyData eventData in Eventdata) { //Get more info on the event EventData eventdata = directoryService.GetEventInfo(eventData.eventID); if (eventdata == null) continue; //Can't do anything about it Vector3 globalPos = eventdata.globalPos; mapitem = new mapItemReply { x = (uint) (globalPos.X + (remoteClient.Scene.RegionInfo.RegionSizeX/2)), y = (uint) (globalPos.Y + (remoteClient.Scene.RegionInfo.RegionSizeY/2)), id = UUID.Random(), name = eventData.name, Extra = (int) eventdata.dateUTC, Extra2 = (int) eventdata.eventID }; //Use global position plus half the region so that it doesn't always appear in the bottom corner mapitems.Add(mapitem); } //Send if we have any if (mapitems.Count != 0) { remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags); mapitems.Clear(); } } #endregion #region Classified if (itemtype == (uint) GridItemType.Classified) { if (directoryService == null) return; //Get all the classifieds in this region List<Classified> Classifieds = directoryService.GetClassifiedsInRegion(GR.RegionName); foreach (Classified classified in Classifieds) { //Get the region so we have its position GridRegion region = m_Scenes[0].GridService.GetRegionByName(UUID.Zero, classified.SimName); mapitem = new mapItemReply { x = (uint) (region.RegionLocX + classified.GlobalPos.X + (remoteClient.Scene.RegionInfo.RegionSizeX/2)), y = (uint) (region.RegionLocY + classified.GlobalPos.Y + (remoteClient.Scene.RegionInfo.RegionSizeY/2)), id = classified.CreatorUUID, name = classified.Name, Extra = 0, Extra2 = 0 }; //Use global position plus half the sim so that all classifieds are not in the bottom corner mapitems.Add(mapitem); } //Send the events, if we have any if (mapitems.Count != 0) { remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags); mapitems.Clear(); } } #endregion } public void OnPlacesQueryRequest(UUID QueryID, UUID TransactionID, string QueryText, uint QueryFlags, byte Category, string SimName, IClientAPI client) { if (QueryFlags == 64) //Agent Owned { //Get all the parcels client.SendPlacesQuery(directoryService.GetParcelByOwner(client.AgentId).ToArray(), QueryID, TransactionID); } if (QueryFlags == 256) //Group Owned { //Find all the group owned land List<ExtendedLandData> parcels = directoryService.GetParcelByOwner(QueryID); //Send if we have any parcels if (parcels.Count != 0) client.SendPlacesQuery(parcels.ToArray(), QueryID, TransactionID); } } public void ProcessAvatarPickerRequest(IClientAPI client, UUID avatarID, UUID RequestID, string query) { IScene scene = client.Scene; List<UserAccount> accounts = scene.UserAccountService.GetUserAccounts(scene.RegionInfo.ScopeID, query); if (accounts == null) accounts = new List<UserAccount>(0); AvatarPickerReplyPacket replyPacket = (AvatarPickerReplyPacket) PacketPool.Instance.GetPacket(PacketType.AvatarPickerReply); // TODO: don't create new blocks if recycling an old packet AvatarPickerReplyPacket.DataBlock[] searchData = new AvatarPickerReplyPacket.DataBlock[accounts.Count]; AvatarPickerReplyPacket.AgentDataBlock agentData = new AvatarPickerReplyPacket.AgentDataBlock {AgentID = avatarID, QueryID = RequestID}; replyPacket.AgentData = agentData; int i = 0; foreach (UserAccount item in accounts) { UUID translatedIDtem = item.PrincipalID; searchData[i] = new AvatarPickerReplyPacket.DataBlock { AvatarID = translatedIDtem, FirstName = Utils.StringToBytes(item.FirstName), LastName = Utils.StringToBytes(item.LastName) }; i++; } if (accounts.Count == 0) { searchData = new AvatarPickerReplyPacket.DataBlock[0]; } replyPacket.Data = searchData; AvatarPickerReplyAgentDataArgs agent_data = new AvatarPickerReplyAgentDataArgs { AgentID = replyPacket.AgentData.AgentID, QueryID = replyPacket.AgentData.QueryID }; List<AvatarPickerReplyDataArgs> data_args = new List<AvatarPickerReplyDataArgs>(); for (i = 0; i < replyPacket.Data.Length; i++) { AvatarPickerReplyDataArgs data_arg = new AvatarPickerReplyDataArgs { AvatarID = replyPacket.Data[i].AvatarID, FirstName = replyPacket.Data[i].FirstName, LastName = replyPacket.Data[i].LastName }; data_args.Add(data_arg); } client.SendAvatarPickerReply(agent_data, data_args); } #endregion #region ISharedRegionModule Members public void Initialise(IConfigSource config) { IConfig searchConfig = config.Configs["Search"]; if (searchConfig != null) //Check whether we are enabled if (searchConfig.GetString("SearchModule", Name) == Name) m_SearchEnabled = true; } public void AddRegion(IScene scene) { if (!m_SearchEnabled) return; m_Scenes.Add(scene); scene.EventManager.OnNewClient += NewClient; scene.EventManager.OnClosingClient += OnClosingClient; } public void RemoveRegion(IScene scene) { if (!m_SearchEnabled) return; m_Scenes.Remove(scene); scene.EventManager.OnNewClient -= NewClient; scene.EventManager.OnClosingClient -= OnClosingClient; } public void RegionLoaded(IScene scene) { if (!m_SearchEnabled) return; //Pull in the services we need ProfileFrontend = DataManager.DataManager.RequestPlugin<IProfileConnector>(); directoryService = DataManager.DataManager.RequestPlugin<IDirectoryServiceConnector>(); GroupsModule = scene.RequestModuleInterface<IGroupsModule>(); } public Type ReplaceableInterface { get { return null; } } public bool IsSharedModule { get { return false; } } public void PostInitialise() { } public void Close() { } public string Name { get { return "AuroraSearchModule"; } } #endregion } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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 System.Xml.Serialization; using Gallio.Common; using Gallio.Common.Collections; using Gallio.Common.Concurrency; using Gallio.Common.Policies; using Gallio.Runtime.Preferences.Schema; namespace Gallio.Runtime.Preferences { /// <summary> /// A preference set implementation based on storing preference settings within a file. /// </summary> public class FilePreferenceSet : IPreferenceSet { private readonly FileInfo preferenceSetFile; private readonly LockBox<PreferenceSetData> dataLockBox; /// <summary> /// Creates a file preference set. /// </summary> /// <param name="preferenceSetFile">The preference set file.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="preferenceSetFile"/> is null.</exception> public FilePreferenceSet(FileInfo preferenceSetFile) { if (preferenceSetFile == null) throw new ArgumentNullException("preferenceSetFile"); this.preferenceSetFile = preferenceSetFile; dataLockBox = new LockBox<PreferenceSetData>(new PreferenceSetData(preferenceSetFile)); } /// <summary> /// Gets the preference set file. /// </summary> public FileInfo PreferenceSetFile { get { return new FileInfo(preferenceSetFile.ToString()); } } /// <inheritdoc /> public void Read(ReadAction<IPreferenceSetReader> readAction) { if (readAction == null) throw new ArgumentNullException("readAction"); dataLockBox.Read(data => { data.Refresh(); readAction(new PreferenceSetReader(data)); }); } /// <inheritdoc /> public TResult Read<TResult>(ReadFunc<IPreferenceSetReader, TResult> readFunc) { if (readFunc == null) throw new ArgumentNullException("readFunc"); return dataLockBox.Read(data => { data.Refresh(); return readFunc(new PreferenceSetReader(data)); }); } /// <inheritdoc /> public void Write(WriteAction<IPreferenceSetWriter> writeAction) { if (writeAction == null) throw new ArgumentNullException("writeAction"); dataLockBox.Write(data => { data.Refresh(); try { writeAction(new PreferenceSetWriter(data)); } finally { data.Commit(); } }); } /// <inheritdoc /> public TResult Write<TResult>(WriteFunc<IPreferenceSetWriter, TResult> writeFunc) { if (writeFunc == null) throw new ArgumentNullException("writeFunc"); return dataLockBox.Write(data => { data.Refresh(); try { return writeFunc(new PreferenceSetWriter(data)); } finally { data.Commit(); } }); } private static string ConvertToRawValue<T>(T value) { return value != null ? Convert.ToString(value) : null; } private static T ConvertFromRawValue<T>(string rawValue) { if (typeof(T).IsEnum) return (T) Enum.Parse(typeof(T), rawValue); return (T)Convert.ChangeType(rawValue, typeof(T)); } private sealed class PreferenceSetData { private Memoizer<XmlSerializer> xmlSerializerMemoizer = new Memoizer<XmlSerializer>(); private readonly FileInfo preferenceSetFile; private readonly Dictionary<string, string> contents; private DateTime? cachedTimestamp; private bool modified; public PreferenceSetData(FileInfo preferenceSetFile) { this.preferenceSetFile = preferenceSetFile; contents = new Dictionary<string,string>(); } public void Refresh() { if (cachedTimestamp.HasValue) { DateTime? newTimestamp = GetTimestamp(); if (!newTimestamp.HasValue || newTimestamp.Value != cachedTimestamp.Value) { contents.Clear(); cachedTimestamp = null; } } } private void EnsureLoaded() { if (!cachedTimestamp.HasValue) { cachedTimestamp = GetTimestamp(); if (cachedTimestamp.HasValue) { PreferenceContainer container = LoadPreferenceContainer(); if (container != null) { foreach (var setting in container.Settings) contents[setting.Name] = setting.Value; } } } } public void Commit() { if (modified) { PreferenceContainer container = new PreferenceContainer(); foreach (var pair in contents) container.Settings.Add(new PreferenceSetting(pair.Key, pair.Value)); SavePreferenceContainer(container); cachedTimestamp = GetTimestamp(); modified = false; } } public string GetSetting<T>(Key<T> preferenceSettingKey) { EnsureLoaded(); string value; contents.TryGetValue(preferenceSettingKey.Name, out value); return value; } public void SetSetting<T>(Key<T> preferenceSettingKey, string rawValue) { EnsureLoaded(); if (rawValue == null) { if (contents.Remove(preferenceSettingKey.Name)) { modified = true; } } else { string oldRawValue; if (!contents.TryGetValue(preferenceSettingKey.Name, out oldRawValue) || oldRawValue != rawValue) { modified = true; contents[preferenceSettingKey.Name] = rawValue; } } } private XmlSerializer XmlSerializer { get { return xmlSerializerMemoizer.Memoize(() => new XmlSerializer(typeof(PreferenceContainer))); } } private DateTime? GetTimestamp() { preferenceSetFile.Refresh(); return preferenceSetFile.Exists ? preferenceSetFile.LastWriteTimeUtc : (DateTime?) null; } private PreferenceContainer LoadPreferenceContainer() { preferenceSetFile.Refresh(); if (preferenceSetFile.Exists) { try { using (var reader = new StreamReader(preferenceSetFile.Open(FileMode.Open, FileAccess.Read, FileShare.Read))) { var container = (PreferenceContainer) XmlSerializer.Deserialize(reader); container.Validate(); return container; } } catch (Exception ex) { UnhandledExceptionPolicy.Report(string.Format("Failed to load preferences from file '{0}'.", preferenceSetFile.FullName), ex); } } return null; } private void SavePreferenceContainer(PreferenceContainer container) { if (! preferenceSetFile.Directory.Exists) preferenceSetFile.Directory.Create(); using (var writer = new StreamWriter(preferenceSetFile.Open(FileMode.Create, FileAccess.Write, FileShare.None))) { XmlSerializer.Serialize(writer, container); } } } private class PreferenceSetReader : IPreferenceSetReader { protected readonly PreferenceSetData data; public PreferenceSetReader(PreferenceSetData data) { this.data = data; } public T GetSetting<T>(Key<T> preferenceSettingKey) { return GetSetting(preferenceSettingKey, default(T)); } public T GetSetting<T>(Key<T> preferenceSettingKey, T defaultValue) { string rawValue = data.GetSetting(preferenceSettingKey); if (rawValue == null) return defaultValue; return ConvertFromRawValue<T>(rawValue); } public bool HasSetting<T>(Key<T> preferenceSettingKey) { return data.GetSetting(preferenceSettingKey) != null; } } private sealed class PreferenceSetWriter : PreferenceSetReader, IPreferenceSetWriter { public PreferenceSetWriter(PreferenceSetData data) : base(data) { } public void SetSetting<T>(Key<T> preferenceSettingKey, T value) { string rawValue = ConvertToRawValue(value); data.SetSetting(preferenceSettingKey, rawValue); } public void RemoveSetting<T>(Key<T> preferenceSettingKey) { data.SetSetting(preferenceSettingKey, null); } } } }
/* [The "BSD licence"] Copyright (c) 2005-2007 Kunle Odutola All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code MUST RETAIN the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior WRITTEN permission. 4. Unless explicitly state otherwise, any contribution intentionally submitted for inclusion in this work to the copyright owner or licensor shall be under the terms and conditions of this license, without any additional terms or conditions. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */ #pragma warning disable 219 // No unused variable warnings namespace Antlr.Runtime.Tests { using System; using Stream = System.IO.Stream; using FileStream = System.IO.FileStream; using MemoryStream = System.IO.MemoryStream; using FileMode = System.IO.FileMode; using Encoding = System.Text.Encoding; using Encoder = System.Text.Encoder; using ANTLRInputStream = Antlr.Runtime.ANTLRInputStream; using MbUnit.Framework; [TestFixture] public class ANTLRxxxxStreamFixture : TestFixtureBase { private static readonly string grammarStr = "" + "parser grammar p;" + NL + "prog : WHILE ID LCURLY (assign)* RCURLY EOF;" + NL + "assign : ID ASSIGN expr SEMI ;" + NL + "expr : INT | FLOAT | ID ;" + NL; #region ANTLRInputStream Tests [Test] public void TestANTLRInputStreamConstructorDoesNotHang() { Encoding encoding = Encoding.Unicode; byte[] grammarStrBuffer = encoding.GetBytes(grammarStr); MemoryStream grammarStream = new MemoryStream(grammarStrBuffer); ANTLRInputStream input = new ANTLRInputStream(grammarStream, encoding); } [Test] public void TestSizeOnEmptyANTLRInputStream() { MemoryStream grammarStream = new MemoryStream(new byte[] { }); ANTLRInputStream inputStream = new ANTLRInputStream(grammarStream, Encoding.Unicode); Assert.AreEqual(0, inputStream.Count); } [Test] public void TestSizeOnANTLRInputStream() { Encoding encoding = Encoding.Unicode; byte[] grammarStrBuffer = encoding.GetBytes(grammarStr); MemoryStream grammarStream = new MemoryStream(grammarStrBuffer); ANTLRInputStream inputStream = new ANTLRInputStream(grammarStream, Encoding.Unicode); Assert.AreEqual(grammarStr.Length, inputStream.Count); } [Test] public void TestConsumeAndIndexOnANTLRInputStream() { Encoding encoding = Encoding.Unicode; byte[] grammarStrBuffer = encoding.GetBytes(grammarStr); MemoryStream grammarStream = new MemoryStream(grammarStrBuffer); ANTLRInputStream inputStream = new ANTLRInputStream(grammarStream, Encoding.Unicode); Assert.AreEqual(0, inputStream.Index); inputStream.Consume(); Assert.AreEqual(1, inputStream.Index); inputStream.Consume(); Assert.AreEqual(2, inputStream.Index); while (inputStream.Index < inputStream.Count) { inputStream.Consume(); } Assert.AreEqual(inputStream.Index, inputStream.Count); } [Test] public void TestConsumeAllCharactersInAnANTLRInputStream() { Encoding encoding = Encoding.Unicode; byte[] grammarStrBuffer = encoding.GetBytes(grammarStr); MemoryStream grammarStream = new MemoryStream(grammarStrBuffer); ANTLRInputStream inputStream = new ANTLRInputStream(grammarStream, Encoding.Unicode); while (inputStream.Index < inputStream.Count) { Console.Out.Write((char)inputStream.LA(1)); inputStream.Consume(); } Assert.AreEqual(inputStream.Index, inputStream.Count); } [Test] public void TestConsumeOnANTLRInputStream() { Encoding encoding = Encoding.Unicode; byte[] buffer = encoding.GetBytes("One\r\nTwo"); MemoryStream grammarStream = new MemoryStream(buffer); ANTLRInputStream inputStream = new ANTLRInputStream(grammarStream, Encoding.Unicode); Assert.AreEqual(0, inputStream.Index); Assert.AreEqual(0, inputStream.CharPositionInLine); Assert.AreEqual(1, inputStream.Line); inputStream.Consume(); // O Assert.AreEqual(1, inputStream.Index); Assert.AreEqual(1, inputStream.CharPositionInLine); Assert.AreEqual(1, inputStream.Line); inputStream.Consume(); // n Assert.AreEqual(2, inputStream.Index); Assert.AreEqual(2, inputStream.CharPositionInLine); Assert.AreEqual(1, inputStream.Line); inputStream.Consume(); // e Assert.AreEqual(3, inputStream.Index); Assert.AreEqual(3, inputStream.CharPositionInLine); Assert.AreEqual(1, inputStream.Line); inputStream.Consume(); // \r Assert.AreEqual(4, inputStream.Index); Assert.AreEqual(4, inputStream.CharPositionInLine); Assert.AreEqual(1, inputStream.Line); inputStream.Consume(); // \n Assert.AreEqual(5, inputStream.Index); Assert.AreEqual(0, inputStream.CharPositionInLine); Assert.AreEqual(2, inputStream.Line); inputStream.Consume(); // T Assert.AreEqual(6, inputStream.Index); Assert.AreEqual(1, inputStream.CharPositionInLine); Assert.AreEqual(2, inputStream.Line); inputStream.Consume(); // w Assert.AreEqual(7, inputStream.Index); Assert.AreEqual(2, inputStream.CharPositionInLine); Assert.AreEqual(2, inputStream.Line); inputStream.Consume(); // o Assert.AreEqual(8, inputStream.Index); Assert.AreEqual(3, inputStream.CharPositionInLine); Assert.AreEqual(2, inputStream.Line); inputStream.Consume(); // EOF Assert.AreEqual(8, inputStream.Index); Assert.AreEqual(3, inputStream.CharPositionInLine); Assert.AreEqual(2, inputStream.Line); inputStream.Consume(); // EOF Assert.AreEqual(8, inputStream.Index); Assert.AreEqual(3, inputStream.CharPositionInLine); Assert.AreEqual(2, inputStream.Line); } [Test] public void TestResetOnANTLRInputStream() { Encoding encoding = Encoding.Unicode; byte[] buffer = encoding.GetBytes("One\r\nTwo"); MemoryStream grammarStream = new MemoryStream(buffer); ANTLRInputStream inputStream = new ANTLRInputStream(grammarStream, encoding); Assert.AreEqual(0, inputStream.Index); Assert.AreEqual(0, inputStream.CharPositionInLine); Assert.AreEqual(1, inputStream.Line); inputStream.Consume(); // O inputStream.Consume(); // n Assert.AreEqual('e', inputStream.LA(1)); Assert.AreEqual(2, inputStream.Index); inputStream.Reset(); Assert.AreEqual('O', inputStream.LA(1)); Assert.AreEqual(0, inputStream.Index); Assert.AreEqual(0, inputStream.CharPositionInLine); Assert.AreEqual(1, inputStream.Line); inputStream.Consume(); // O Assert.AreEqual('n', inputStream.LA(1)); Assert.AreEqual(1, inputStream.Index); Assert.AreEqual(1, inputStream.CharPositionInLine); Assert.AreEqual(1, inputStream.Line); inputStream.Consume(); // n Assert.AreEqual('e', inputStream.LA(1)); Assert.AreEqual(2, inputStream.Index); Assert.AreEqual(2, inputStream.CharPositionInLine); Assert.AreEqual(1, inputStream.Line); inputStream.Consume(); // e } [Test] public void TestSubstringOnANTLRInputStream() { Encoding encoding = Encoding.Unicode; byte[] buffer = encoding.GetBytes("One\r\nTwo\r\nThree"); MemoryStream grammarStream = new MemoryStream(buffer); ANTLRInputStream stream = new ANTLRInputStream(grammarStream, encoding); Assert.AreEqual("Two", stream.Substring(5, 7)); Assert.AreEqual("One", stream.Substring(0, 2)); Assert.AreEqual("Three", stream.Substring(10, 14)); stream.Consume(); Assert.AreEqual("Two", stream.Substring(5, 7)); Assert.AreEqual("One", stream.Substring(0, 2)); Assert.AreEqual("Three", stream.Substring(10, 14)); } [Test] public void TestSeekOnANTLRInputStream() { Encoding encoding = Encoding.Unicode; byte[] buffer = encoding.GetBytes("One\r\nTwo\r\nThree"); MemoryStream grammarStream = new MemoryStream(buffer); ANTLRInputStream stream = new ANTLRInputStream(grammarStream, encoding); Assert.AreEqual('O', stream.LA(1)); Assert.AreEqual(0, stream.Index); Assert.AreEqual(0, stream.CharPositionInLine); Assert.AreEqual(1, stream.Line); stream.Seek(6); Assert.AreEqual('w', stream.LA(1)); Assert.AreEqual(6, stream.Index); Assert.AreEqual(1, stream.CharPositionInLine); Assert.AreEqual(2, stream.Line); stream.Seek(11); Assert.AreEqual('h', stream.LA(1)); Assert.AreEqual(11, stream.Index); Assert.AreEqual(1, stream.CharPositionInLine); Assert.AreEqual(3, stream.Line); // seeking backwards leaves state info (other than index in stream) unchanged stream.Seek(1); Assert.AreEqual('n', stream.LA(1)); Assert.AreEqual(1, stream.Index); Assert.AreEqual(1, stream.CharPositionInLine); Assert.AreEqual(3, stream.Line); } #endregion #region ANTLRStringStream Tests [Test] public void TestSizeOnEmptyANTLRStringStream() { ANTLRStringStream s1 = new ANTLRStringStream(""); Assert.AreEqual(0, s1.Count); Assert.AreEqual(0, s1.Index); } [Test] public void TestSizeOnANTLRStringStream() { ANTLRStringStream s1 = new ANTLRStringStream("lexer\r\n"); Assert.AreEqual(7, s1.Count); ANTLRStringStream s2 = new ANTLRStringStream(grammarStr); Assert.AreEqual(grammarStr.Length, s2.Count); ANTLRStringStream s3 = new ANTLRStringStream("grammar P;"); Assert.AreEqual(10, s3.Count); } [Test] public void TestConsumeOnANTLRStringStream() { ANTLRStringStream stream = new ANTLRStringStream("One\r\nTwo"); Assert.AreEqual(0, stream.Index); Assert.AreEqual(0, stream.CharPositionInLine); Assert.AreEqual(1, stream.Line); stream.Consume(); // O Assert.AreEqual(1, stream.Index); Assert.AreEqual(1, stream.CharPositionInLine); Assert.AreEqual(1, stream.Line); stream.Consume(); // n Assert.AreEqual(2, stream.Index); Assert.AreEqual(2, stream.CharPositionInLine); Assert.AreEqual(1, stream.Line); stream.Consume(); // e Assert.AreEqual(3, stream.Index); Assert.AreEqual(3, stream.CharPositionInLine); Assert.AreEqual(1, stream.Line); stream.Consume(); // \r Assert.AreEqual(4, stream.Index); Assert.AreEqual(4, stream.CharPositionInLine); Assert.AreEqual(1, stream.Line); stream.Consume(); // \n Assert.AreEqual(5, stream.Index); Assert.AreEqual(0, stream.CharPositionInLine); Assert.AreEqual(2, stream.Line); stream.Consume(); // T Assert.AreEqual(6, stream.Index); Assert.AreEqual(1, stream.CharPositionInLine); Assert.AreEqual(2, stream.Line); stream.Consume(); // w Assert.AreEqual(7, stream.Index); Assert.AreEqual(2, stream.CharPositionInLine); Assert.AreEqual(2, stream.Line); stream.Consume(); // o Assert.AreEqual(8, stream.Index); Assert.AreEqual(3, stream.CharPositionInLine); Assert.AreEqual(2, stream.Line); stream.Consume(); // EOF Assert.AreEqual(8, stream.Index); Assert.AreEqual(3, stream.CharPositionInLine); Assert.AreEqual(2, stream.Line); stream.Consume(); // EOF Assert.AreEqual(8, stream.Index); Assert.AreEqual(3, stream.CharPositionInLine); Assert.AreEqual(2, stream.Line); } [Test] public void TestResetOnANTLRStringStream() { ANTLRStringStream stream = new ANTLRStringStream("One\r\nTwo"); Assert.AreEqual(0, stream.Index); Assert.AreEqual(0, stream.CharPositionInLine); Assert.AreEqual(1, stream.Line); stream.Consume(); // O stream.Consume(); // n Assert.AreEqual('e', stream.LA(1)); Assert.AreEqual(2, stream.Index); stream.Reset(); Assert.AreEqual('O', stream.LA(1)); Assert.AreEqual(0, stream.Index); Assert.AreEqual(0, stream.CharPositionInLine); Assert.AreEqual(1, stream.Line); stream.Consume(); // O Assert.AreEqual('n', stream.LA(1)); Assert.AreEqual(1, stream.Index); Assert.AreEqual(1, stream.CharPositionInLine); Assert.AreEqual(1, stream.Line); stream.Consume(); // n Assert.AreEqual('e', stream.LA(1)); Assert.AreEqual(2, stream.Index); Assert.AreEqual(2, stream.CharPositionInLine); Assert.AreEqual(1, stream.Line); stream.Consume(); // e } [Test] public void TestSubstringOnANTLRStringStream() { ANTLRStringStream stream = new ANTLRStringStream("One\r\nTwo\r\nThree"); Assert.AreEqual("Two", stream.Substring(5, 7)); Assert.AreEqual("One", stream.Substring(0, 2)); Assert.AreEqual("Three", stream.Substring(10, 14)); stream.Consume(); Assert.AreEqual("Two", stream.Substring(5, 7)); Assert.AreEqual("One", stream.Substring(0, 2)); Assert.AreEqual("Three", stream.Substring(10, 14)); } #endregion } }
//////////////////////////////////////////////////////////////////////////////// // ________ _____ __ // / _____/_______ _____ ____ ____ _/ ____\__ __ | | // / \ ___\_ __ \\__ \ _/ ___\_/ __ \\ __\| | \| | // \ \_\ \| | \/ / __ \_\ \___\ ___/ | | | | /| |__ // \______ /|__| (____ / \___ >\___ >|__| |____/ |____/ // \/ \/ \/ \/ // ============================================================================= // Designed & Developed by Brad Jones <brad @="bjc.id.au" /> // ============================================================================= //////////////////////////////////////////////////////////////////////////////// namespace Graceful.Utils.Visitors { using System; using System.Text; using Graceful.Query; using System.Reflection; using System.Linq.Expressions; using System.Collections.Generic; /** * Given an Expression Tree, we will convert it into a SQL LIKE clause. * * ``` * Expression<Func<TModel, bool>> expression = * m => m.Foo == "%Bar%" && m.Baz != "Q%x"; * * var converter = new LikeConverter(); * converter.Visit(expression.Body); * * // converter.Sql == "Foo LIKE {0} AND Baz NOT LIKE {1}" * // converter.Parameters == new object[] { "%Bar%", "Q%x" } * ``` */ public class LikeConverter : ExpressionVisitor { /** * The portion of the SQL query that will come after a WHERE clause. */ public string Sql { get { return this.sql.ToString().Trim(); } } private StringBuilder sql = new StringBuilder(); /** * A list of parameter values that go along with our sql query segment. */ public object[] Parameters { get { return this.parameters.ToArray(); } } private List<object> parameters = new List<object>(); /** * When we recurse into a MemberExpression, looking for a * ConstantExpression, we do not want to write anything to * the sql StringBuilder. */ private bool blockWriting = false; /** * In some cases, we need to save the value we get from a MemberInfo * and save it for later use, when we are at the correct * MemberExpression. */ private object value; protected override Expression VisitBinary(BinaryExpression node) { // Open the binary expression in SQL this.sql.Append("("); // Go and visit the left hand side of this expression this.Visit(node.Left); // Add the operator in the middle switch (node.NodeType) { case ExpressionType.Equal: this.sql.Append("LIKE"); break; case ExpressionType.NotEqual: this.sql.Append("NOT LIKE"); break; case ExpressionType.And: case ExpressionType.AndAlso: this.sql.Append("AND"); break; case ExpressionType.Or: case ExpressionType.OrElse: this.sql.Append("OR"); break; default: throw new UnknownOperatorException(node.NodeType); } // Operator needs a space after it. this.sql.Append(" "); // Now visit the right hand side of this expression. this.Visit(node.Right); // Close the binary expression in SQL this.sql.Append(") "); return node; } protected override Expression VisitMember(MemberExpression node) { // This will get filled with the "actual" value from our child // ConstantExpression if happen to have a child ConstantExpression. // see: http://stackoverflow.com/questions/6998523 object value = null; // Recurse down to see if we can simplify... this.blockWriting = true; var expression = this.Visit(node.Expression); this.blockWriting = false; // If we've ended up with a constant, and it's a property // or a field, we can simplify ourselves to a constant. if (expression is ConstantExpression) { MemberInfo member = node.Member; object container = ((ConstantExpression)expression).Value; if (member is FieldInfo) { value = ((FieldInfo)member).GetValue(container); } else if (member is PropertyInfo) { value = ((PropertyInfo)member).GetValue(container, null); } // If we managed to actually get a value, lets now create a // ConstantExpression with the expected value and Vist it. if (value != null) { if (TypeMapper.IsClrType(value)) { this.Visit(Expression.Constant(value)); } else { // So if we get to here, what has happened is that // the value returned by the FieldInfo GetValue call // is actually the container, so we save it for later. this.value = value; } } } else if (expression is MemberExpression) { // Now we can use the value we saved earlier to actually grab // the constant value that we expected. I guess this sort of // recursion could go on for ages and hence why the accepted // answer used DyanmicInvoke. Anyway we will hope that this // does the job for our needs. MemberInfo member = node.Member; object container = this.value; if (member is FieldInfo) { value = ((FieldInfo)member).GetValue(container); } else if (member is PropertyInfo) { value = ((PropertyInfo)member).GetValue(container, null); } this.value = null; if (TypeMapper.IsClrType(value)) { this.Visit(Expression.Constant(value)); } else { throw new ExpressionTooComplexException(); } } // We only need to do this if we did not // have a child ConstantExpression if (value == null) { this.sql.Append(new SqlId(node.Member.Name).Value); this.sql.Append(" "); } return node; } protected override Expression VisitConstant(ConstantExpression node) { if (!this.blockWriting) { this.sql.Append("{"); this.sql.Append(this.parameters.Count); this.sql.Append("}"); this.parameters.Add(node.Value); } return node; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; namespace System.Net { internal class IPAddressParser { private const int MaxIPv4StringLength = 15; // 4 numbers separated by 3 periods, with up to 3 digits per number internal static unsafe IPAddress Parse(ReadOnlySpan<char> ipSpan, bool tryParse) { if (ipSpan.IndexOf(':') >= 0) { // The address is parsed as IPv6 if and only if it contains a colon. This is valid because // we don't support/parse a port specification at the end of an IPv4 address. ushort* numbers = stackalloc ushort[IPAddressParserStatics.IPv6AddressShorts]; new Span<ushort>(numbers, IPAddressParserStatics.IPv6AddressShorts).Clear(); if (Ipv6StringToAddress(ipSpan, numbers, IPAddressParserStatics.IPv6AddressShorts, out uint scope)) { return new IPAddress(numbers, IPAddressParserStatics.IPv6AddressShorts, scope); } } else if (Ipv4StringToAddress(ipSpan, out long address)) { return new IPAddress(address); } if (tryParse) { return null; } throw new FormatException(SR.dns_bad_ip_address, new SocketException(SocketError.InvalidArgument)); } internal static unsafe string IPv4AddressToString(uint address) { char* addressString = stackalloc char[MaxIPv4StringLength]; int charsWritten = IPv4AddressToStringHelper(address, addressString); return new string(addressString, 0, charsWritten); } internal static unsafe bool IPv4AddressToString(uint address, Span<char> formatted, out int charsWritten) { if (formatted.Length < MaxIPv4StringLength) { charsWritten = 0; return false; } fixed (char* formattedPtr = &MemoryMarshal.GetReference(formatted)) { charsWritten = IPv4AddressToStringHelper(address, formattedPtr); } return true; } private static unsafe int IPv4AddressToStringHelper(uint address, char* addressString) { int offset = 0; FormatIPv4AddressNumber((int)(address & 0xFF), addressString, ref offset); addressString[offset++] = '.'; FormatIPv4AddressNumber((int)((address >> 8) & 0xFF), addressString, ref offset); addressString[offset++] = '.'; FormatIPv4AddressNumber((int)((address >> 16) & 0xFF), addressString, ref offset); addressString[offset++] = '.'; FormatIPv4AddressNumber((int)((address >> 24) & 0xFF), addressString, ref offset); return offset; } internal static string IPv6AddressToString(ushort[] address, uint scopeId) { Debug.Assert(address != null); Debug.Assert(address.Length == IPAddressParserStatics.IPv6AddressShorts); StringBuilder buffer = IPv6AddressToStringHelper(address, scopeId); return StringBuilderCache.GetStringAndRelease(buffer); } internal static bool IPv6AddressToString(ushort[] address, uint scopeId, Span<char> destination, out int charsWritten) { Debug.Assert(address != null); Debug.Assert(address.Length == IPAddressParserStatics.IPv6AddressShorts); StringBuilder buffer = IPv6AddressToStringHelper(address, scopeId); if (destination.Length < buffer.Length) { StringBuilderCache.Release(buffer); charsWritten = 0; return false; } buffer.CopyTo(0, destination, buffer.Length); charsWritten = buffer.Length; StringBuilderCache.Release(buffer); return true; } internal static StringBuilder IPv6AddressToStringHelper(ushort[] address, uint scopeId) { const int INET6_ADDRSTRLEN = 65; StringBuilder buffer = StringBuilderCache.Acquire(INET6_ADDRSTRLEN); if (IPv6AddressHelper.ShouldHaveIpv4Embedded(address)) { // We need to treat the last 2 ushorts as a 4-byte IPv4 address, // so output the first 6 ushorts normally, followed by the IPv4 address. AppendSections(address, 0, 6, buffer); if (buffer[buffer.Length - 1] != ':') { buffer.Append(':'); } buffer.Append(IPAddressParser.IPv4AddressToString(ExtractIPv4Address(address))); } else { // No IPv4 address. Output all 8 sections as part of the IPv6 address // with normal formatting rules. AppendSections(address, 0, 8, buffer); } // If there's a scope ID, append it. if (scopeId != 0) { buffer.Append('%').Append(scopeId); } return buffer; } private static unsafe void FormatIPv4AddressNumber(int number, char* addressString, ref int offset) { // Math.DivRem has no overload for byte, assert here for safety Debug.Assert(number < 256); offset += number > 99 ? 3 : number > 9 ? 2 : 1; int i = offset; do { number = Math.DivRem(number, 10, out int rem); addressString[--i] = (char)('0' + rem); } while (number != 0); } public static unsafe bool Ipv4StringToAddress(ReadOnlySpan<char> ipSpan, out long address) { int end = ipSpan.Length; long tmpAddr; fixed (char* ipStringPtr = &MemoryMarshal.GetReference(ipSpan)) { tmpAddr = IPv4AddressHelper.ParseNonCanonical(ipStringPtr, 0, ref end, notImplicitFile: true); } if (tmpAddr != IPv4AddressHelper.Invalid && end == ipSpan.Length) { // IPv4AddressHelper.ParseNonCanonical returns the bytes in the inverse order. // Reverse them and return success. address = ((0xFF000000 & tmpAddr) >> 24) | ((0x00FF0000 & tmpAddr) >> 8) | ((0x0000FF00 & tmpAddr) << 8) | ((0x000000FF & tmpAddr) << 24); return true; } else { // Failed to parse the address. address = 0; return false; } } public static unsafe bool Ipv6StringToAddress(ReadOnlySpan<char> ipSpan, ushort* numbers, int numbersLength, out uint scope) { Debug.Assert(numbers != null); Debug.Assert(numbersLength >= IPAddressParserStatics.IPv6AddressShorts); int end = ipSpan.Length; bool isValid = false; fixed (char* ipStringPtr = &MemoryMarshal.GetReference(ipSpan)) { isValid = IPv6AddressHelper.IsValidStrict(ipStringPtr, 0, ref end); } if (isValid || (end != ipSpan.Length)) { string scopeId = null; IPv6AddressHelper.Parse(ipSpan, numbers, 0, ref scopeId); long result = 0; if (!string.IsNullOrEmpty(scopeId)) { if (scopeId.Length < 2) { scope = 0; return false; } for (int i = 1; i < scopeId.Length; i++) { char c = scopeId[i]; if (c < '0' || c > '9') { scope = 0; return false; } result = (result * 10) + (c - '0'); if (result > uint.MaxValue) { scope = 0; return false; } } } scope = (uint)result; return true; } scope = 0; return false; } /// <summary> /// Appends each of the numbers in address in indexed range [fromInclusive, toExclusive), /// while also replacing the longest sequence of 0s found in that range with "::", as long /// as the sequence is more than one 0. /// </summary> private static void AppendSections(ushort[] address, int fromInclusive, int toExclusive, StringBuilder buffer) { // Find the longest sequence of zeros to be combined into a "::" (int zeroStart, int zeroEnd) = IPv6AddressHelper.FindCompressionRange(address, fromInclusive, toExclusive); bool needsColon = false; // Output all of the numbers before the zero sequence for (int i = fromInclusive; i < zeroStart; i++) { if (needsColon) { buffer.Append(':'); } needsColon = true; AppendHex(address[i], buffer); } // Output the zero sequence if there is one if (zeroStart >= 0) { buffer.Append("::"); needsColon = false; fromInclusive = zeroEnd; } // Output everything after the zero sequence for (int i = fromInclusive; i < toExclusive; i++) { if (needsColon) { buffer.Append(':'); } needsColon = true; AppendHex(address[i], buffer); } } /// <summary>Appends a number as hexadecimal (without the leading "0x") to the StringBuilder.</summary> private static unsafe void AppendHex(ushort value, StringBuilder buffer) { const int MaxLength = sizeof(ushort) * 2; // two hex chars per byte char* chars = stackalloc char[MaxLength]; int pos = MaxLength; do { int rem = value % 16; value /= 16; chars[--pos] = rem < 10 ? (char)('0' + rem) : (char)('a' + (rem - 10)); Debug.Assert(pos >= 0); } while (value != 0); buffer.Append(chars + pos, MaxLength - pos); } /// <summary>Extracts the IPv4 address from the end of the IPv6 address byte array.</summary> private static uint ExtractIPv4Address(ushort[] address) => (uint)(Reverse(address[7]) << 16) | Reverse(address[6]); /// <summary>Reverses the two bytes in the ushort.</summary> private static ushort Reverse(ushort number) => (ushort)(((number >> 8) & 0xFF) | ((number << 8) & 0xFF00)); } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmNewDenomination { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmNewDenomination() : base() { Load += frmNewDenomination_Load; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; private System.Windows.Forms.TextBox withEventsField_txtUnit; public System.Windows.Forms.TextBox txtUnit { get { return withEventsField_txtUnit; } set { if (withEventsField_txtUnit != null) { withEventsField_txtUnit.Enter -= txtUnit_Enter; withEventsField_txtUnit.KeyPress -= txtUnit_KeyPress; withEventsField_txtUnit.Leave -= txtUnit_Leave; } withEventsField_txtUnit = value; if (withEventsField_txtUnit != null) { withEventsField_txtUnit.Enter += txtUnit_Enter; withEventsField_txtUnit.KeyPress += txtUnit_KeyPress; withEventsField_txtUnit.Leave += txtUnit_Leave; } } } public System.Windows.Forms.CheckBox Check1; public System.Windows.Forms.RadioButton _optCoin_1; public System.Windows.Forms.RadioButton _optCoin_0; private System.Windows.Forms.TextBox withEventsField_txtPack; public System.Windows.Forms.TextBox txtPack { get { return withEventsField_txtPack; } set { if (withEventsField_txtPack != null) { withEventsField_txtPack.Enter -= txtPack_Enter; withEventsField_txtPack.KeyPress -= txtPack_KeyPress; withEventsField_txtPack.Leave -= txtPack_Leave; } withEventsField_txtPack = value; if (withEventsField_txtPack != null) { withEventsField_txtPack.Enter += txtPack_Enter; withEventsField_txtPack.KeyPress += txtPack_KeyPress; withEventsField_txtPack.Leave += txtPack_Leave; } } } public System.Windows.Forms.TextBox txtName; private System.Windows.Forms.Button withEventsField_Command2; public System.Windows.Forms.Button Command2 { get { return withEventsField_Command2; } set { if (withEventsField_Command2 != null) { withEventsField_Command2.Click -= Command2_Click; } withEventsField_Command2 = value; if (withEventsField_Command2 != null) { withEventsField_Command2.Click += Command2_Click; } } } private System.Windows.Forms.Button withEventsField_Command1; public System.Windows.Forms.Button Command1 { get { return withEventsField_Command1; } set { if (withEventsField_Command1 != null) { withEventsField_Command1.Click -= Command1_Click; } withEventsField_Command1 = value; if (withEventsField_Command1 != null) { withEventsField_Command1.Click += Command1_Click; } } } public System.Windows.Forms.Panel picButtons; public System.Windows.Forms.Label Label4; public System.Windows.Forms.Label Label3; public System.Windows.Forms.Label Label2; public System.Windows.Forms.Label Label1; //Public WithEvents optCoin As Microsoft.VisualBasic.Compatibility.VB6.RadioButtonArray //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmNewDenomination)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.txtUnit = new System.Windows.Forms.TextBox(); this.Check1 = new System.Windows.Forms.CheckBox(); this._optCoin_1 = new System.Windows.Forms.RadioButton(); this._optCoin_0 = new System.Windows.Forms.RadioButton(); this.txtPack = new System.Windows.Forms.TextBox(); this.txtName = new System.Windows.Forms.TextBox(); this.picButtons = new System.Windows.Forms.Panel(); this.Command2 = new System.Windows.Forms.Button(); this.Command1 = new System.Windows.Forms.Button(); this.Label4 = new System.Windows.Forms.Label(); this.Label3 = new System.Windows.Forms.Label(); this.Label2 = new System.Windows.Forms.Label(); this.Label1 = new System.Windows.Forms.Label(); //Me.optCoin = New Microsoft.VisualBasic.Compatibility.VB6.RadioButtonArray(components) this.picButtons.SuspendLayout(); this.SuspendLayout(); this.ToolTip1.Active = true; //CType(Me.optCoin, System.ComponentModel.ISupportInitialize).BeginInit() this.Text = "New Denomination"; this.ClientSize = new System.Drawing.Size(234, 157); this.Location = new System.Drawing.Point(4, 23); this.ControlBox = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Control; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable; this.Enabled = true; this.KeyPreview = false; this.MaximizeBox = true; this.MinimizeBox = true; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.ShowInTaskbar = true; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmNewDenomination"; this.txtUnit.AutoSize = false; this.txtUnit.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.txtUnit.Size = new System.Drawing.Size(81, 19); this.txtUnit.Location = new System.Drawing.Point(146, 66); this.txtUnit.TabIndex = 1; this.txtUnit.Text = "0"; this.txtUnit.AcceptsReturn = true; this.txtUnit.BackColor = System.Drawing.SystemColors.Window; this.txtUnit.CausesValidation = true; this.txtUnit.Enabled = true; this.txtUnit.ForeColor = System.Drawing.SystemColors.WindowText; this.txtUnit.HideSelection = true; this.txtUnit.ReadOnly = false; this.txtUnit.MaxLength = 0; this.txtUnit.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtUnit.Multiline = false; this.txtUnit.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtUnit.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtUnit.TabStop = true; this.txtUnit.Visible = true; this.txtUnit.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtUnit.Name = "txtUnit"; this.Check1.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this.Check1.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.Check1.BackColor = System.Drawing.SystemColors.ScrollBar; this.Check1.Text = "Disable Denominations"; this.Check1.ForeColor = System.Drawing.SystemColors.WindowText; this.Check1.Size = new System.Drawing.Size(223, 17); this.Check1.Location = new System.Drawing.Point(2, 134); this.Check1.TabIndex = 10; this.Check1.CausesValidation = true; this.Check1.Enabled = true; this.Check1.Cursor = System.Windows.Forms.Cursors.Default; this.Check1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Check1.Appearance = System.Windows.Forms.Appearance.Normal; this.Check1.TabStop = true; this.Check1.CheckState = System.Windows.Forms.CheckState.Unchecked; this.Check1.Visible = true; this.Check1.Name = "Check1"; this._optCoin_1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this._optCoin_1.BackColor = System.Drawing.SystemColors.ScrollBar; this._optCoin_1.Text = "Note"; this._optCoin_1.ForeColor = System.Drawing.SystemColors.WindowText; this._optCoin_1.Size = new System.Drawing.Size(59, 15); this._optCoin_1.Location = new System.Drawing.Point(166, 114); this._optCoin_1.TabIndex = 9; this._optCoin_1.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft; this._optCoin_1.CausesValidation = true; this._optCoin_1.Enabled = true; this._optCoin_1.Cursor = System.Windows.Forms.Cursors.Default; this._optCoin_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._optCoin_1.Appearance = System.Windows.Forms.Appearance.Normal; this._optCoin_1.TabStop = true; this._optCoin_1.Checked = false; this._optCoin_1.Visible = true; this._optCoin_1.Name = "_optCoin_1"; this._optCoin_0.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this._optCoin_0.BackColor = System.Drawing.SystemColors.ScrollBar; this._optCoin_0.Text = "Coin"; this._optCoin_0.ForeColor = System.Drawing.SystemColors.WindowText; this._optCoin_0.Size = new System.Drawing.Size(51, 15); this._optCoin_0.Location = new System.Drawing.Point(94, 114); this._optCoin_0.TabIndex = 8; this._optCoin_0.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft; this._optCoin_0.CausesValidation = true; this._optCoin_0.Enabled = true; this._optCoin_0.Cursor = System.Windows.Forms.Cursors.Default; this._optCoin_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._optCoin_0.Appearance = System.Windows.Forms.Appearance.Normal; this._optCoin_0.TabStop = true; this._optCoin_0.Checked = false; this._optCoin_0.Visible = true; this._optCoin_0.Name = "_optCoin_0"; this.txtPack.AutoSize = false; this.txtPack.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.txtPack.Size = new System.Drawing.Size(81, 17); this.txtPack.Location = new System.Drawing.Point(146, 92); this.txtPack.TabIndex = 2; this.txtPack.Text = "0"; this.txtPack.AcceptsReturn = true; this.txtPack.BackColor = System.Drawing.SystemColors.Window; this.txtPack.CausesValidation = true; this.txtPack.Enabled = true; this.txtPack.ForeColor = System.Drawing.SystemColors.WindowText; this.txtPack.HideSelection = true; this.txtPack.ReadOnly = false; this.txtPack.MaxLength = 0; this.txtPack.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtPack.Multiline = false; this.txtPack.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtPack.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtPack.TabStop = true; this.txtPack.Visible = true; this.txtPack.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtPack.Name = "txtPack"; this.txtName.AutoSize = false; this.txtName.Size = new System.Drawing.Size(137, 17); this.txtName.Location = new System.Drawing.Point(92, 44); this.txtName.TabIndex = 0; this.txtName.AcceptsReturn = true; this.txtName.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtName.BackColor = System.Drawing.SystemColors.Window; this.txtName.CausesValidation = true; this.txtName.Enabled = true; this.txtName.ForeColor = System.Drawing.SystemColors.WindowText; this.txtName.HideSelection = true; this.txtName.ReadOnly = false; this.txtName.MaxLength = 0; this.txtName.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtName.Multiline = false; this.txtName.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtName.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtName.TabStop = true; this.txtName.Visible = true; this.txtName.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtName.Name = "txtName"; this.picButtons.Dock = System.Windows.Forms.DockStyle.Top; this.picButtons.BackColor = System.Drawing.Color.Blue; this.picButtons.Size = new System.Drawing.Size(234, 38); this.picButtons.Location = new System.Drawing.Point(0, 0); this.picButtons.TabIndex = 3; this.picButtons.TabStop = false; this.picButtons.CausesValidation = true; this.picButtons.Enabled = true; this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText; this.picButtons.Cursor = System.Windows.Forms.Cursors.Default; this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No; this.picButtons.Visible = true; this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.picButtons.Name = "picButtons"; this.Command2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.Command2.Text = "&Undo"; this.Command2.Size = new System.Drawing.Size(85, 25); this.Command2.Location = new System.Drawing.Point(4, 4); this.Command2.TabIndex = 12; this.Command2.BackColor = System.Drawing.SystemColors.Control; this.Command2.CausesValidation = true; this.Command2.Enabled = true; this.Command2.ForeColor = System.Drawing.SystemColors.ControlText; this.Command2.Cursor = System.Windows.Forms.Cursors.Default; this.Command2.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Command2.TabStop = true; this.Command2.Name = "Command2"; this.Command1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.Command1.Text = "E&xit"; this.Command1.Size = new System.Drawing.Size(87, 25); this.Command1.Location = new System.Drawing.Point(140, 4); this.Command1.TabIndex = 4; this.Command1.BackColor = System.Drawing.SystemColors.Control; this.Command1.CausesValidation = true; this.Command1.Enabled = true; this.Command1.ForeColor = System.Drawing.SystemColors.ControlText; this.Command1.Cursor = System.Windows.Forms.Cursors.Default; this.Command1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Command1.TabStop = true; this.Command1.Name = "Command1"; this.Label4.Text = "Unit/Amount:"; this.Label4.Size = new System.Drawing.Size(77, 15); this.Label4.Location = new System.Drawing.Point(4, 68); this.Label4.TabIndex = 11; this.Label4.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.Label4.BackColor = System.Drawing.Color.Transparent; this.Label4.Enabled = true; this.Label4.ForeColor = System.Drawing.SystemColors.ControlText; this.Label4.Cursor = System.Windows.Forms.Cursors.Default; this.Label4.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label4.UseMnemonic = true; this.Label4.Visible = true; this.Label4.AutoSize = false; this.Label4.BorderStyle = System.Windows.Forms.BorderStyle.None; this.Label4.Name = "Label4"; this.Label3.Text = "Type :"; this.Label3.Size = new System.Drawing.Size(83, 15); this.Label3.Location = new System.Drawing.Point(4, 114); this.Label3.TabIndex = 7; this.Label3.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.Label3.BackColor = System.Drawing.Color.Transparent; this.Label3.Enabled = true; this.Label3.ForeColor = System.Drawing.SystemColors.ControlText; this.Label3.Cursor = System.Windows.Forms.Cursors.Default; this.Label3.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label3.UseMnemonic = true; this.Label3.Visible = true; this.Label3.AutoSize = false; this.Label3.BorderStyle = System.Windows.Forms.BorderStyle.None; this.Label3.Name = "Label3"; this.Label2.Text = "Pack :"; this.Label2.Size = new System.Drawing.Size(83, 15); this.Label2.Location = new System.Drawing.Point(4, 94); this.Label2.TabIndex = 6; this.Label2.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.Label2.BackColor = System.Drawing.Color.Transparent; this.Label2.Enabled = true; this.Label2.ForeColor = System.Drawing.SystemColors.ControlText; this.Label2.Cursor = System.Windows.Forms.Cursors.Default; this.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label2.UseMnemonic = true; this.Label2.Visible = true; this.Label2.AutoSize = false; this.Label2.BorderStyle = System.Windows.Forms.BorderStyle.None; this.Label2.Name = "Label2"; this.Label1.Text = "Name :"; this.Label1.Size = new System.Drawing.Size(83, 15); this.Label1.Location = new System.Drawing.Point(4, 46); this.Label1.TabIndex = 5; this.Label1.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.Label1.BackColor = System.Drawing.Color.Transparent; this.Label1.Enabled = true; this.Label1.ForeColor = System.Drawing.SystemColors.ControlText; this.Label1.Cursor = System.Windows.Forms.Cursors.Default; this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label1.UseMnemonic = true; this.Label1.Visible = true; this.Label1.AutoSize = false; this.Label1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.Label1.Name = "Label1"; this.Controls.Add(txtUnit); this.Controls.Add(Check1); this.Controls.Add(_optCoin_1); this.Controls.Add(_optCoin_0); this.Controls.Add(txtPack); this.Controls.Add(txtName); this.Controls.Add(picButtons); this.Controls.Add(Label4); this.Controls.Add(Label3); this.Controls.Add(Label2); this.Controls.Add(Label1); this.picButtons.Controls.Add(Command2); this.picButtons.Controls.Add(Command1); //Me.optCoin.SetIndex(_optCoin_1, CType(1, Short)) //Me.optCoin.SetIndex(_optCoin_0, CType(0, Short)) //CType(Me.optCoin, System.ComponentModel.ISupportInitialize).EndInit() this.picButtons.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
/* Copyright (c) 2013, HotDocs Limited Use, modification and redistribution of this source is subject to the New BSD License as set out in LICENSE.TXT. */ using HotDocs.Sdk; using HotDocs.Sdk.Server.Contracts; using HotDocs.Server; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace HotDocs.Sdk.Server { internal delegate string TemplateFilesRetriever(string templateKey, string state); internal delegate Stream TemplatePackageRetriever(string packageID, string state, out bool closeStream); /// <summary> /// The <c>Util</c> class provides some methods needed for this class. Some of those methods are used for a specific implementation of IServices. /// </summary> public class Util { internal static void SafeDeleteFolder(string folder) { if (folder != null && folder != "" && folder[0] != '\\') Directory.Delete(folder, true); } internal static void ParseHdAsmCmdLine(string cmdLine, out string path, out string switches) { path = ""; switches = ""; cmdLine = cmdLine.Trim(); if (cmdLine.Length > 0) { if (cmdLine[0] == '\"') { //Handle the case where the path is defined by quotation marks. int pathEnd = cmdLine.IndexOf('\"'); if (pathEnd == -1) { path = cmdLine.Substring(1, cmdLine.Length - 1); } else { path = cmdLine.Substring(1, pathEnd - 1); switches = cmdLine.Substring(pathEnd + 1, cmdLine.Length - pathEnd - 1); } return; } else { //Finally, we look for switches in the path. int switchStart = cmdLine.IndexOf('/'); if (switchStart == -1) { path = cmdLine; } else { path = cmdLine.Substring(0, switchStart); switches = cmdLine.Substring(switchStart, cmdLine.Length - switchStart); } } ////Remove any folder information from the path, just in case. It's not allowed. //int lastBackSlash = path.LastIndexOf('\\'); //int lastFwdSlash = path.LastIndexOf('/'); //if (lastBackSlash > -1 || lastFwdSlash > -1) //{ // int lastSlash = lastBackSlash > lastFwdSlash ? lastBackSlash : lastFwdSlash; // if (lastSlash >= path.Length - 1) // path = ""; // else // path = path.Substring(lastSlash + 1, path.Length - lastSlash - 1); //} //Remove any extra whitespace. path = path.Trim(); switches = switches.Trim(); } } internal static string DecryptServerString(string templateLocator) { string decryptedString = UtilityTools.DecryptString(templateLocator); int separatorIndex = decryptedString.IndexOf('|'); return (separatorIndex >= 0) ? decryptedString.Substring(0, separatorIndex) : decryptedString; } internal static string ExtractString(BinaryObject obj) { string extractedString; Encoding enc = null; if (obj.DataEncoding != null) { try { enc = System.Text.Encoding.GetEncoding(obj.DataEncoding); } catch (ArgumentException) { enc = null; } } // BinaryObjects containing textual information from the HotDocs web service // should always have DataEncoding set to the official IANA name of a text encoding. // Therefore enc should always be non-null at this point. However, in case of // unexpected input, we include some alternative methods below. System.Diagnostics.Debug.Assert(enc != null); if (enc != null) { extractedString = enc.GetString(obj.Data); } else { using (var ms = new MemoryStream(obj.Data)) { using (var tr = (TextReader)new StreamReader(ms)) { extractedString = tr.ReadToEnd(); } } } // discard BOM if there is one if (extractedString[0] == 0xFEFF) return extractedString.Substring(1); else return extractedString; } internal static void AppendSdkScriptBlock(StringBuilder interview, Template template, InterviewSettings settings) { // Append the SDK specific script block begin interview.AppendLine(); interview.AppendLine("<script type=\"text/javascript\">"); // Append the template locator variable. interview.AppendFormat("HDTemplateLocator=\"{0}\";", template.CreateLocator()); interview.AppendLine(); // Append the interview locale (if the host app has overridden the server default) if (!String.IsNullOrEmpty(settings.Locale)) { interview.AppendFormat("HDInterviewLocale=\"{0}\";", settings.Locale); interview.AppendLine(); } // Append the "Next follows outline" setting (if the host app has overridden the server default) if (settings.NextFollowsOutline != Tristate.Default) { interview.AppendFormat("HDOutlineInOrder={0};", settings.NextFollowsOutline == Tristate.True ? "true" : "false"); interview.AppendLine(); } // Append the "Show all resource buttons" setting (if the host app has overridden the server default) if (settings.ShowAllResourceButtons != Tristate.Default) { interview.AppendFormat("HDShowAllResourceBtns={0};", settings.ShowAllResourceButtons == Tristate.True ? "true" : "false"); interview.AppendLine(); } if ((!string.IsNullOrEmpty(settings.AnswerFileDataServiceUrl) || (settings.CustomDataSources != null))) { // The SDK user has configured some data sources addresses to send down to the browser interview. Append a table // that maps data source names to data service addresses so that the browser will know how to request data for // a data source. // Get the data sources used by the template and all its dependencies. TemplateManifest templateManifest = template.GetManifest(ManifestParseFlags.ParseDataSources | ManifestParseFlags.ParseRecursively); Dictionary<string, string> dataSourceDict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); string address; foreach (DataSource dataSource in templateManifest.DataSources) { address = null; switch (dataSource.Type) { case DataSourceType.AnswerFile: { address = settings.AnswerFileDataServiceUrl; break; } case DataSourceType.Custom: { if (settings.CustomDataSources != null) { settings.CustomDataSources.TryGetValue(dataSource.Name, out address); } break; } } if ((address != null) && !dataSourceDict.ContainsKey(dataSource.Name)) dataSourceDict.Add(dataSource.Name, address); } // Now write out all unique data sources. interview.AppendLine("HDDataSources=["); int i = 0; foreach (var dataSource in dataSourceDict) { interview.AppendFormat("\t{{Name:\"{0}\", Address:\"{1}\"", dataSource.Key, dataSource.Value); interview.AppendLine((i++ < dataSourceDict.Count - 1) ? "}," : "}"); } interview.AppendLine("];"); } // Append the SDK specific script block end interview.AppendLine("</script>"); } internal static string GetInterviewDefinitionUrl(InterviewSettings settings, Template template) { // Start with the base InterviewFilesUrl and see if it already has a query string. // If so, we will just be adding parameters. Otherwise, we will be appending a new query string to the base url. string url = settings.InterviewFilesUrl; url += url.Contains("?") ? "&" : "?"; url += ("loc=" + template.CreateLocator()); return url; } internal static string GetInterviewImageUrl(InterviewSettings settings, Template template) { // This is the same as the interview definition URL, but we also add the type and template parameters to the query string. return GetInterviewDefinitionUrl(settings, template) + "&type=img&template="; } internal static string EmbedImagesInURIs(string fileName) { string html = null; // Loads the html file content from a byte[] html = File.ReadAllText(fileName); string targetFilenameNoExtention = Path.GetFileName(fileName).Replace(Path.GetExtension(fileName), ""); // Iterates looking for images associated with the html file requested. foreach (string img in Directory.EnumerateFiles(Path.GetDirectoryName(fileName))) { string ext = Path.GetExtension(img).ToLower().Remove(0, 1); // Encode only the images that are related to the html file if (Path.GetFileName(img).StartsWith(targetFilenameNoExtention) && ((ext == "jpg") || (ext == "jpeg") || (ext == "gif") || (ext == "png") || (ext == "bmp"))) { // Load the content of the image file byte[] data = File.ReadAllBytes(img); // Replace the html src attribute that points to the image file to its base64 content html = html.Replace(@"src=""" + Path.GetFileName(img), @"src=""data:" + HotDocs.Sdk.Util.GetMimeType(img) + ";base64," + Convert.ToBase64String(data)); // html = html.Replace(@"src=""file://" + img, @"src=""data:" + getImageMimeType(ext) + ";base64," + Convert.ToBase64String(data)); } } return html; } internal static string CreateMimePart(string contentBoundary, string contentType, string contentID, string content, string transferEncoding) { StringBuilder sb = new StringBuilder(); sb.AppendLine(contentBoundary); sb.AppendLine("Content-Type: " + contentType); if (!String.IsNullOrEmpty(transferEncoding)) sb.AppendLine("Content-Transfer-Encoding: " + transferEncoding); if (!String.IsNullOrEmpty(contentID)) sb.AppendLine("Content-ID: " + contentID); sb.AppendLine(); sb.AppendLine(content); sb.AppendLine(); return sb.ToString(); } /// <summary> /// Converts an HTML file into a multi-part MIME string. /// </summary> /// <param name="htmlFileName">The name of the html file that will be converted to a multi-part MIME string.</param> /// <returns>A multi-part MIME string.</returns> internal static string HtmlToMultiPartMime(string htmlFileName) { /* * MIME-Version: 1.0 * Content-Type: multipart/mixed; boundary="frontier" * * This is a message with multiple parts in MIME format. * --frontier * Content-Type: text/plain * * This is the body of the message. * --frontier * Content-Type: application/octet-stream * Content-Transfer-Encoding: base64 * * PGh0bWw+CiAgPGhlYWQ+CiAgPC9oZWFkPgogIDxib2R5PgogICAgPHA+VGhpcyBpcyB0aGUg * Ym9keSBvZiB0aGUgbWVzc2FnZS48L3A+CiAgPC9ib2R5Pgo8L2h0bWw+Cg== * --frontier-- */ StringBuilder result = new StringBuilder(); string html = File.ReadAllText(htmlFileName); // Extract all images from the html document. string imageFilesExpression = @"src=""(.+[.](png|jpg|jpeg|jpe|jfif|gif|bmp|tif|tiff|wmf|ico))[""]"; // Extracts and maps image files to mime multipart sections Dictionary<string, string> imageMapping = (from Match m in Regex.Matches(html, imageFilesExpression, RegexOptions.IgnoreCase) select m.Groups[1].Value).Distinct().ToDictionary(v => v, v => Regex.Replace(Guid.NewGuid().ToString(), "{|}|-", "") + Path.GetExtension(v).ToLower()); // Updates the html image references to use the multipart mapping foreach (KeyValuePair<string, string> pair in imageMapping) html = html.Replace(pair.Key, "cid:" + pair.Value); // Writes the header string boundary = "------=_NextPart_" + Regex.Replace(Guid.NewGuid().ToString(), "{|}", ""); result.AppendLine("MIME-Version: 1.0"); result.AppendLine("Content-Type: multipart/related; boundary=\"" + boundary + "\";"); result.AppendLine(); result.AppendLine("This is a multi-part message in MIME format."); result.AppendLine(); // Write the content parts boundary = "--" + boundary; // Appends the HTML result.Append(CreateMimePart(boundary, "text/html; charset=utf-8", null, html, null)); // Appends all the image files foreach (KeyValuePair<string, string> pair in imageMapping) { result.Append(CreateMimePart(boundary, HotDocs.Sdk.Util.GetMimeType(Path.GetExtension(pair.Key)), "<" + pair.Value + ">", Convert.ToBase64String(File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(htmlFileName), pair.Key))), "base64" )); } // End of the content result.Append(boundary + "--"); return result.ToString(); } private class DataSourceNameEqualityCompararer : IEqualityComparer<string> { #region IEqualityComparer<string> Members public bool Equals(string x, string y) { return string.Equals(x, y, StringComparison.OrdinalIgnoreCase); } public int GetHashCode(string obj) { return obj.ToLower().GetHashCode(); } #endregion } /// <summary> /// Reads the bytes from a text reader and returns them in a BinaryObject. /// </summary> /// <param name="textReader">A text reader.</param> /// <returns>A BinaryObject containing the contents of the text reader.</returns> internal static BinaryObject GetBinaryObjectFromTextReader(TextReader textReader) { string allText = textReader.ReadToEnd(); return new BinaryObject { Data = Encoding.UTF8.GetBytes(allText), DataEncoding = "UTF-8" }; } /// <summary> /// This method returns the requested runtime file from the ServerFiles cache. If the file can be found in either the cache or the /// source URL, it is returned in the response. Otherwise, nothing is done with the response and the method returns false to indicate failure. /// </summary> /// <param name="fileName">The name of the file.</param> /// <param name="cacheFolder">The folder where the file is cached.</param> /// <param name="sourceUrl">The URL where the file can be found if it does not exist in the cache.</param> /// <param name="contentType">Output parameter containing the MIME type of requested runtime file.</param> /// <returns>A <c>Stream</c> containing the runtime file.</returns> public static Stream GetInterviewRuntimeFile(string fileName, string cacheFolder, string sourceUrl, out string contentType) { // Validate and normalize input parameters. if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(cacheFolder) || string.IsNullOrEmpty(sourceUrl)) throw new ArgumentNullException(); try { // Construct the full file path to the cached file, and create its parent folder(s) if necessary. string cachedFilePath = Path.Combine(cacheFolder, fileName.Replace('/', '\\')); string cachedFileDirectory = Path.GetDirectoryName(cachedFilePath); if (!Directory.Exists(cachedFileDirectory)) { Directory.CreateDirectory(cachedFileDirectory); } // Construct the full source URL of the requested file. // The source of cloud services files (files.hotdocs.ws) is case-sensitive, so always make the folders in the // URL lowercase if we are getting it from there! We don't make everything lowercase because some files (e.g., Silverlight.js) // contain capital letters. string sourceFileUrl = sourceUrl.TrimEnd('/') + "/" + fileName; if (sourceFileUrl.IndexOf("files.hotdocs.ws") > 0) { int lastForwardSlash = sourceFileUrl.LastIndexOf('/'); sourceFileUrl = sourceFileUrl.Substring(0, lastForwardSlash).ToLower() + sourceFileUrl.Substring(lastForwardSlash); } System.Net.WebRequest myRequest; if (File.Exists(cachedFilePath)) { // There is a matching file in the cache. See if it is up to date or not. FileInfo fInfo = new FileInfo(cachedFilePath); if (fInfo.LastWriteTimeUtc < DateTime.UtcNow.AddDays(-1)) { // The file is more than 1 day old, so we can re-check now. // Check to see if we need to get a new version of the file from the server. myRequest = System.Net.WebRequest.Create(sourceFileUrl); myRequest.Method = "HEAD"; using (System.Net.WebResponse myResponse = myRequest.GetResponse()) { string lastMod = myResponse.Headers["Last-Modified"]; DateTime serverFileDate = DateTime.Parse(lastMod); if (fInfo.CreationTimeUtc != serverFileDate.ToUniversalTime()) { // The creation time of our local file is not the same as the last modification date // of the server file, so we are out of sync. Delete the local file and get a new one. File.SetAttributes(cachedFilePath, FileAttributes.Normal); File.Delete(cachedFilePath); } else { // Set the modification date to Now so we won't check for at least 24 more hours. File.SetLastWriteTimeUtc(cachedFilePath, DateTime.UtcNow); } } } } if (!File.Exists(cachedFilePath)) { // Either the file did not exist in the cache from the start, or we deleted it because it was out of date. // In any case, it does not exist, so we need to request it from the source URL and save it to our cache folder. myRequest = System.Net.WebRequest.Create(sourceFileUrl); myRequest.Method = "GET"; using (System.Net.WebResponse myResponse = myRequest.GetResponse()) { using (FileStream writeStream = new FileStream(cachedFilePath, FileMode.Create, FileAccess.Write)) using (Stream readStream = myResponse.GetResponseStream()) { readStream.CopyTo(writeStream); } // Set the creation time of the locally cached file to the last modification date from the server file. // We use this time to compare with the server's file during future requests to see if it matches or not. File.SetCreationTimeUtc(cachedFilePath, DateTime.Parse(myResponse.Headers["Last-Modified"]).ToUniversalTime()); } } contentType = HotDocs.Sdk.Util.GetMimeType(cachedFilePath); if (File.Exists(cachedFilePath)) { // The locally cached file is either less than 24 hours old or we got the latest one from the source URL. // We can return it in the response. return new FileStream(cachedFilePath, FileMode.Open, FileAccess.Read); } else { // If we could not find the file, give the user a HTTP_STATUS_NOT_FOUND error. return null; } } catch { // Something really bad happened. contentType = null; return null; } } /// <summary> /// This method is used by both WS and Cloud implementations of AssembleDocument to convert an AssemblyResult to an AssembleDocumentResult. /// </summary> /// <param name="template">The template associated with the <c>AssemblyResult</c>.</param> /// <param name="asmResult">The <c>AssemblyResult</c> to convert.</param> /// <param name="docType">The type of document contained in the result.</param> /// <returns>An <c>AssembleDocumentResult</c>, which contains the same document as the <c>asmResult</c>.</returns> internal static AssembleDocumentResult ConvertAssemblyResult(Template template, AssemblyResult asmResult, DocumentType docType) { AssembleDocumentResult result = null; MemoryStream document = null; StreamReader ansRdr = null; List<NamedStream> supportingFiles = new List<NamedStream>(); // Create the list of pending assemblies. IEnumerable<Template> pendingAssemblies = asmResult.PendingAssemblies == null ? new List<Template>() : from pa in asmResult.PendingAssemblies select new Template( Path.GetFileName(pa.TemplateName), template.Location.Duplicate(), pa.Switches); for (int i = 0; i < asmResult.Documents.Length; i++) { switch (asmResult.Documents[i].Format) { case OutputFormat.Answers: ansRdr = new StreamReader(new MemoryStream(asmResult.Documents[i].Data)); break; case OutputFormat.JPEG: case OutputFormat.PNG: // If the output document is plain HTML, we might also get additional image files in the // AssemblyResult that we need to pass on to the caller. supportingFiles.Add(new NamedStream(asmResult.Documents[i].FileName, new MemoryStream(asmResult.Documents[i].Data))); break; default: document = new MemoryStream(asmResult.Documents[i].Data); if (docType == DocumentType.Native) { docType = Document.GetDocumentType(asmResult.Documents[i].FileName); } break; } } result = new AssembleDocumentResult( document == null ? null : new Document(template, document, docType, supportingFiles.ToArray(), asmResult.UnansweredVariables), ansRdr == null ? null : ansRdr.ReadToEnd(), pendingAssemblies.ToArray(), asmResult.UnansweredVariables ); return result; } } }
using System; using System.Reflection; using FileHelpers.Converters; namespace FileHelpers { /// <summary>Indicates the <see cref="ConverterKind"/> used for read/write operations.</summary> /// <remarks>See the <a href="http://www.filehelpers.net/mustread">Complete attributes list</a> for more information and examples of each one.</remarks> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class FieldConverterAttribute : Attribute { #region " Constructors " /// <summary>Indicates the <see cref="ConverterKind"/> used for read/write operations. </summary> /// <param name="converter">The <see cref="ConverterKind"/> used for the transformations.</param> public FieldConverterAttribute(ConverterKind converter) : this(converter, new string[] {}) {} /// <summary>Indicates the <see cref="ConverterKind"/> used for read/write operations. </summary> /// <param name="converter">The <see cref="ConverterKind"/> used for the transformations.</param> /// <param name="arg1">The first param passed directly to the Converter Constructor.</param> public FieldConverterAttribute(ConverterKind converter, string arg1) : this(converter, new string[] {arg1}) {} /// <summary>Indicates the <see cref="ConverterKind"/> used for read/write operations. </summary> /// <param name="converter">The <see cref="ConverterKind"/> used for the transformations.</param> /// <param name="arg1">The first param passed directly to the Converter Constructor.</param> /// <param name="arg2">The second param passed directly to the Converter Constructor.</param> public FieldConverterAttribute(ConverterKind converter, string arg1, string arg2) : this(converter, new string[] {arg1, arg2}) {} /// <summary>Indicates the <see cref="ConverterKind"/> used for read/write operations. </summary> /// <param name="converter">The <see cref="ConverterKind"/> used for the transformations.</param> /// <param name="arg1">The first param passed directly to the Converter Constructor.</param> /// <param name="arg2">The second param passed directly to the Converter Constructor.</param> /// <param name="arg3">The third param passed directly to the Converter Constructor.</param> public FieldConverterAttribute(ConverterKind converter, string arg1, string arg2, string arg3) : this(converter, new string[] {arg1, arg2, arg3}) {} /// <summary> /// Indicates the <see cref="ConverterKind"/> used for read/write operations. /// </summary> /// <param name="converter">The <see cref="ConverterKind"/> used for the transformations.</param> /// <param name="args">An array of parameters passed directly to the Converter</param> private FieldConverterAttribute(ConverterKind converter, params string[] args) { Kind = converter; Type convType; switch (converter) { case ConverterKind.Date: convType = typeof (DateTimeConverter); break; case ConverterKind.DateMultiFormat: convType = typeof (DateTimeMultiFormatConverter); break; case ConverterKind.Byte: convType = typeof (ByteConverter); break; case ConverterKind.SByte: convType = typeof (SByteConverter); break; case ConverterKind.Int16: convType = typeof (Int16Converter); break; case ConverterKind.Int32: convType = typeof (Int32Converter); break; case ConverterKind.Int64: convType = typeof (Int64Converter); break; case ConverterKind.UInt16: convType = typeof (UInt16Converter); break; case ConverterKind.UInt32: convType = typeof (UInt32Converter); break; case ConverterKind.UInt64: convType = typeof (UInt64Converter); break; case ConverterKind.Decimal: convType = typeof (DecimalConverter); break; case ConverterKind.Double: convType = typeof (DoubleConverter); break; // Added by Shreyas Narasimhan 17 March 2010 case ConverterKind.PercentDouble: convType = typeof (PercentDoubleConverter); break; case ConverterKind.Single: convType = typeof (SingleConverter); break; case ConverterKind.Boolean: convType = typeof (BooleanConverter); break; // Added by Alexander Obolonkov 2007.11.08 case ConverterKind.Char: convType = typeof (CharConverter); break; // Added by Alexander Obolonkov 2007.11.08 case ConverterKind.Guid: convType = typeof (GuidConverter); break; default: throw new BadUsageException("Converter '" + converter.ToString() + "' not found, you must specify a valid converter."); } //mType = type; CreateConverter(convType, args); } /// <summary>Indicates a custom <see cref="ConverterBase"/> implementation.</summary> /// <param name="customConverter">The Type of your custom converter.</param> /// <param name="arg1">The first param passed directly to the Converter Constructor.</param> public FieldConverterAttribute(Type customConverter, string arg1) : this(customConverter, new string[] {arg1}) {} /// <summary>Indicates a custom <see cref="ConverterBase"/> implementation.</summary> /// <param name="customConverter">The Type of your custom converter.</param> /// <param name="arg1">The first param passed directly to the Converter Constructor.</param> /// <param name="arg2">The second param passed directly to the Converter Constructor.</param> public FieldConverterAttribute(Type customConverter, string arg1, string arg2) : this(customConverter, new string[] {arg1, arg2}) {} /// <summary>Indicates a custom <see cref="ConverterBase"/> implementation.</summary> /// <param name="customConverter">The Type of your custom converter.</param> /// <param name="arg1">The first param passed directly to the Converter Constructor.</param> /// <param name="arg2">The second param passed directly to the Converter Constructor.</param> /// <param name="arg3">The third param passed directly to the Converter Constructor.</param> public FieldConverterAttribute(Type customConverter, string arg1, string arg2, string arg3) : this(customConverter, new string[] {arg1, arg2, arg3}) {} /// <summary>Indicates a custom <see cref="ConverterBase"/> implementation.</summary> /// <param name="customConverter">The Type of your custom converter.</param> /// <param name="args">A list of params passed directly to your converter constructor.</param> public FieldConverterAttribute(Type customConverter, params object[] args) { CreateConverter(customConverter, args); } /// <summary>Indicates a custom <see cref="ConverterBase"/> implementation.</summary> /// <param name="customConverter">The Type of your custom converter.</param> public FieldConverterAttribute(Type customConverter) { CreateConverter(customConverter, new object[] {}); } #endregion #region " Converter " /// <summary>The final concrete converter used for FieldToString and StringToField operations </summary> public ConverterBase Converter { get; private set; } /// <summary>The <see cref="ConverterKind"/> if a default converter is used </summary> public ConverterKind Kind { get; private set; } #endregion #region " CreateConverter " private void CreateConverter(Type convType, object[] args) { if (typeof(ConverterBase).IsAssignableFrom(convType)) { ConstructorInfo constructor; constructor = convType.GetConstructor( BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic, null, ArgsToTypes(args), null); if (constructor == null) { if (args.Length == 0) { throw new BadUsageException("Empty constructor for converter: " + convType.Name + " was not found. You must add a constructor without args (can be public or private)"); } else { throw new BadUsageException("Constructor for converter: " + convType.Name + " with these arguments: (" + ArgsDesc(args) + ") was not found. You must add a constructor with this signature (can be public or private)"); } } try { Converter = (ConverterBase)constructor.Invoke(args); } catch (TargetInvocationException ex) { throw ex.InnerException; } } else if (convType.IsEnum) if (args.Length == 0) Converter = new EnumConverter(convType); else Converter = new EnumConverter(convType, args[0] as string); else throw new BadUsageException("The custom converter must inherit from ConverterBase"); } #endregion #region " ArgsToTypes " private static Type[] ArgsToTypes(object[] args) { if (args == null) { throw new BadUsageException( "The args to the constructor can be null if you do not want to pass anything into them."); } var res = new Type[args.Length]; for (int i = 0; i < args.Length; i++) { if (args[i] == null) res[i] = typeof (object); else res[i] = args[i].GetType(); } return res; } private static string ArgsDesc(object[] args) { string res = DisplayType(args[0]); for (int i = 1; i < args.Length; i++) res += ", " + DisplayType(args[i]); return res; } private static string DisplayType(object o) { if (o == null) return "Object"; else return o.GetType().Name; } #endregion internal void ValidateTypes(FieldInfo fi) { bool valid = false; Type fieldType = fi.FieldType; if (fieldType.IsValueType && fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof (Nullable<>)) fieldType = fieldType.GetGenericArguments()[0]; switch (Kind) { case ConverterKind.None: valid = true; break; case ConverterKind.Date: case ConverterKind.DateMultiFormat: valid = typeof (DateTime) == fieldType; break; case ConverterKind.Byte: case ConverterKind.SByte: case ConverterKind.Int16: case ConverterKind.Int32: case ConverterKind.Int64: case ConverterKind.UInt16: case ConverterKind.UInt32: case ConverterKind.UInt64: case ConverterKind.Decimal: case ConverterKind.Double: case ConverterKind.Single: case ConverterKind.Boolean: case ConverterKind.Char: case ConverterKind.Guid: valid = Kind.ToString() == fieldType.UnderlyingSystemType.Name; break; case ConverterKind.PercentDouble: valid = typeof (double) == fieldType; break; } if (valid == false) { throw new BadUsageException( "The converter of the field: '" + fi.Name + "' is wrong. The field is of Type: " + fieldType.Name + " and the converter is for type: " + Kind.ToString()); } } } }
using System; using System.IO; using System.Web.Http; using Aspose.Note.Live.Demos.UI.Models; using System.Threading.Tasks; using Aspose.Note.Live.Demos.UI.Config; using System.IO.Compression; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; using System.Drawing.Imaging; using System.Drawing; using System.Net; using System.Linq; using Aspose.Note.Live.Demos.UI.Helpers; namespace Aspose.Note.Live.Demos.UI.Controllers { ///<Summary> /// AsposeViewerController class to get document page ///</Summary> public class AsposeViewerController : ApiController { ///<Summary> /// GetDocumentPage method to get document page ///</Summary> [HttpGet] public HttpResponseMessage GetDocumentPage( string file, string folderName, int currentPage) { string outfileName = Path.GetFileNameWithoutExtension(file) + "_{0}"; string outPath = Config.Configuration.OutputDirectory + folderName + "/" + outfileName; currentPage = currentPage - 1; string imagePath = string.Format(outPath, currentPage) + ".jpeg"; Directory.CreateDirectory(Config.Configuration.OutputDirectory + folderName); if (System.IO.File.Exists(imagePath)) { return GetImageFromPath(imagePath); } return null; } ///<Summary> /// DocumentPages method to get document pages ///</Summary> [HttpGet] public List<string> DocumentPages( string file, string folderName, int currentPage) { List<string> output; try { output = GetDocumentPages( file, folderName, currentPage); } catch (Exception ex) { throw ex; } return output; } private List<string> GetDocumentPages(string file, string folderName, int currentPage) { List<string> lstOutput = new List<string>(); string outfileName = "page_{0}"; string outPath = Config.Configuration.OutputDirectory + folderName + "/" + outfileName; currentPage = currentPage - 1; Directory.CreateDirectory(Config.Configuration.OutputDirectory + folderName); string imagePath = string.Format(outPath, currentPage) + ".jpeg"; if (System.IO.File.Exists(imagePath) && currentPage > 0) { lstOutput.Add(imagePath); return lstOutput; } int i = currentPage; var filename = System.IO.File.Exists(Config.Configuration.WorkingDirectory + folderName + "/" + file) ? Config.Configuration.WorkingDirectory + folderName + "/" + file : Config.Configuration.OutputDirectory + folderName + "/" + file; using (FilePathLock.Use(filename)) { try { Aspose.Note.Live.Demos.UI.Models.License.SetAsposeNoteLicense(); // Load the document from disk. Aspose.Note.Document doc = new Aspose.Note.Document(filename); Aspose.Note.Saving.ImageSaveOptions options = new Aspose.Note.Saving.ImageSaveOptions(Aspose.Note.SaveFormat.Jpeg); // Save each page of the document as image. options.PageIndex = currentPage; doc.Save(imagePath, options); lstOutput.Add(doc.GetChildNodes<Aspose.Note.Page>().Count.ToString()); lstOutput.Add(imagePath); return lstOutput; } catch (Exception ex) { throw ex; } } } ///<Summary> /// DownloadDocument method to download document ///</Summary> [HttpGet] public HttpResponseMessage DownloadDocument(string file, string folderName, bool isImage) { string outfileName = Path.GetFileNameWithoutExtension(file) + "_Out.zip"; string outPath; if (!isImage) { if (System.IO.File.Exists(Config.Configuration.WorkingDirectory + folderName + "/" + file)) outPath = Config.Configuration.WorkingDirectory + folderName + "/" + file; else outPath = Config.Configuration.OutputDirectory + folderName + "/" + file; } else { outPath = Config.Configuration.OutputDirectory + outfileName; } using (FilePathLock.Use(outPath)) { if (isImage) { if (System.IO.File.Exists(outPath)) System.IO.File.Delete(outPath); List<string> lst = GetDocumentPages(file, folderName, 1); if (lst.Count > 1) { int tmpPageCount = int.Parse(lst[0]); for (int i = 2; i <= tmpPageCount; i++) { GetDocumentPages( file, folderName, i); } } ZipFile.CreateFromDirectory(Config.Configuration.OutputDirectory + folderName + "/", outPath); } if ((!System.IO.File.Exists(outPath)) || !Path.GetFullPath(outPath).StartsWith(Path.GetFullPath( System.Web.HttpContext.Current.Server.MapPath("~/Assets/")))) { var exception = new HttpResponseException(HttpStatusCode.NotFound); throw exception; } try { using (var fileStream = new FileStream(outPath, FileMode.Open, FileAccess.Read)) { using (var ms = new MemoryStream()) { fileStream.CopyTo(ms); var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(ms.ToArray()) }; result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = (isImage ? outfileName : file) }; result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); return result; } } } catch (Exception x) { Console.WriteLine(x.Message); } } return null; } ///<Summary> /// PageImage method to get page image ///</Summary> [HttpGet] public HttpResponseMessage PageImage(string imagePath) { return GetImageFromPath(imagePath); } private HttpResponseMessage GetImageFromPath(string imagePath) { HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); FileStream fileStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read); System.Drawing.Image image = System.Drawing.Image.FromStream(fileStream); MemoryStream memoryStream = new MemoryStream(); image.Save(memoryStream, ImageFormat.Jpeg); result.Content = new ByteArrayContent(memoryStream.ToArray()); result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg"); fileStream.Close(); 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.Data.Odbc; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Text; internal static partial class Interop { internal static partial class Odbc { // // ODBC32 // [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLAllocHandle( /*SQLSMALLINT*/ODBC32.SQL_HANDLE HandleType, /*SQLHANDLE*/IntPtr InputHandle, /*SQLHANDLE* */out IntPtr OutputHandle); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLAllocHandle( /*SQLSMALLINT*/ODBC32.SQL_HANDLE HandleType, /*SQLHANDLE*/OdbcHandle InputHandle, /*SQLHANDLE* */out IntPtr OutputHandle); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLBindCol( /*SQLHSTMT*/OdbcStatementHandle StatementHandle, /*SQLUSMALLINT*/ushort ColumnNumber, /*SQLSMALLINT*/ODBC32.SQL_C TargetType, /*SQLPOINTER*/HandleRef TargetValue, /*SQLLEN*/IntPtr BufferLength, /*SQLLEN* */IntPtr StrLen_or_Ind); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLBindCol( /*SQLHSTMT*/OdbcStatementHandle StatementHandle, /*SQLUSMALLINT*/ushort ColumnNumber, /*SQLSMALLINT*/ODBC32.SQL_C TargetType, /*SQLPOINTER*/IntPtr TargetValue, /*SQLLEN*/IntPtr BufferLength, /*SQLLEN* */IntPtr StrLen_or_Ind); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLBindParameter( /*SQLHSTMT*/OdbcStatementHandle StatementHandle, /*SQLUSMALLINT*/ushort ParameterNumber, /*SQLSMALLINT*/short ParamDirection, /*SQLSMALLINT*/ODBC32.SQL_C SQLCType, /*SQLSMALLINT*/short SQLType, /*SQLULEN*/IntPtr cbColDef, /*SQLSMALLINT*/IntPtr ibScale, /*SQLPOINTER*/HandleRef rgbValue, /*SQLLEN*/IntPtr BufferLength, /*SQLLEN* */HandleRef StrLen_or_Ind); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLCancel( /*SQLHSTMT*/OdbcStatementHandle StatementHandle); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLCloseCursor( /*SQLHSTMT*/OdbcStatementHandle StatementHandle); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLColAttributeW( /*SQLHSTMT*/OdbcStatementHandle StatementHandle, /*SQLUSMALLINT*/short ColumnNumber, /*SQLUSMALLINT*/short FieldIdentifier, /*SQLPOINTER*/CNativeBuffer CharacterAttribute, /*SQLSMALLINT*/short BufferLength, /*SQLSMALLINT* */out short StringLength, /*SQLPOINTER*/out IntPtr NumericAttribute); // note: in sql.h this is defined differently for the 64Bit platform. // However, for us the code is not different for SQLPOINTER or SQLLEN ... // frome sql.h: // #ifdef _WIN64 // SQLRETURN SQL_API SQLColAttribute (SQLHSTMT StatementHandle, // SQLUSMALLINT ColumnNumber, SQLUSMALLINT FieldIdentifier, // SQLPOINTER CharacterAttribute, SQLSMALLINT BufferLength, // SQLSMALLINT *StringLength, SQLLEN *NumericAttribute); // #else // SQLRETURN SQL_API SQLColAttribute (SQLHSTMT StatementHandle, // SQLUSMALLINT ColumnNumber, SQLUSMALLINT FieldIdentifier, // SQLPOINTER CharacterAttribute, SQLSMALLINT BufferLength, // SQLSMALLINT *StringLength, SQLPOINTER NumericAttribute); // #endif [DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLColumnsW( /*SQLHSTMT*/OdbcStatementHandle StatementHandle, /*SQLCHAR* */string CatalogName, /*SQLSMALLINT*/short NameLen1, /*SQLCHAR* */string SchemaName, /*SQLSMALLINT*/short NameLen2, /*SQLCHAR* */string TableName, /*SQLSMALLINT*/short NameLen3, /*SQLCHAR* */string ColumnName, /*SQLSMALLINT*/short NameLen4); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLDisconnect( /*SQLHDBC*/IntPtr ConnectionHandle); [DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLDriverConnectW( /*SQLHDBC*/OdbcConnectionHandle hdbc, /*SQLHWND*/IntPtr hwnd, /*SQLCHAR* */string connectionstring, /*SQLSMALLINT*/short cbConnectionstring, /*SQLCHAR* */IntPtr connectionstringout, /*SQLSMALLINT*/short cbConnectionstringoutMax, /*SQLSMALLINT* */out short cbConnectionstringout, /*SQLUSMALLINT*/short fDriverCompletion); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLEndTran( /*SQLSMALLINT*/ODBC32.SQL_HANDLE HandleType, /*SQLHANDLE*/IntPtr Handle, /*SQLSMALLINT*/short CompletionType); [DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLExecDirectW( /*SQLHSTMT*/OdbcStatementHandle StatementHandle, /*SQLCHAR* */string StatementText, /*SQLINTEGER*/int TextLength); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLExecute( /*SQLHSTMT*/OdbcStatementHandle StatementHandle); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLFetch( /*SQLHSTMT*/OdbcStatementHandle StatementHandle); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLFreeHandle( /*SQLSMALLINT*/ODBC32.SQL_HANDLE HandleType, /*SQLHSTMT*/IntPtr StatementHandle); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLFreeStmt( /*SQLHSTMT*/OdbcStatementHandle StatementHandle, /*SQLUSMALLINT*/ODBC32.STMT Option); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLGetConnectAttrW( /*SQLHBDC*/OdbcConnectionHandle ConnectionHandle, /*SQLINTEGER*/ODBC32.SQL_ATTR Attribute, /*SQLPOINTER*/byte[] Value, /*SQLINTEGER*/int BufferLength, /*SQLINTEGER* */out int StringLength); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLGetData( /*SQLHSTMT*/OdbcStatementHandle StatementHandle, /*SQLUSMALLINT*/ushort ColumnNumber, /*SQLSMALLINT*/ODBC32.SQL_C TargetType, /*SQLPOINTER*/CNativeBuffer TargetValue, /*SQLLEN*/IntPtr BufferLength, // sql.h differs from MSDN /*SQLLEN* */out IntPtr StrLen_or_Ind); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLGetDescFieldW( /*SQLHSTMT*/OdbcDescriptorHandle StatementHandle, /*SQLUSMALLINT*/short RecNumber, /*SQLUSMALLINT*/ODBC32.SQL_DESC FieldIdentifier, /*SQLPOINTER*/CNativeBuffer ValuePointer, /*SQLINTEGER*/int BufferLength, /*SQLINTEGER* */out int StringLength); [DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLGetDiagRecW( /*SQLSMALLINT*/ODBC32.SQL_HANDLE HandleType, /*SQLHANDLE*/OdbcHandle Handle, /*SQLSMALLINT*/short RecNumber, /*SQLCHAR* */ [Out] StringBuilder rchState, /*SQLINTEGER* */out int NativeError, /*SQLCHAR* */ [Out] StringBuilder MessageText, /*SQLSMALLINT*/short BufferLength, /*SQLSMALLINT* */out short TextLength); [DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLGetDiagFieldW( /*SQLSMALLINT*/ ODBC32.SQL_HANDLE HandleType, /*SQLHANDLE*/ OdbcHandle Handle, /*SQLSMALLINT*/ short RecNumber, /*SQLSMALLINT*/ short DiagIdentifier, /*SQLPOINTER*/ [Out] StringBuilder rchState, /*SQLSMALLINT*/ short BufferLength, /*SQLSMALLINT* */ out short StringLength); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLGetFunctions( /*SQLHBDC*/OdbcConnectionHandle hdbc, /*SQLUSMALLINT*/ODBC32.SQL_API fFunction, /*SQLUSMALLINT* */out short pfExists); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLGetInfoW( /*SQLHBDC*/OdbcConnectionHandle hdbc, /*SQLUSMALLINT*/ODBC32.SQL_INFO fInfoType, /*SQLPOINTER*/byte[] rgbInfoValue, /*SQLSMALLINT*/short cbInfoValueMax, /*SQLSMALLINT* */out short pcbInfoValue); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLGetInfoW( /*SQLHBDC*/OdbcConnectionHandle hdbc, /*SQLUSMALLINT*/ODBC32.SQL_INFO fInfoType, /*SQLPOINTER*/byte[] rgbInfoValue, /*SQLSMALLINT*/short cbInfoValueMax, /*SQLSMALLINT* */IntPtr pcbInfoValue); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLGetStmtAttrW( /*SQLHSTMT*/OdbcStatementHandle StatementHandle, /*SQLINTEGER*/ODBC32.SQL_ATTR Attribute, /*SQLPOINTER*/out IntPtr Value, /*SQLINTEGER*/int BufferLength, /*SQLINTEGER*/out int StringLength); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLGetTypeInfo( /*SQLHSTMT*/OdbcStatementHandle StatementHandle, /*SQLSMALLINT*/short fSqlType); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLMoreResults( /*SQLHSTMT*/OdbcStatementHandle StatementHandle); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLNumResultCols( /*SQLHSTMT*/OdbcStatementHandle StatementHandle, /*SQLSMALLINT* */out short ColumnCount); [DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLPrepareW( /*SQLHSTMT*/OdbcStatementHandle StatementHandle, /*SQLCHAR* */string StatementText, /*SQLINTEGER*/int TextLength); [DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLPrimaryKeysW( /*SQLHSTMT*/OdbcStatementHandle StatementHandle, /*SQLCHAR* */string CatalogName, /*SQLSMALLINT*/short NameLen1, /*SQLCHAR* */ string SchemaName, /*SQLSMALLINT*/short NameLen2, /*SQLCHAR* */string TableName, /*SQLSMALLINT*/short NameLen3); [DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLProcedureColumnsW( /*SQLHSTMT*/OdbcStatementHandle StatementHandle, /*SQLCHAR* */ string CatalogName, /*SQLSMALLINT*/short NameLen1, /*SQLCHAR* */ string SchemaName, /*SQLSMALLINT*/short NameLen2, /*SQLCHAR* */ string ProcName, /*SQLSMALLINT*/short NameLen3, /*SQLCHAR* */ string ColumnName, /*SQLSMALLINT*/short NameLen4); [DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLProceduresW( /*SQLHSTMT*/OdbcStatementHandle StatementHandle, /*SQLCHAR* */ string CatalogName, /*SQLSMALLINT*/short NameLen1, /*SQLCHAR* */ string SchemaName, /*SQLSMALLINT*/short NameLen2, /*SQLCHAR* */ string ProcName, /*SQLSMALLINT*/short NameLen3); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLRowCount( /*SQLHSTMT*/OdbcStatementHandle StatementHandle, /*SQLLEN* */out IntPtr RowCount); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLSetConnectAttrW( /*SQLHBDC*/OdbcConnectionHandle ConnectionHandle, /*SQLINTEGER*/ODBC32.SQL_ATTR Attribute, /*SQLPOINTER*/System.Transactions.IDtcTransaction Value, /*SQLINTEGER*/int StringLength); [DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLSetConnectAttrW( /*SQLHBDC*/OdbcConnectionHandle ConnectionHandle, /*SQLINTEGER*/ODBC32.SQL_ATTR Attribute, /*SQLPOINTER*/string Value, /*SQLINTEGER*/int StringLength); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLSetConnectAttrW( /*SQLHBDC*/OdbcConnectionHandle ConnectionHandle, /*SQLINTEGER*/ODBC32.SQL_ATTR Attribute, /*SQLPOINTER*/IntPtr Value, /*SQLINTEGER*/int StringLength); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLSetConnectAttrW( // used only for AutoCommitOn /*SQLHBDC*/IntPtr ConnectionHandle, /*SQLINTEGER*/ODBC32.SQL_ATTR Attribute, /*SQLPOINTER*/IntPtr Value, /*SQLINTEGER*/int StringLength); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLSetDescFieldW( /*SQLHSTMT*/OdbcDescriptorHandle StatementHandle, /*SQLSMALLINT*/short ColumnNumber, /*SQLSMALLINT*/ODBC32.SQL_DESC FieldIdentifier, /*SQLPOINTER*/HandleRef CharacterAttribute, /*SQLINTEGER*/int BufferLength); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLSetDescFieldW( /*SQLHSTMT*/OdbcDescriptorHandle StatementHandle, /*SQLSMALLINT*/short ColumnNumber, /*SQLSMALLINT*/ODBC32.SQL_DESC FieldIdentifier, /*SQLPOINTER*/IntPtr CharacterAttribute, /*SQLINTEGER*/int BufferLength); [DllImport(Interop.Libraries.Odbc32)] // user can set SQL_ATTR_CONNECTION_POOLING attribute with envHandle = null, this attribute is process-level attribute internal static extern /*SQLRETURN*/ODBC32.RetCode SQLSetEnvAttr( /*SQLHENV*/OdbcEnvironmentHandle EnvironmentHandle, /*SQLINTEGER*/ODBC32.SQL_ATTR Attribute, /*SQLPOINTER*/IntPtr Value, /*SQLINTEGER*/ODBC32.SQL_IS StringLength); [DllImport(Interop.Libraries.Odbc32)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLSetStmtAttrW( /*SQLHSTMT*/OdbcStatementHandle StatementHandle, /*SQLINTEGER*/int Attribute, /*SQLPOINTER*/IntPtr Value, /*SQLINTEGER*/int StringLength); [DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLSpecialColumnsW( /*SQLHSTMT*/OdbcStatementHandle StatementHandle, /*SQLUSMALLINT*/ODBC32.SQL_SPECIALCOLS IdentifierType, /*SQLCHAR* */string CatalogName, /*SQLSMALLINT*/short NameLen1, /*SQLCHAR* */string SchemaName, /*SQLSMALLINT*/short NameLen2, /*SQLCHAR* */string TableName, /*SQLSMALLINT*/short NameLen3, /*SQLUSMALLINT*/ODBC32.SQL_SCOPE Scope, /*SQLUSMALLINT*/ ODBC32.SQL_NULLABILITY Nullable); [DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLStatisticsW( /*SQLHSTMT*/OdbcStatementHandle StatementHandle, /*SQLCHAR* */string CatalogName, /*SQLSMALLINT*/short NameLen1, /*SQLCHAR* */string SchemaName, /*SQLSMALLINT*/short NameLen2, /*SQLCHAR* */IntPtr TableName, // IntPtr instead of string because callee may mutate contents /*SQLSMALLINT*/short NameLen3, /*SQLUSMALLINT*/short Unique, /*SQLUSMALLINT*/short Reserved); [DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLTablesW( /*SQLHSTMT*/OdbcStatementHandle StatementHandle, /*SQLCHAR* */string CatalogName, /*SQLSMALLINT*/short NameLen1, /*SQLCHAR* */string SchemaName, /*SQLSMALLINT*/short NameLen2, /*SQLCHAR* */string TableName, /*SQLSMALLINT*/short NameLen3, /*SQLCHAR* */string TableType, /*SQLSMALLINT*/short NameLen4); } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace ClrHeapAllocationAnalyzer { [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(AvoidAllocationWithArrayEmptyCodeFix)), Shared] public class AvoidAllocationWithArrayEmptyCodeFix : CodeFixProvider { private const string RemoveUnnecessaryListCreation = "Avoid allocation by using Array.Empty<>()"; public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(ExplicitAllocationAnalyzer.NewObjectRule.Id, ExplicitAllocationAnalyzer.NewArrayRule.Id); public sealed override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); var diagnostic = context.Diagnostics.First(); var diagnosticSpan = diagnostic.Location.SourceSpan; var node = root.FindNode(diagnosticSpan); if (IsReturnStatement(node)) { await TryToRegisterCodeFixesForReturnStatement(context, node, diagnostic); return; } if (IsMethodInvocationParameter(node)) { await TryToRegisterCodeFixesForMethodInvocationParameter(context, node, diagnostic); return; } } private async Task TryToRegisterCodeFixesForMethodInvocationParameter(CodeFixContext context, SyntaxNode node, Diagnostic diagnostic) { var semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken); if (IsExpectedParameterReadonlySequence(node, semanticModel) && node is ArgumentSyntax argument) { TryRegisterCodeFix(context, node, diagnostic, argument.Expression, semanticModel); } } private async Task TryToRegisterCodeFixesForReturnStatement(CodeFixContext context, SyntaxNode node, Diagnostic diagnostic) { var semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken); if (IsInsideMemberReturningEnumerable(node, semanticModel)) { TryRegisterCodeFix(context, node, diagnostic, node, semanticModel); } } private void TryRegisterCodeFix(CodeFixContext context, SyntaxNode node, Diagnostic diagnostic, SyntaxNode creationExpression, SemanticModel semanticModel) { switch (creationExpression) { case ObjectCreationExpressionSyntax objectCreation: { if (CanBeReplaceWithEnumerableEmpty(objectCreation, semanticModel)) { if (objectCreation.Type is GenericNameSyntax genericName) { var codeAction = CodeAction.Create(RemoveUnnecessaryListCreation, token => Transform(context.Document, node, genericName.TypeArgumentList.Arguments[0], token), RemoveUnnecessaryListCreation); context.RegisterCodeFix(codeAction, diagnostic); } } } break; case ArrayCreationExpressionSyntax arrayCreation: { if (CanBeReplaceWithEnumerableEmpty(arrayCreation)) { var codeAction = CodeAction.Create(RemoveUnnecessaryListCreation, token => Transform(context.Document, node, arrayCreation.Type.ElementType, token), RemoveUnnecessaryListCreation); context.RegisterCodeFix(codeAction, diagnostic); } } break; } } private bool IsMethodInvocationParameter(SyntaxNode node) => node is ArgumentSyntax; private static bool IsReturnStatement(SyntaxNode node) { return node.Parent is ReturnStatementSyntax || node.Parent is YieldStatementSyntax || node.Parent is ArrowExpressionClauseSyntax; } private bool IsInsideMemberReturningEnumerable(SyntaxNode node, SemanticModel semanticModel) { return IsInsideMethodReturningEnumerable(node, semanticModel) || IsInsidePropertyDeclaration(node, semanticModel); } private bool IsInsidePropertyDeclaration(SyntaxNode node, SemanticModel semanticModel) { if(node.FindContainer<PropertyDeclarationSyntax>() is PropertyDeclarationSyntax propertyDeclaration && IsPropertyTypeReadonlySequence(semanticModel, propertyDeclaration)) { return IsAutoPropertyWithGetter(node) || IsArrowExpression(node); } return false; } private bool IsAutoPropertyWithGetter(SyntaxNode node) { if(node.FindContainer<AccessorDeclarationSyntax>() is AccessorDeclarationSyntax accessorDeclaration) { return accessorDeclaration.Keyword.Text == "get"; } return false; } private bool IsArrowExpression(SyntaxNode node) { return node.FindContainer<ArrowExpressionClauseSyntax>() != null; } private bool CanBeReplaceWithEnumerableEmpty(ArrayCreationExpressionSyntax arrayCreation) { return IsInitializationBlockEmpty(arrayCreation.Initializer); } private bool CanBeReplaceWithEnumerableEmpty(ObjectCreationExpressionSyntax objectCreation, SemanticModel semanticModel) { return IsCollectionType(semanticModel, objectCreation) && IsInitializationBlockEmpty(objectCreation.Initializer) && IsCopyConstructor(semanticModel, objectCreation) == false; } private static bool IsInsideMethodReturningEnumerable(SyntaxNode node, SemanticModel semanticModel) { if (node.FindContainer<MethodDeclarationSyntax>() is MethodDeclarationSyntax methodDeclaration) { if (IsReturnTypeReadonlySequence(semanticModel, methodDeclaration)) { return true; } } return false; } private async Task<Document> Transform(Document contextDocument, SyntaxNode node, TypeSyntax typeArgument, CancellationToken cancellationToken) { var noAllocation = SyntaxFactory.ParseExpression($"Array.Empty<{typeArgument}>()"); var newNode = ReplaceExpression(node, noAllocation); if (newNode == null) { return contextDocument; } var syntaxRootAsync = await contextDocument.GetSyntaxRootAsync(cancellationToken); var newSyntaxRoot = syntaxRootAsync.ReplaceNode(node.Parent, newNode); return contextDocument.WithSyntaxRoot(newSyntaxRoot); } private SyntaxNode ReplaceExpression(SyntaxNode node, ExpressionSyntax newExpression) { switch (node.Parent) { case ReturnStatementSyntax parentReturn: return parentReturn.WithExpression(newExpression); case ArrowExpressionClauseSyntax arrowStatement: return arrowStatement.WithExpression(newExpression); case ArgumentListSyntax argumentList: var newArguments = argumentList.Arguments.Select(x => x == node ? SyntaxFactory.Argument(newExpression) : x); return argumentList.WithArguments(SyntaxFactory.SeparatedList(newArguments)); default: return null; } } private bool IsCopyConstructor(SemanticModel semanticModel, ObjectCreationExpressionSyntax objectCreation) { if (objectCreation.ArgumentList == null || objectCreation.ArgumentList.Arguments.Count == 0) { return false; } if (semanticModel.GetSymbolInfo(objectCreation).Symbol is IMethodSymbol methodSymbol) { if (methodSymbol.Parameters.Any(x=> x.Type is INamedTypeSymbol namedType && IsCollectionType(namedType))) { return true; } } return false; } private static bool IsInitializationBlockEmpty(InitializerExpressionSyntax initializer) { return initializer == null || initializer.Expressions.Count == 0; } private bool IsCollectionType(SemanticModel semanticModel, ObjectCreationExpressionSyntax objectCreationExpressionSyntax) { return semanticModel.GetTypeInfo(objectCreationExpressionSyntax).Type is INamedTypeSymbol createdType && (createdType.TypeKind == TypeKind.Array || IsCollectionType(createdType) ); } private bool IsCollectionType(INamedTypeSymbol typeSymbol) { return typeSymbol.ConstructedFrom.Interfaces.Any(x => x.IsGenericType && x.ToString().StartsWith("System.Collections.Generic.ICollection")); } private static bool IsPropertyTypeReadonlySequence(SemanticModel semanticModel, PropertyDeclarationSyntax propertyDeclaration) { return IsTypeReadonlySequence(semanticModel, propertyDeclaration.Type); } private static bool IsReturnTypeReadonlySequence(SemanticModel semanticModel, MethodDeclarationSyntax methodDeclarationSyntax) { var typeSyntax = methodDeclarationSyntax.ReturnType; return IsTypeReadonlySequence(semanticModel, typeSyntax); } private bool IsExpectedParameterReadonlySequence(SyntaxNode node, SemanticModel semanticModel) { if (node is ArgumentSyntax argument && node.Parent is ArgumentListSyntax argumentList) { var argumentIndex = argumentList.Arguments.IndexOf(argument); if (semanticModel.GetSymbolInfo(argumentList.Parent).Symbol is IMethodSymbol methodSymbol) { if (methodSymbol.Parameters.Length > argumentIndex) { var parameterType = methodSymbol.Parameters[argumentIndex].Type; if (IsTypeReadonlySequence(semanticModel, parameterType)) { return true; } } } } return false; } private static bool IsTypeReadonlySequence(SemanticModel semanticModel, TypeSyntax typeSyntax) { var returnType = ModelExtensions.GetTypeInfo(semanticModel, typeSyntax).Type; return IsTypeReadonlySequence(semanticModel, returnType); } private static bool IsTypeReadonlySequence(SemanticModel semanticModel, ITypeSymbol type) { if (type.Kind == SymbolKind.ArrayType) { return true; } if (type is INamedTypeSymbol namedType && namedType.IsGenericType) { foreach (var readonlySequence in GetReadonlySequenceTypes(semanticModel)) { if (readonlySequence.Equals(namedType.ConstructedFrom)) { return true; } } } return false; } private static IEnumerable<INamedTypeSymbol> GetReadonlySequenceTypes(SemanticModel semanticModel) { yield return semanticModel.Compilation.GetTypeByMetadataName("System.Collections.Generic.IEnumerable`1"); yield return semanticModel.Compilation.GetTypeByMetadataName("System.Collections.Generic.IReadOnlyList`1"); yield return semanticModel.Compilation.GetTypeByMetadataName("System.Collections.Generic.IReadOnlyCollection`1"); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the MIT License. See LICENSE.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; using System.Globalization; using System.Xml.Serialization; using System.IO; namespace CodeGen { namespace Effects { public class EnumValue { [XmlAttribute("name")] public string Name { get; set; } [XmlAttribute("displayname")] public string Displayname { get; set; } public override bool Equals(object obj) { EnumValue value = obj as EnumValue; return (value != null) && (Name == value.Name); } public override int GetHashCode() { return Name.GetHashCode(); } } public class EnumValues { public EnumValues() { Usage = UsageType.UsedByOneEffect; IsRepresentative = false; } [XmlIgnore] public Enum D2DEnum { get; set; } public enum UsageType { UsedByOneEffect, UsedByMultipleEffects } public UsageType Usage; public bool IsRepresentative { get; set; } [XmlElement("Field")] public List<EnumValue> FieldsList { get; set; } } public class Property { public Property() { ShouldProject = true; } [XmlAttribute("name")] public string Name { get; set; } [XmlAttribute("type")] public string Type { get; set; } [XmlAttribute("value")] public string Value { get; set; } [XmlElement("Property")] public List<Property> Properties { get; set; } // Used only for enum types [XmlElement("Fields")] public EnumValues EnumFields { get; set; } public string EffectName { get; set; } public string TypeNameIdl { get; set; } public string TypeNameCpp { get; set; } public string TypeNameBoxed { get; set; } public bool IsArray { get; set; } public bool ShouldProject { get; set; } public bool IsHidden { get; set; } public bool IsHandCoded { get; set; } public bool ConvertRadiansToDegrees { get; set; } public string NativePropertyName { get; set; } public string WinVer { get; set; } public List<string> ExcludedEnumIndexes { get; set; } } public class Input { [XmlAttribute("name")] public string Name { get; set; } [XmlAttribute("minimum")] public string Minimum { get; set; } [XmlAttribute("maximum")] public string Maximum { get; set; } } public class Inputs { [XmlElement("Input")] public List<Input> InputsList { get; set; } [XmlAttribute("minimum")] public string Minimum { get; set; } [XmlAttribute("maximum")] public string Maximum { get; set; } } [XmlRoot("Effect")] public class Effect { [XmlElement("Property")] public List<Property> Properties { get; set; } [XmlElement("Inputs")] public Inputs Inputs { get; set; } public string ClassName { get; set; } public string InterfaceName { get; set; } public string Uuid { get; set; } [XmlIgnore] public Overrides.XmlBindings.Effect Overrides { get; set; } } public class D2DEnum { public D2DEnum() { Enums = new SortedDictionary<int, string>(); } public string Name { get; set; } public SortedDictionary<int, string> Enums { get; set; } } } public static class EffectGenerator { public static void OutputEffects(string inputEffectsDir, Dictionary<string, QualifiableType> typeDictionary, string outputPath) { string[] filePaths = Directory.GetFiles(inputEffectsDir); var overridesXmlData = XmlBindings.Utilities.LoadXmlData<Overrides.XmlBindings.Settings>(inputEffectsDir, "../../Settings.xml"); List<Effects.Effect> effects = new List<Effects.Effect>(); foreach (var xmlFilePath in filePaths) { effects.Add(ParseEffectXML(xmlFilePath)); } string windowsKitPath = Environment.ExpandEnvironmentVariables(@"%WindowsSdkDir%"); // Check if %WindowsSdkDir% path is set if (!Directory.Exists(windowsKitPath)) { // Try the default path windowsKitPath = @"C:\Program Files (x86)\Windows Kits\8.1"; if (!Directory.Exists(windowsKitPath)) { throw new Exception(@"Missing WindowsSdkDir environment variable. Please run this application from VS command prompt"); } } List<string> d2dHeaders = new List<string> { windowsKitPath + @"/Include/um/d2d1effects.h", windowsKitPath + @"/Include/um/d2d1_1.h" }; AssignEffectsNamesToProperties(effects); DetectCommonEnums(effects); AssignPropertyNames(effects); var overrides = overridesXmlData.Namespaces.Find(namespaceElement => namespaceElement.Name == "Effects"); List<Enum> d2dEnums = ParseD2DEffectsEnums(d2dHeaders, typeDictionary); // Put the known enums into typeDictionary. AssignD2DEnums(effects, d2dEnums); AssignEffectsClassNames(effects, overrides.Effects, typeDictionary); ResolveTypeNames(effects); RegisterUuids(effects); OverrideEnums(overrides.Enums, effects); GenerateOutput(effects, outputPath); } // Register effect uuids. These are generated by hashing the interface name following RFC 4122. private static void RegisterUuids(List<Effects.Effect> effects) { var salt = new Guid("8DEBAF20-F852-4B20-BE55-4D7EA6DE19BE"); foreach (var effect in effects) { var name = "Microsoft.Graphics.Canvas.Effects." + effect.InterfaceName; var uuid = UuidHelper.GetVersion5Uuid(salt, name); effect.Uuid = uuid.ToString().ToUpper(); } } public static bool IsEffectEnabled(Effects.Effect effect) { switch (effect.Properties[0].Value) { // TODO #2648: figure out how to project effects that output computation results rather than images. case "Histogram": return false; default: return true; } } private static List<Effects.Property> GetAllEffectsProperties(List<Effects.Effect> effects) { List<Effects.Property> allProperties = new List<Effects.Property>(); foreach (var effect in effects) { foreach (var property in effect.Properties) { allProperties.Add(property); } } return allProperties; } private static void AssignEffectsNamesToProperties(List<Effects.Effect> effects) { foreach (var effect in effects) { foreach (var property in effect.Properties) { // Zero property in xml effect description corresponds to effect name property.EffectName = effect.Properties[0].Value; } } } private static void OverrideEnums(List<Overrides.XmlBindings.Enum> enumsOverrides, List<Effects.Effect> effects) { foreach (var property in GetAllEffectsProperties(effects)) { var enumOverride = enumsOverrides.Find(element => element.Name == property.TypeNameIdl); if (enumOverride != null) { if (enumOverride.ProjectedNameOverride != null) { property.TypeNameIdl = enumOverride.ProjectedNameOverride; if (enumOverride.Namespace != null) { property.TypeNameIdl = enumOverride.Namespace + "." + property.TypeNameIdl; } property.TypeNameCpp = enumOverride.ProjectedNameOverride; } property.ShouldProject = enumOverride.ShouldProject; property.WinVer = enumOverride.WinVer; foreach (var enumValue in enumOverride.Values) { if (!enumValue.ShouldProject && property.ExcludedEnumIndexes != null) { property.ExcludedEnumIndexes.Add(enumValue.Index); } if (enumValue.ProjectedNameOverride != null) { var enumToOverride = property.EnumFields.FieldsList.Find(enumEntry => enumEntry.Name == enumValue.Name); if (enumToOverride != null) { enumToOverride.Name = enumValue.ProjectedNameOverride; } } } } } } private static void ResolveTypeNames(List<Effects.Effect> effects) { var typeRenames = new Dictionary<string, string[]> { // D2D name IDL name C++ name { "bool", new string[] { "boolean", "boolean" } }, { "int32", new string[] { "INT32", "int32_t" } }, { "uint32", new string[] { "INT32", "int32_t" } }, }; foreach (var property in GetAllEffectsProperties(effects)) { if (property.TypeNameIdl != null) { string xmlName = property.TypeNameIdl; if (typeRenames.ContainsKey(xmlName)) { // Specially remapped type, where D2D format XML files don't match WinRT type naming. property.TypeNameIdl = typeRenames[xmlName][0]; property.TypeNameCpp = typeRenames[xmlName][1]; property.TypeNameBoxed = typeRenames[xmlName][1]; } else if (xmlName.StartsWith("matrix") || xmlName.StartsWith("vector")) { if (property.Name.Contains("Rect")) { // D2D passes rectangle properties as float4, but we remap them to use strongly typed Rect. property.TypeNameIdl = "Windows.Foundation.Rect"; property.TypeNameCpp = "Rect"; } else if (property.Name.Contains("Color") && xmlName.StartsWith("vector")) { // D2D passes color properties as float3 or float4, but we remap them to use strongly typed Color. property.TypeNameIdl = "Windows.UI.Color"; property.TypeNameCpp = "Color"; } else { // Vector or matrix type. property.TypeNameIdl = char.ToUpper(xmlName[0]) + xmlName.Substring(1); property.TypeNameCpp = property.TypeNameIdl; // Matrix5x4 is defined locally as part of Effects, but other math types live in the Numerics namespace. if (!xmlName.Contains("5x4")) { property.TypeNameIdl = "NUMERICS." + property.TypeNameIdl; property.TypeNameCpp = "Numerics::" + property.TypeNameCpp; } } // Convert eg. "matrix3x2" to 6, or "vector3" to 3. var sizeSuffix = xmlName.SkipWhile(char.IsLetter).ToArray(); var sizeElements = new string(sizeSuffix).Split('x').Select(int.Parse); var size = sizeElements.Aggregate((a, b) => a * b); property.TypeNameBoxed = "float[" + size + "]"; } else if (xmlName == "blob") { // The D2D "blob" type projects as an array of floats. property.TypeNameIdl = "float"; property.TypeNameCpp = "float"; property.TypeNameBoxed = "float"; property.IsArray = true; } else { // Any other type. property.TypeNameCpp = xmlName; property.TypeNameBoxed = xmlName; // Enums are internally stored as uints. if (property.Type == "enum") { property.TypeNameBoxed = "uint32_t"; } } } } } // Determine if enums are unique to specific effect // or general for all effects private static void DetectCommonEnums(List<Effects.Effect> effects) { List<Effects.Property> allProperties = GetAllEffectsProperties(effects); for (int propertyIndex = 0; propertyIndex < allProperties.Count; propertyIndex++) { Effects.EnumValues fields = allProperties[propertyIndex].EnumFields; if (fields == null || fields.Usage != Effects.EnumValues.UsageType.UsedByOneEffect) continue; for (int propertyIndex2 = propertyIndex + 1; propertyIndex2 < allProperties.Count; propertyIndex2++) { Effects.EnumValues fields2 = allProperties[propertyIndex2].EnumFields; if (fields2 == null) continue; // Allow merging if either enum is a subset of the values of the other, // but not if their value sets are distinct in both directions. var delta1 = fields.FieldsList.Except(fields2.FieldsList); var delta2 = fields2.FieldsList.Except(fields.FieldsList); if (!delta1.Any() || !delta2.Any()) { fields.Usage = Effects.EnumValues.UsageType.UsedByMultipleEffects; fields.IsRepresentative = true; fields2.Usage = Effects.EnumValues.UsageType.UsedByMultipleEffects; fields2.FieldsList = fields.FieldsList; // Exclude any enum values that are supported by one enum but not the other. allProperties[propertyIndex2].ExcludedEnumIndexes.AddRange(delta1.Select(field => fields.FieldsList.IndexOf(field).ToString())); allProperties[propertyIndex].ExcludedEnumIndexes.AddRange(delta2.Select(field => fields2.FieldsList.IndexOf(field).ToString())); } } } } private static void AssignPropertyNames(List<Effects.Effect> effects) { foreach (var property in GetAllEffectsProperties(effects)) { string className = property.EffectName.Replace(" ", "") + "Effect"; property.TypeNameIdl = property.Type; if (property.TypeNameIdl == "enum") { if (property.EnumFields.Usage == Effects.EnumValues.UsageType.UsedByMultipleEffects) property.TypeNameIdl = "Effect" + property.Name; else { Debug.Assert(property.EnumFields.Usage == Effects.EnumValues.UsageType.UsedByOneEffect); property.TypeNameIdl = className + property.Name; } } property.NativePropertyName = "D2D1_" + property.EffectName.Replace(" ", "").Replace("-", "").ToUpper() + "_PROP"; foreach (Char c in property.Name) { if (Char.IsUpper(c)) { property.NativePropertyName += "_"; } property.NativePropertyName += c.ToString().ToUpper(); } } } // Some effects have names that starts with 3D or 2D prefix. // C++ forbidds class name that starts with digits // Replace 3D/2D prefix at the end private static void AssignEffectsClassNames( List<Effects.Effect> effects, List<Overrides.XmlBindings.Effect> overrides, Dictionary<string, QualifiableType> typeDictionary) { foreach (var effect in effects) { string className = FormatClassName(effect.Properties[0].Value); string prefix = className.Substring(0, 2); if (prefix == "2D" || prefix == "3D") { effect.ClassName = className.Remove(0, 2) + prefix + "Effect"; } else { effect.ClassName = className + "Effect"; } // Apply effect and property name overrides based on XML settings var effectOverride = overrides.Find(o => o.Name == effect.ClassName); if (effectOverride != null) { ApplyEffectOverrides(effect, effectOverride, typeDictionary); } effect.InterfaceName = "I" + effect.ClassName; } } private static void ApplyEffectOverrides(Effects.Effect effect, Overrides.XmlBindings.Effect effectOverride, Dictionary<string, QualifiableType> typeDictionary) { effect.Overrides = effectOverride; // Override the effect name? if (effectOverride.ProjectedNameOverride != null) { effect.ClassName = effectOverride.ProjectedNameOverride; } // Override input names? foreach (var inputOverride in effectOverride.Inputs) { var input = effect.Inputs.InputsList.Find(p => p.Name == inputOverride.Name); input.Name = inputOverride.ProjectedNameOverride; } foreach (var propertyOverride in effectOverride.Properties) { var property = effect.Properties.Find(p => p.Name == propertyOverride.Name); if (property != null) { // Override settings of an existing property. if (propertyOverride.ProjectedNameOverride != null) { property.Name = propertyOverride.ProjectedNameOverride; } if (propertyOverride.DefaultValueOverride != null) { var defaultProperty = property.Properties.Single(p => p.Name == "Default"); defaultProperty.Value = propertyOverride.DefaultValueOverride; } property.IsHidden = propertyOverride.IsHidden; property.ConvertRadiansToDegrees = propertyOverride.ConvertRadiansToDegrees; } if (property == null || propertyOverride.IsHandCoded) { // Add a custom property that is part of our API surface but not defined by D2D. effect.Properties.Add(new Effects.Property { Name = propertyOverride.ProjectedNameOverride ?? propertyOverride.Name, TypeNameIdl = string.IsNullOrEmpty(propertyOverride.Type) ? property.TypeNameIdl : propertyOverride.Type, IsHandCoded = true }); // If we are masking a real D2D property with an alternative // hand-coded version, mark the real D2D property as hidden. if (property != null) { property.IsHidden = true; } } } } private static List<Enum> ParseD2DEffectsEnums(List<string> pathsToHeaders, Dictionary<string, QualifiableType> typeDictionary) { List<Enum> d2dEnums = new List<Enum>(); foreach (var path in pathsToHeaders) { StreamReader reader = File.OpenText(path); string line; while ((line = reader.ReadLine()) != null) { if (line.Contains("typedef enum") && line.Substring(line.Length - 4) != "PROP") { char[] separator = { ' ' }; string[] words = line.Split(separator, StringSplitOptions.RemoveEmptyEntries); string enumName = words[words.Length - 1]; // Skip brace reader.ReadLine(); List<EnumValue> enumValues = new List<EnumValue>(); while ((line = reader.ReadLine()) != "") { words = line.TrimEnd(',').Split(separator, StringSplitOptions.RemoveEmptyEntries); // Looking for definitions of the form "EnumEntry = value" if (words.Length == 3 && words[1] == "=" && !words[0].StartsWith("//") && !words[0].Contains("FORCE_DWORD")) { NumberStyles numberStyle = 0; if (words[2].StartsWith("0x")) { words[2] = words[2].Substring(2); numberStyle = NumberStyles.HexNumber; } int value; if (!int.TryParse(words[2], numberStyle, null, out value)) { value = enumValues.Count; } string nativeValueName = words[0]; Debug.Assert(nativeValueName.StartsWith("D2D1_")); string rawValueNameComponent = nativeValueName.Substring(5); enumValues.Add(new EnumValue(nativeValueName, rawValueNameComponent, value)); } } Debug.Assert(enumName.StartsWith("D2D1_")); enumName = enumName.Substring(5); Enum effectEnum; string key = "D2D1::" + enumName; if(typeDictionary.ContainsKey(key)) { effectEnum = typeDictionary[key] as Enum; } else { effectEnum = new Enum(enumName, enumValues, typeDictionary); } d2dEnums.Add(effectEnum); } } } return d2dEnums; } private static bool IsEnumEqualD2DEnum(Effects.Property enumProperty, Enum d2dEnum, bool shouldMatchName) { // Check if names are the same if (FormatEnumValueString(d2dEnum.NativeName).Contains(FormatEnumValueString(enumProperty.EffectName)) || !shouldMatchName) { // Check if number of enums values are the same if (d2dEnum.Values.Count == enumProperty.EnumFields.FieldsList.Count) { var d2dEnumValues = d2dEnum.Values; for (int i = 0; i < enumProperty.EnumFields.FieldsList.Count; ++i) { if (!FormatEnumValueString(d2dEnumValues[i].NativeName).Contains(FormatEnumValueString(enumProperty.EnumFields.FieldsList[i].Displayname))) { return false; } } return true; } } return false; } private static void AssignD2DEnums(List<Effects.Effect> effects, List<Enum> d2dEnums) { foreach (var property in GetAllEffectsProperties(effects)) { Effects.EnumValues fields = property.EnumFields; if (fields == null) continue; // Try to find enum for specific effect foreach (var d2dEnum in d2dEnums) { if (IsEnumEqualD2DEnum(property, d2dEnum, true)) { fields.D2DEnum = d2dEnum; } } // If failed to find enum for specific effect, try general if (fields.D2DEnum == null) { // Try to find enum without name matching foreach (var d2dEnum in d2dEnums) { if (IsEnumEqualD2DEnum(property, d2dEnum, false)) { fields.D2DEnum = d2dEnum; } } } } } private static void GenerateOutput(List<Effects.Effect> effects, string outDirectory) { using (Formatter commonStreamWriter = new Formatter(Path.Combine(outDirectory, "EffectsCommon.abi.idl"))) { OutputEffectType.OutputCommonEnums(effects, commonStreamWriter); } foreach (var effect in effects.Where(IsEffectEnabled)) { Directory.CreateDirectory(outDirectory); using (Formatter idlStreamWriter = new Formatter(Path.Combine(outDirectory, effect.ClassName + ".abi.idl")), hStreamWriter = new Formatter(Path.Combine(outDirectory, effect.ClassName + ".h")), cppStreamWriter = new Formatter(Path.Combine(outDirectory, effect.ClassName + ".cpp"))) { OutputEffectType.OutputEffectIdl(effect, idlStreamWriter); OutputEffectType.OutputEffectHeader(effect, hStreamWriter); OutputEffectType.OutputEffectCpp(effect, cppStreamWriter); } } } private static string FormatEnumValueString(string inString) { string result = inString.Replace("_", ""); result = result.Replace(" ", ""); result = result.Replace("-", ""); result = result.ToLower(); return result; } public static string FormatClassName(string name) { return name.Replace(" ", "") .Replace("-", "") .Replace("DPI", "Dpi") .Replace("toAlpha", "ToAlpha"); } private static Effects.Effect ParseEffectXML(string path) { Effects.Effect effect = null; XmlSerializer serializer = new XmlSerializer(typeof(Effects.Effect)); using (StreamReader reader = new StreamReader(path)) { effect = (Effects.Effect)serializer.Deserialize(reader); } return effect; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V9.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V9.Services { /// <summary>Settings for <see cref="CustomerAssetServiceClient"/> instances.</summary> public sealed partial class CustomerAssetServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="CustomerAssetServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="CustomerAssetServiceSettings"/>.</returns> public static CustomerAssetServiceSettings GetDefault() => new CustomerAssetServiceSettings(); /// <summary>Constructs a new <see cref="CustomerAssetServiceSettings"/> object with default settings.</summary> public CustomerAssetServiceSettings() { } private CustomerAssetServiceSettings(CustomerAssetServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetCustomerAssetSettings = existing.GetCustomerAssetSettings; MutateCustomerAssetsSettings = existing.MutateCustomerAssetsSettings; OnCopy(existing); } partial void OnCopy(CustomerAssetServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>CustomerAssetServiceClient.GetCustomerAsset</c> and <c>CustomerAssetServiceClient.GetCustomerAssetAsync</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 GetCustomerAssetSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>CustomerAssetServiceClient.MutateCustomerAssets</c> and /// <c>CustomerAssetServiceClient.MutateCustomerAssetsAsync</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 MutateCustomerAssetsSettings { 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="CustomerAssetServiceSettings"/> object.</returns> public CustomerAssetServiceSettings Clone() => new CustomerAssetServiceSettings(this); } /// <summary> /// Builder class for <see cref="CustomerAssetServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class CustomerAssetServiceClientBuilder : gaxgrpc::ClientBuilderBase<CustomerAssetServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public CustomerAssetServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public CustomerAssetServiceClientBuilder() { UseJwtAccessWithScopes = CustomerAssetServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref CustomerAssetServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CustomerAssetServiceClient> task); /// <summary>Builds the resulting client.</summary> public override CustomerAssetServiceClient Build() { CustomerAssetServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<CustomerAssetServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<CustomerAssetServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private CustomerAssetServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return CustomerAssetServiceClient.Create(callInvoker, Settings); } private async stt::Task<CustomerAssetServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return CustomerAssetServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => CustomerAssetServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => CustomerAssetServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => CustomerAssetServiceClient.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>CustomerAssetService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage customer assets. /// </remarks> public abstract partial class CustomerAssetServiceClient { /// <summary> /// The default endpoint for the CustomerAssetService 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 CustomerAssetService scopes.</summary> /// <remarks> /// The default CustomerAssetService 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="CustomerAssetServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="CustomerAssetServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="CustomerAssetServiceClient"/>.</returns> public static stt::Task<CustomerAssetServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new CustomerAssetServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="CustomerAssetServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="CustomerAssetServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="CustomerAssetServiceClient"/>.</returns> public static CustomerAssetServiceClient Create() => new CustomerAssetServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="CustomerAssetServiceClient"/> 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="CustomerAssetServiceSettings"/>.</param> /// <returns>The created <see cref="CustomerAssetServiceClient"/>.</returns> internal static CustomerAssetServiceClient Create(grpccore::CallInvoker callInvoker, CustomerAssetServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } CustomerAssetService.CustomerAssetServiceClient grpcClient = new CustomerAssetService.CustomerAssetServiceClient(callInvoker); return new CustomerAssetServiceClientImpl(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 CustomerAssetService client</summary> public virtual CustomerAssetService.CustomerAssetServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested customer asset in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::CustomerAsset GetCustomerAsset(GetCustomerAssetRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested customer asset in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::CustomerAsset> GetCustomerAssetAsync(GetCustomerAssetRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested customer asset in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::CustomerAsset> GetCustomerAssetAsync(GetCustomerAssetRequest request, st::CancellationToken cancellationToken) => GetCustomerAssetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested customer asset in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the customer asset to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::CustomerAsset GetCustomerAsset(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetCustomerAsset(new GetCustomerAssetRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested customer asset in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the customer asset to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::CustomerAsset> GetCustomerAssetAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetCustomerAssetAsync(new GetCustomerAssetRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested customer asset in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the customer asset to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::CustomerAsset> GetCustomerAssetAsync(string resourceName, st::CancellationToken cancellationToken) => GetCustomerAssetAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested customer asset in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the customer asset to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::CustomerAsset GetCustomerAsset(gagvr::CustomerAssetName resourceName, gaxgrpc::CallSettings callSettings = null) => GetCustomerAsset(new GetCustomerAssetRequest { ResourceNameAsCustomerAssetName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested customer asset in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the customer asset to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::CustomerAsset> GetCustomerAssetAsync(gagvr::CustomerAssetName resourceName, gaxgrpc::CallSettings callSettings = null) => GetCustomerAssetAsync(new GetCustomerAssetRequest { ResourceNameAsCustomerAssetName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested customer asset in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the customer asset to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::CustomerAsset> GetCustomerAssetAsync(gagvr::CustomerAssetName resourceName, st::CancellationToken cancellationToken) => GetCustomerAssetAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes customer assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [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 MutateCustomerAssetsResponse MutateCustomerAssets(MutateCustomerAssetsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes customer assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [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<MutateCustomerAssetsResponse> MutateCustomerAssetsAsync(MutateCustomerAssetsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes customer assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [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<MutateCustomerAssetsResponse> MutateCustomerAssetsAsync(MutateCustomerAssetsRequest request, st::CancellationToken cancellationToken) => MutateCustomerAssetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes customer assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose customer assets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual customer assets. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateCustomerAssetsResponse MutateCustomerAssets(string customerId, scg::IEnumerable<CustomerAssetOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateCustomerAssets(new MutateCustomerAssetsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes customer assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose customer assets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual customer assets. /// </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<MutateCustomerAssetsResponse> MutateCustomerAssetsAsync(string customerId, scg::IEnumerable<CustomerAssetOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateCustomerAssetsAsync(new MutateCustomerAssetsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes customer assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose customer assets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual customer assets. /// </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<MutateCustomerAssetsResponse> MutateCustomerAssetsAsync(string customerId, scg::IEnumerable<CustomerAssetOperation> operations, st::CancellationToken cancellationToken) => MutateCustomerAssetsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>CustomerAssetService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage customer assets. /// </remarks> public sealed partial class CustomerAssetServiceClientImpl : CustomerAssetServiceClient { private readonly gaxgrpc::ApiCall<GetCustomerAssetRequest, gagvr::CustomerAsset> _callGetCustomerAsset; private readonly gaxgrpc::ApiCall<MutateCustomerAssetsRequest, MutateCustomerAssetsResponse> _callMutateCustomerAssets; /// <summary> /// Constructs a client wrapper for the CustomerAssetService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="CustomerAssetServiceSettings"/> used within this client.</param> public CustomerAssetServiceClientImpl(CustomerAssetService.CustomerAssetServiceClient grpcClient, CustomerAssetServiceSettings settings) { GrpcClient = grpcClient; CustomerAssetServiceSettings effectiveSettings = settings ?? CustomerAssetServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetCustomerAsset = clientHelper.BuildApiCall<GetCustomerAssetRequest, gagvr::CustomerAsset>(grpcClient.GetCustomerAssetAsync, grpcClient.GetCustomerAsset, effectiveSettings.GetCustomerAssetSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetCustomerAsset); Modify_GetCustomerAssetApiCall(ref _callGetCustomerAsset); _callMutateCustomerAssets = clientHelper.BuildApiCall<MutateCustomerAssetsRequest, MutateCustomerAssetsResponse>(grpcClient.MutateCustomerAssetsAsync, grpcClient.MutateCustomerAssets, effectiveSettings.MutateCustomerAssetsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateCustomerAssets); Modify_MutateCustomerAssetsApiCall(ref _callMutateCustomerAssets); 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_GetCustomerAssetApiCall(ref gaxgrpc::ApiCall<GetCustomerAssetRequest, gagvr::CustomerAsset> call); partial void Modify_MutateCustomerAssetsApiCall(ref gaxgrpc::ApiCall<MutateCustomerAssetsRequest, MutateCustomerAssetsResponse> call); partial void OnConstruction(CustomerAssetService.CustomerAssetServiceClient grpcClient, CustomerAssetServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC CustomerAssetService client</summary> public override CustomerAssetService.CustomerAssetServiceClient GrpcClient { get; } partial void Modify_GetCustomerAssetRequest(ref GetCustomerAssetRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_MutateCustomerAssetsRequest(ref MutateCustomerAssetsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested customer asset in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::CustomerAsset GetCustomerAsset(GetCustomerAssetRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetCustomerAssetRequest(ref request, ref callSettings); return _callGetCustomerAsset.Sync(request, callSettings); } /// <summary> /// Returns the requested customer asset in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::CustomerAsset> GetCustomerAssetAsync(GetCustomerAssetRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetCustomerAssetRequest(ref request, ref callSettings); return _callGetCustomerAsset.Async(request, callSettings); } /// <summary> /// Creates, updates, or removes customer assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [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 MutateCustomerAssetsResponse MutateCustomerAssets(MutateCustomerAssetsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateCustomerAssetsRequest(ref request, ref callSettings); return _callMutateCustomerAssets.Sync(request, callSettings); } /// <summary> /// Creates, updates, or removes customer assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [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<MutateCustomerAssetsResponse> MutateCustomerAssetsAsync(MutateCustomerAssetsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateCustomerAssetsRequest(ref request, ref callSettings); return _callMutateCustomerAssets.Async(request, callSettings); } } }
using System; using System.IO; using ChainUtils.BouncyCastle.Asn1; using ChainUtils.BouncyCastle.Asn1.CryptoPro; using ChainUtils.BouncyCastle.Asn1.Oiw; using ChainUtils.BouncyCastle.Asn1.Pkcs; using ChainUtils.BouncyCastle.Asn1.X509; using ChainUtils.BouncyCastle.Asn1.X9; using ChainUtils.BouncyCastle.Crypto; using ChainUtils.BouncyCastle.Crypto.Generators; using ChainUtils.BouncyCastle.Crypto.Parameters; using ChainUtils.BouncyCastle.Math; namespace ChainUtils.BouncyCastle.Security { public sealed class PublicKeyFactory { private PublicKeyFactory() { } public static AsymmetricKeyParameter CreateKey( byte[] keyInfoData) { return CreateKey( SubjectPublicKeyInfo.GetInstance( Asn1Object.FromByteArray(keyInfoData))); } public static AsymmetricKeyParameter CreateKey( Stream inStr) { return CreateKey( SubjectPublicKeyInfo.GetInstance( Asn1Object.FromStream(inStr))); } public static AsymmetricKeyParameter CreateKey( SubjectPublicKeyInfo keyInfo) { var algID = keyInfo.AlgorithmID; var algOid = algID.ObjectID; // TODO See RSAUtil.isRsaOid in Java build if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption) || algOid.Equals(X509ObjectIdentifiers.IdEARsa) || algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss) || algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep)) { var pubKey = RsaPublicKeyStructure.GetInstance( keyInfo.GetPublicKey()); return new RsaKeyParameters(false, pubKey.Modulus, pubKey.PublicExponent); } else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber)) { var seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()); var dhPublicKey = DHPublicKey.GetInstance(keyInfo.GetPublicKey()); var y = dhPublicKey.Y.Value; if (IsPkcsDHParam(seq)) return ReadPkcsDHParam(algOid, y, seq); var dhParams = DHDomainParameters.GetInstance(seq); var p = dhParams.P.Value; var g = dhParams.G.Value; var q = dhParams.Q.Value; BigInteger j = null; if (dhParams.J != null) { j = dhParams.J.Value; } DHValidationParameters validation = null; var dhValidationParms = dhParams.ValidationParms; if (dhValidationParms != null) { var seed = dhValidationParms.Seed.GetBytes(); var pgenCounter = dhValidationParms.PgenCounter.Value; // TODO Check pgenCounter size? validation = new DHValidationParameters(seed, pgenCounter.IntValue); } return new DHPublicKeyParameters(y, new DHParameters(p, g, q, j, validation)); } else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { var seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()); var derY = (DerInteger) keyInfo.GetPublicKey(); return ReadPkcsDHParam(algOid, derY.Value, seq); } else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { var para = new ElGamalParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); var derY = (DerInteger) keyInfo.GetPublicKey(); return new ElGamalPublicKeyParameters( derY.Value, new ElGamalParameters(para.P, para.G)); } else if (algOid.Equals(X9ObjectIdentifiers.IdDsa) || algOid.Equals(OiwObjectIdentifiers.DsaWithSha1)) { var derY = (DerInteger) keyInfo.GetPublicKey(); var ae = algID.Parameters; DsaParameters parameters = null; if (ae != null) { var para = DsaParameter.GetInstance(ae.ToAsn1Object()); parameters = new DsaParameters(para.P, para.Q, para.G); } return new DsaPublicKeyParameters(derY.Value, parameters); } else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey)) { var para = new X962Parameters(algID.Parameters.ToAsn1Object()); X9ECParameters x9; if (para.IsNamedCurve) { x9 = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters); } else { x9 = new X9ECParameters((Asn1Sequence)para.Parameters); } Asn1OctetString key = new DerOctetString(keyInfo.PublicKeyData.GetBytes()); var derQ = new X9ECPoint(x9.Curve, key); var q = derQ.Point; if (para.IsNamedCurve) { return new ECPublicKeyParameters("EC", q, (DerObjectIdentifier)para.Parameters); } var dParams = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed()); return new ECPublicKeyParameters(q, dParams); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { var gostParams = new Gost3410PublicKeyAlgParameters( (Asn1Sequence) algID.Parameters); Asn1OctetString key; try { key = (Asn1OctetString) keyInfo.GetPublicKey(); } catch (IOException) { throw new ArgumentException("invalid info structure in GOST3410 public key"); } var keyEnc = key.GetOctets(); var x = new byte[32]; var y = new byte[32]; for (var i = 0; i != y.Length; i++) { x[i] = keyEnc[32 - 1 - i]; } for (var i = 0; i != x.Length; i++) { y[i] = keyEnc[64 - 1 - i]; } var ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet); if (ecP == null) return null; var q = ecP.Curve.CreatePoint(new BigInteger(1, x), new BigInteger(1, y)); return new ECPublicKeyParameters("ECGOST3410", q, gostParams.PublicKeyParamSet); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { var algParams = new Gost3410PublicKeyAlgParameters( (Asn1Sequence) algID.Parameters); DerOctetString derY; try { derY = (DerOctetString) keyInfo.GetPublicKey(); } catch (IOException) { throw new ArgumentException("invalid info structure in GOST3410 public key"); } var keyEnc = derY.GetOctets(); var keyBytes = new byte[keyEnc.Length]; for (var i = 0; i != keyEnc.Length; i++) { keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // was little endian } var y = new BigInteger(1, keyBytes); return new Gost3410PublicKeyParameters(y, algParams.PublicKeyParamSet); } else { throw new SecurityUtilityException("algorithm identifier in key not recognised: " + algOid); } } private static bool IsPkcsDHParam(Asn1Sequence seq) { if (seq.Count == 2) return true; if (seq.Count > 3) return false; var l = DerInteger.GetInstance(seq[2]); var p = DerInteger.GetInstance(seq[0]); return l.Value.CompareTo(BigInteger.ValueOf(p.Value.BitLength)) <= 0; } private static DHPublicKeyParameters ReadPkcsDHParam(DerObjectIdentifier algOid, BigInteger y, Asn1Sequence seq) { var para = new DHParameter(seq); var lVal = para.L; var l = lVal == null ? 0 : lVal.IntValue; var dhParams = new DHParameters(para.P, para.G, null, l); return new DHPublicKeyParameters(y, dhParams, algOid); } } }
#region File Description //----------------------------------------------------------------------------- // SceneItem.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; #endregion namespace Spacewar { /// <summary> /// SceneItem is any item that can be in a scenegraph /// </summary> public class SceneItem : List<SceneItem> { /// <summary> /// Collision Radius of this item /// </summary> protected float radius; /// <summary> /// Should this item be deleted? /// </summary> protected bool delete; /// <summary> /// Simulation paused for this items, nothing will update /// </summary> private bool paused; /// <summary> /// The root SceneItem /// </summary> protected SceneItem Root; /// <summary> /// The parent SceneItem /// </summary> protected SceneItem Parent; /// <summary> /// Shape is the actual renderable object /// </summary> protected Shape shape; /// <summary> /// The position of this item /// </summary> protected Vector3 position; /// <summary> /// The velocity of this item /// </summary> protected Vector3 velocity; /// <summary> /// The acceleration of the item /// </summary> protected Vector3 acceleration; /// <summary> /// The current rotation of this item /// </summary> protected Vector3 rotation; /// <summary> /// The scaling transformation for this object /// </summary> protected Vector3 scale = new Vector3(1f, 1f, 1f); /// <summary> /// The center of rotation and scaling /// </summary> protected Vector3 center; private Game game; #region Properties public bool Delete { get { return delete; } set { delete = value; } } public float Radius { get { return radius; } set { radius = value; } } public Shape ShapeItem { get { return shape; } set { shape = value; } } public bool Paused { get { return paused; } set { paused = value; } } public Vector3 Acceleration { get { return acceleration; } } public Vector3 Velocity { get { return velocity; } set { velocity = value; } } public Vector3 Position { get { return position; } set { position = value; } } public Vector3 Rotation { get { return rotation; } set { rotation = value; } } public Vector3 Center { get { return center; } set { center = value; } } public Vector3 Scale { get { return scale; } set { scale = value; } } protected Game GameInstance { get { return game; } } #endregion /// <summary> /// Default constructor, does nothing special /// </summary> public SceneItem(Game game) { this.game = game; } /// <summary> /// Creates a SceneItem with a shape to be rendered at an initial position /// </summary> /// <param name="shape">The shape to be rendered for this item</param> /// <param name="initialPosition">The initial position of the item</param> public SceneItem(Game game, Shape shape, Vector3 initialPosition) { this.shape = shape; this.position = initialPosition; this.game = game; } /// <summary> /// Creates a SceneItem with a shape to be rendered /// </summary> /// <param name="shape">The shape to be rendered for this item</param> public SceneItem(Game game, Shape shape) { this.shape = shape; this.game = game; } /// <summary> /// Creates a SceneItem with no shape but a position /// </summary> /// <param name="initialPosition">The initial position of the item</param> public SceneItem(Game game, Vector3 initialPosition) { this.position = initialPosition; this.game = game; } /// <summary> /// Adds an item to the Scene Node /// </summary> /// <param name="childItem">The item to add</param> public new void Add(SceneItem childItem) { //A new custom 'add' that sets the parent and the root properties //on the child item childItem.Parent = this; if (Root == null) { childItem.Root = this; } else { childItem.Root = Root; } //Call the 'real' add method on the dictionary ((List<SceneItem>)this).Add(childItem); } /// <summary> /// Updates any values associated with this scene item and its children /// </summary> /// <param name="time">Game time</param> /// <param name="elapsedTime">Elapsed game time since last call</param> public virtual void Update(TimeSpan time, TimeSpan elapsedTime) { if (!paused) { //Do the basic acceleration/velocity/position updates velocity += Vector3.Multiply(acceleration, (float)elapsedTime.TotalSeconds); position += Vector3.Multiply(velocity, (float)elapsedTime.TotalSeconds); } //If this item has something to draw then update it if (shape != null) { shape.World = Matrix.CreateTranslation(-center) * Matrix.CreateScale(scale) * Matrix.CreateRotationX(rotation.X) * Matrix.CreateRotationY(rotation.Y) * Matrix.CreateRotationZ(rotation.Z) * Matrix.CreateTranslation(position + center); if (!paused) { shape.Update(time, elapsedTime); } } //Update each child item foreach (SceneItem item in this) { item.Update(time, elapsedTime); } //Remove any items that need deletion int i = 0; while (i < Count) { if (this[i].delete) { RemoveAt(i); } else { i++; } } //RemoveAll(IsDeleted); } private static bool IsDeleted(SceneItem item) { return item.delete; } /// <summary> /// Render any items associated with this scene item and its children /// </summary> public virtual void Render() { //If this item has something to draw then draw it if (shape != null) { shape.Render(); } //Then render all of the child nodes foreach (SceneItem item in this) { item.Render(); } } /// <summary> /// Checks if there is a collision between the this and the passed in item /// </summary> /// <param name="item">A scene item to check</param> /// <returns>True if there is a collision</returns> public virtual bool Collide(SceneItem item) { //Until we get collision meshes sorted just do a simple sphere (well circle!) check if ((position - item.position).Length() < radius + item.radius) return true; //If we are a ship and we are a long, thin pencil, //we have additional extents, check those, too! Ship shipItem = item as Ship; if (shipItem != null && shipItem.ExtendedExtent != null) { Matrix localRotation = Matrix.CreateRotationZ(shipItem.Rotation.Z); Vector4 extendedPosition = Vector4.Transform(shipItem.ExtendedExtent[0], localRotation); Vector3 localPosition = shipItem.Position + new Vector3(extendedPosition.X, extendedPosition.Y, extendedPosition.Z); if ((Position - localPosition).Length() < radius + item.Radius) return true; extendedPosition = Vector4.Transform(shipItem.ExtendedExtent[1], localRotation); localPosition = shipItem.Position + new Vector3(extendedPosition.X, extendedPosition.Y, extendedPosition.Z); if ((Position - localPosition).Length() < radius + item.Radius) return true; } Ship ship = this as Ship; if (ship != null && ship.ExtendedExtent != null) { Matrix localRotation = Matrix.CreateRotationZ(ship.Rotation.Z); Vector4 extendedPosition = Vector4.Transform(ship.ExtendedExtent[0], localRotation); Vector3 localPosition = ship.Position + new Vector3(extendedPosition.X, extendedPosition.Y, extendedPosition.Z); if ((localPosition - item.Position).Length() < radius + item.Radius) return true; extendedPosition = Vector4.Transform(ship.ExtendedExtent[1], localRotation); localPosition = ship.Position + new Vector3(extendedPosition.X, extendedPosition.Y, extendedPosition.Z); if ((localPosition - item.Position).Length() < radius + item.Radius) return true; } return false; } public virtual void OnCreateDevice() { } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Net; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Server.Kestrel.Internal.System.IO.Pipelines; using Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal; using Microsoft.Extensions.Logging; namespace RedHatX.AspNetCore.Server.Kestrel.Transport.Linux { sealed partial class TransportThread { private const int MaxPooledBlockLength = MemoryPool.MaxPooledBlockLength; // 128 IOVectors, take up 2KB of stack, can send up to 512KB private const int MaxIOVectorSendLength = 128; // 128 IOVectors, take up 2KB of stack, can receive up to 512KB private const int MaxIOVectorReceiveLength = 128; private const int MaxSendLength = MaxIOVectorSendLength * MaxPooledBlockLength; private const int ListenBacklog = 128; private const int EventBufferLength = 512; private const int EPollBlocked = 1; private const int EPollNotBlocked = 0; // Highest bit set in EPollData for writable poll // the remaining bits of the EPollData are the key // of the _sockets dictionary. private const int DupKeyMask = 1 << 31; private const byte PipeStopThread = 0; private const byte PipeActionsPending = 1; private const byte PipeStopSockets = 2; private struct ScheduledAction { public Action<object> Action; public Object State; } enum State { Initial, Starting, Started, ClosingAccept, AcceptClosed, Stopping, Stopped } private readonly IConnectionHandler _connectionHandler; private readonly int _threadId; private readonly IPEndPoint _endPoint; private readonly LinuxTransportOptions _transportOptions; private readonly ILoggerFactory _loggerFactory; private readonly object _gate = new object(); private int _cpuId; private State _state; private Exception _failReason; private Thread _thread; private TaskCompletionSource<object> _stateChangeCompletion; private ThreadContext _threadContext; public TransportThread(IPEndPoint endPoint, IConnectionHandler connectionHandler, LinuxTransportOptions options, int threadId, int cpuId, ILoggerFactory loggerFactory) { if (connectionHandler == null) { throw new ArgumentNullException(nameof(connectionHandler)); } _connectionHandler = connectionHandler; _threadId = threadId; _cpuId = cpuId; _endPoint = endPoint; _transportOptions = options; _loggerFactory = loggerFactory; } public Task StartAsync() { TaskCompletionSource<object> tcs; lock (_gate) { if (_state == State.Started) { return Task.CompletedTask; } else if (_state == State.Starting) { return _stateChangeCompletion.Task; } else if (_state != State.Initial) { ThrowInvalidState(); } try { tcs = _stateChangeCompletion = new TaskCompletionSource<object>(); _state = State.Starting; _thread = new Thread(PollThread); _thread.Start(); } catch { _state = State.Stopped; throw; } } return tcs.Task; } private static void AcceptOn(IPEndPoint endPoint, int cpuId, LinuxTransportOptions transportOptions, ThreadContext threadContext) { Socket acceptSocket = null; int fd = 0; int port = endPoint.Port; SocketFlags flags = SocketFlags.TypeAccept; try { bool ipv4 = endPoint.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork; acceptSocket = Socket.Create(ipv4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp, blocking: false); fd = acceptSocket.DangerousGetHandle().ToInt32(); if (!ipv4) { // Don't do mapped ipv4 acceptSocket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, 1); } if (transportOptions.ReceiveOnIncomingCpu) { if (cpuId != -1) { if (!acceptSocket.TrySetSocketOption(SocketOptionLevel.Socket, SocketOptionName.IncomingCpu, cpuId)) { threadContext.Logger.LogWarning($"Cannot enable nameof{SocketOptionName.IncomingCpu} for {endPoint}"); } } } // Linux: allow bind during linger time acceptSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1); // Linux: allow concurrent binds and let the kernel do load-balancing acceptSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReusePort, 1); if (transportOptions.DeferAccept) { // Linux: wait up to 1 sec for data to arrive before accepting socket acceptSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.DeferAccept, 1); flags |= SocketFlags.DeferAccept; } acceptSocket.Bind(endPoint); if (port == 0) { // When testing we want the OS to select a free port port = acceptSocket.GetLocalIPAddress().Port; } acceptSocket.Listen(ListenBacklog); } catch { acceptSocket?.Dispose(); throw; } TSocket tsocket = null; var sockets = threadContext.Sockets; try { tsocket = new TSocket(threadContext) { Flags = flags, Fd = fd, Socket = acceptSocket }; threadContext.AcceptSockets.Add(tsocket); lock (sockets) { sockets.Add(tsocket.Fd, tsocket); } EPollInterop.EPollControl(threadContext.EPollFd, EPollOperation.Add, fd, EPollEvents.Readable, EPollData(fd)); } catch { acceptSocket.Dispose(); threadContext.AcceptSockets.Remove(tsocket); lock (sockets) { sockets.Remove(fd); } throw; } endPoint.Port = port; } public async Task CloseAcceptAsync() { TaskCompletionSource<object> tcs = null; lock (_gate) { if (_state == State.Initial) { _state = State.Stopped; return; } else if (_state == State.AcceptClosed || _state == State.Stopping || _state == State.Stopped) { return; } else if (_state == State.ClosingAccept) { tcs = _stateChangeCompletion; } } if (tcs != null) { await tcs.Task; return; } try { await StartAsync(); } catch {} bool triggerStateChange = false; lock (_gate) { if (_state == State.AcceptClosed || _state == State.Stopping || _state == State.Stopped) { return; } else if (_state == State.ClosingAccept) { tcs = _stateChangeCompletion; } else if (_state == State.Started) { triggerStateChange = true; tcs = _stateChangeCompletion = new TaskCompletionSource<object>(); _state = State.ClosingAccept; } else { // Cannot happen ThrowInvalidState(); } } if (triggerStateChange) { _threadContext.CloseAccept(); } await tcs.Task; } public async Task StopAsync() { lock (_gate) { if (_state == State.Initial) { _state = State.Stopped; return; } else if (_state == State.Stopped) { if (_failReason != null) { var failReason = _failReason; _failReason = null; throw failReason; } return; } } await CloseAcceptAsync(); TaskCompletionSource<object> tcs = null; bool triggerStateChange = false; lock (_gate) { if (_state == State.Stopped) { if (_failReason != null) { var failReason = _failReason; _failReason = null; throw failReason; } return; } else if (_state == State.Stopping) { tcs = _stateChangeCompletion; } else if (_state == State.AcceptClosed) { tcs = _stateChangeCompletion = new TaskCompletionSource<object>(); _state = State.Stopping; triggerStateChange = true; } else { // Cannot happen ThrowInvalidState(); } } if (triggerStateChange) { _threadContext.StopSockets(); } await tcs.Task; } private ILogger CreateLogger() { return _loggerFactory.CreateLogger("{nameof(TransportThread)}.{_threadId}"); } private unsafe void PollThread(object obj) { ThreadContext threadContext = null; Exception error = null; try { // .NET doesn't support setting thread affinity on Start // We could change it before starting the thread // so it gets inherited, but we don't know how many threads // the runtime may start. if (_cpuId != -1) { Scheduler.SetCurrentThreadAffinity(_cpuId); } // objects are allocated on the PollThread heap int pipeKey; threadContext = new ThreadContext(this, _transportOptions, _connectionHandler, CreateLogger()); threadContext.Initialize(); { // register pipe pipeKey = threadContext.PipeEnds.ReadEnd.DangerousGetHandle().ToInt32(); EPollInterop.EPollControl(threadContext.EPollFd, EPollOperation.Add, threadContext.PipeEnds.ReadEnd.DangerousGetHandle().ToInt32(), EPollEvents.Readable, EPollData(pipeKey)); // accept connections AcceptOn(_endPoint, _cpuId, _transportOptions, threadContext); _threadContext = threadContext; } int epollFd = threadContext.EPollFd; var readEnd = threadContext.PipeEnds.ReadEnd; int notPacked = !EPoll.PackedEvents ? 1 : 0; var buffer = stackalloc int[EventBufferLength * (3 + notPacked)]; int statReadEvents = 0; int statWriteEvents = 0; int statAcceptEvents = 0; int statAccepts = 0; var sockets = threadContext.Sockets; var acceptableSockets = new List<TSocket>(1); var readableSockets = new List<TSocket>(EventBufferLength); var writableSockets = new List<TSocket>(EventBufferLength); bool pipeReadable = false; CompleteStateChange(State.Started); bool running = true; do { int numEvents = EPollInterop.EPollWait(epollFd, buffer, EventBufferLength, timeout: EPoll.TimeoutInfinite).Value; // actions can be scheduled without unblocking epoll threadContext.SetEpollNotBlocked(); // check events // we don't handle them immediately: // - this ensures we don't mismatch a closed socket with a new socket that have the same fd // ~ To have the same fd, the previous fd must be closed, which means it is removed from the epoll // ~ and won't show up in our next call to epoll.Wait. // ~ The old fd may be present in the buffer still, but lookup won't give a match, since it is removed // ~ from the dictionary before it is closed. If we were accepting already, a new socket could match. // - this also improves cache/cpu locality of the lookup int* ptr = buffer; lock (sockets) { for (int i = 0; i < numEvents; i++) { // Packed Non-Packed // ------ ------ // 0:Events == Events // 1:Int1 = Key [Padding] // 2:Int2 = Key == Int1 = Key // 3:~~~~~~~~~~ Int2 = Key // ~~~~~~~~~~ int key = ptr[2]; ptr += 3 + notPacked; TSocket tsocket; if (sockets.TryGetValue(key & ~DupKeyMask, out tsocket)) { var type = tsocket.Flags & SocketFlags.TypeMask; if (type == SocketFlags.TypeClient) { bool read = (key & DupKeyMask) == 0; if (read) { readableSockets.Add(tsocket); } else { writableSockets.Add(tsocket); } } else { statAcceptEvents++; acceptableSockets.Add(tsocket); } } else if (key == pipeKey) { pipeReadable = true; } } } // handle accepts statAcceptEvents += acceptableSockets.Count; for (int i = 0; i < acceptableSockets.Count; i++) { statAccepts += HandleAccept(acceptableSockets[i], threadContext); } acceptableSockets.Clear(); // handle writes statWriteEvents += writableSockets.Count; for (int i = 0; i < writableSockets.Count; i++) { writableSockets[i].CompleteWritable(); } writableSockets.Clear(); // handle reads statReadEvents += readableSockets.Count; for (int i = 0; i < readableSockets.Count; i++) { readableSockets[i].CompleteReadable(); } readableSockets.Clear(); // handle pipe if (pipeReadable) { PosixResult result; do { result = readEnd.TryReadByte(); if (result.Value == PipeStopSockets) { StopSockets(threadContext.Sockets); } else if (result.Value == PipeStopThread) { running = false; } } while (result); pipeReadable = false; } // scheduled work threadContext.DoScheduledWork(); } while (running); threadContext.Logger.LogInformation($"Thread {_threadId}: Stats A/AE:{statAccepts}/{statAcceptEvents} RE:{statReadEvents} WE:{statWriteEvents}"); } catch (Exception ex) { error = ex; } finally { // We are not using SafeHandles for epoll to increase performance. // running == false when there are no more Sockets // so we are sure there are no more epoll users. threadContext?.Dispose(); CompleteStateChange(State.Stopped, error); } } private static int HandleAccept(TSocket tacceptSocket, ThreadContext threadContext) { // TODO: should we handle more than 1 accept? If we do, we shouldn't be to eager // as that might give the kernel the impression we have nothing to do // which could interfere with the SO_REUSEPORT load-balancing. Socket clientSocket; var result = tacceptSocket.Socket.TryAccept(out clientSocket, blocking: false); if (result.IsSuccess) { int fd; TSocket tsocket; try { fd = clientSocket.DangerousGetHandle().ToInt32(); tsocket = new TSocket(threadContext) { Flags = SocketFlags.TypeClient, Fd = fd, Socket = clientSocket, PeerAddress = clientSocket.GetPeerIPAddress(), LocalAddress = clientSocket.GetLocalIPAddress() }; clientSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1); } catch { clientSocket.Dispose(); return 0; } var connectionContext = threadContext.ConnectionHandler.OnConnection(tsocket); tsocket.PipeReader = connectionContext.Output; tsocket.PipeWriter = connectionContext.Input; tsocket.ConnectionContext = connectionContext; var sockets = threadContext.Sockets; lock (sockets) { sockets.Add(fd, tsocket); } WriteToSocket(tsocket, connectionContext.Output); bool dataMayBeAvailable = (tacceptSocket.Flags & SocketFlags.DeferAccept) != 0; ReadFromSocket(tsocket, connectionContext.Input, dataMayBeAvailable); return 1; } else { return 0; } } private static async void WriteToSocket(TSocket tsocket, IPipeReader reader) { Exception error = null; try { while (true) { var readResult = await reader.ReadAsync(); ReadableBuffer buffer = readResult.Buffer; ReadCursor end = buffer.Start; try { if ((buffer.IsEmpty && readResult.IsCompleted) || readResult.IsCancelled) { // EOF or TransportThread stopped break; } if (!buffer.IsEmpty) { var result = TrySend(tsocket.Fd, ref buffer); if (result.Value == buffer.Length) { end = buffer.End; } else if (result.IsSuccess) { end = buffer.Move(buffer.Start, result.Value); } else if (result == PosixResult.EAGAIN || result == PosixResult.EWOULDBLOCK) { if (!await Writable(tsocket)) { // TransportThread stopped break; } } else { error = result.AsException(); break; } } } finally { // We need to call Advance to end the read reader.Advance(end); } } } catch (Exception ex) { error = ex; } finally { tsocket.ConnectionContext.OnConnectionClosed(error); reader.Complete(error); tsocket.StopReadFromSocket(); CleanupSocketEnd(tsocket); } } private static unsafe PosixResult TrySend(int fd, ref ReadableBuffer buffer) { int ioVectorLength = 0; foreach (var memory in buffer) { if (memory.Length == 0) { continue; } ioVectorLength++; if (ioVectorLength == MaxIOVectorSendLength) { // No more room in the IOVector break; } } if (ioVectorLength == 0) { return new PosixResult(0); } var ioVectors = stackalloc IOVector[ioVectorLength]; int i = 0; foreach (var memory in buffer) { if (memory.Length == 0) { continue; } void* pointer; memory.TryGetPointer(out pointer); ioVectors[i].Base = pointer; ioVectors[i].Count = (void*)memory.Length; i++; if (i == ioVectorLength) { // No more room in the IOVector break; } } return SocketInterop.Send(fd, ioVectors, ioVectorLength); } private static WritableAwaitable Writable(TSocket tsocket) => new WritableAwaitable(tsocket); private static void RegisterForWritable(TSocket tsocket) { bool registered = tsocket.DupSocket != null; // To avoid having to synchronize the event mask with the Readable // we dup the socket. // In the EPollData we set the highest bit to indicate this is the // poll for writable. if (!registered) { tsocket.DupSocket = tsocket.Socket.Duplicate(); } EPollInterop.EPollControl(tsocket.ThreadContext.EPollFd, registered ? EPollOperation.Modify : EPollOperation.Add, tsocket.DupSocket.DangerousGetHandle().ToInt32(), EPollEvents.Writable | EPollEvents.OneShot, EPollData(tsocket.Fd | DupKeyMask)); } private static ReadableAwaitable Readable(TSocket tsocket) => new ReadableAwaitable(tsocket); private static void RegisterForReadable(TSocket tsocket) { bool register = tsocket.SetRegistered(); EPollInterop.EPollControl(tsocket.ThreadContext.EPollFd, register ? EPollOperation.Add : EPollOperation.Modify, tsocket.Fd, EPollEvents.Readable | EPollEvents.OneShot, EPollData(tsocket.Fd)); } private static async void ReadFromSocket(TSocket tsocket, IPipeWriter writer, bool dataMayBeAvailable) { Exception error = null; try { var availableBytes = dataMayBeAvailable ? tsocket.Socket.GetAvailableBytes() : 0; bool readable0 = true; if (availableBytes == 0 && (readable0 = await Readable(tsocket))) // Readable { availableBytes = tsocket.Socket.GetAvailableBytes(); } else if (!readable0) { error = new ConnectionAbortedException(); } while (availableBytes != 0) { var buffer = writer.Alloc(2048); try { error = Receive(tsocket.Fd, availableBytes, ref buffer); if (error != null) { break; } availableBytes = 0; var flushResult = await buffer.FlushAsync(); bool readable = true; if (!flushResult.IsCompleted // Reader hasn't stopped && !flushResult.IsCancelled // TransportThread hasn't stopped && (readable = await Readable(tsocket))) // Readable { availableBytes = tsocket.Socket.GetAvailableBytes(); } else if (flushResult.IsCancelled || !readable) { error = new ConnectionAbortedException(); } } catch (Exception e) { availableBytes = 0; buffer.Commit(); error = e; } } } catch (Exception ex) { error = ex; } finally { // even when error == null, we call Abort // this mean receiving FIN causes Abort // rationale: https://github.com/aspnet/KestrelHttpServer/issues/1139#issuecomment-251748845 tsocket.ConnectionContext.Abort(error); writer.Complete(error); CleanupSocketEnd(tsocket); } } private static unsafe Exception Receive(int fd, int availableBytes, ref WritableBuffer wb) { int ioVectorLength = availableBytes <= wb.Buffer.Length ? 1 : Math.Min(1 + (availableBytes - wb.Buffer.Length + MaxPooledBlockLength - 1) / MaxPooledBlockLength, MaxIOVectorReceiveLength); var ioVectors = stackalloc IOVector[ioVectorLength]; var allocated = 0; var advanced = 0; int ioVectorsUsed = 0; for (; ioVectorsUsed < ioVectorLength; ioVectorsUsed++) { wb.Ensure(1); var memory = wb.Buffer; var length = memory.Length; void* pointer; wb.Buffer.TryGetPointer(out pointer); ioVectors[ioVectorsUsed].Base = pointer; ioVectors[ioVectorsUsed].Count = (void*)length; allocated += length; if (allocated >= availableBytes) { // Every Memory (except the last one) must be filled completely. ioVectorsUsed++; break; } wb.Advance(length); advanced += length; } var expectedMin = Math.Min(availableBytes, allocated); // Ideally we get availableBytes in a single receive // but we are happy if we get at least a part of it // and we are willing to take {MaxEAgainCount} EAGAINs. // Less data could be returned due to these reasons: // * TCP URG // * packet was not placed in receive queue (race with FIONREAD) // * ? const int MaxEAgainCount = 10; var eAgainCount = 0; var received = 0; do { var result = SocketInterop.Receive(fd, ioVectors, ioVectorsUsed); if (result.IsSuccess) { received += result.Value; if (received >= expectedMin) { // We made it! wb.Advance(received - advanced); return null; } eAgainCount = 0; // Update ioVectors to match bytes read var skip = result.Value; for (int i = 0; (i < ioVectorsUsed) && (skip > 0); i++) { var length = (int)ioVectors[i].Count; var skipped = Math.Min(skip, length); ioVectors[i].Count = (void*)(length - skipped); ioVectors[i].Base = (byte*)ioVectors[i].Base + skipped; skip -= skipped; } } else if (result == PosixResult.EAGAIN || result == PosixResult.EWOULDBLOCK) { eAgainCount++; if (eAgainCount == MaxEAgainCount) { return new NotSupportedException("Too many EAGAIN, unable to receive available bytes."); } } else if (result == PosixResult.ECONNRESET) { return new ConnectionResetException(result.ErrorDescription(), result.AsException()); } else { return result.AsException(); } } while (true); } private static void CleanupSocketEnd(TSocket tsocket) { var bothClosed = tsocket.CloseEnd(); if (bothClosed) { // First remove from the Dictionary, so we can't match with a new fd. tsocket.ThreadContext.RemoveSocket(tsocket.Fd); // We are not using SafeHandles to increase performance. // We get here when both reading and writing has stopped // so we are sure this is the last use of the Socket. tsocket.Socket.Dispose(); tsocket.DupSocket?.Dispose(); } } private void CloseAccept(ThreadContext threadContext, Dictionary<int, TSocket> sockets) { var acceptSockets = threadContext.AcceptSockets; lock (sockets) { for (int i = 0; i < acceptSockets.Count; i++) { threadContext.RemoveSocket(acceptSockets[i].Fd); } } for (int i = 0; i < acceptSockets.Count; i++) { // close causes remove from epoll (CLOEXEC) acceptSockets[i].Socket.Dispose(); // will close (no concurrent users) } acceptSockets.Clear(); CompleteStateChange(State.AcceptClosed); } private static void StopSockets(Dictionary<int, TSocket> sockets) { Dictionary<int, TSocket> clone; lock (sockets) { clone = new Dictionary<int, TSocket>(sockets); } foreach (var kv in clone) { var tsocket = kv.Value; tsocket.StopWriteToSocket(); // this calls StopReadFromSocket } } private void ThrowInvalidState() { throw new InvalidOperationException($"nameof(TransportThread) is {_state}"); } private void CompleteStateChange(State state, Exception error = null) { TaskCompletionSource<object> tcs; lock (_gate) { tcs = _stateChangeCompletion; if (tcs == null) { _failReason = error; } _stateChangeCompletion = null; _state = state; } ThreadPool.QueueUserWorkItem(o => { if (error == null) { tcs?.SetResult(null); } else { tcs?.SetException(error); } }); } private static long EPollData(int fd) => (((long)(uint)fd) << 32) | (long)(uint)fd; } }
/* Copyright (c) 2013 DEVSENSE The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.Collections.Generic; using System.Reflection.Emit; using System.Diagnostics; using PHP.Core.AST; using PHP.Core.Emit; using PHP.Core.Parsers; namespace PHP.Core.Compiler.AST { partial class NodeCompilers { [NodeCompiler(typeof(ListEx))] sealed class ListExCompiler : ExpressionCompiler<ListEx> { public override Evaluation Analyze(ListEx node, Analyzer analyzer, ExInfoFromParent info) { access = info.Access; ExInfoFromParent sinfo = new ExInfoFromParent(node); // r-value if (node.RValue != null) node.RValue = node.RValue.Analyze(analyzer, sinfo).Literalize(); // l-values sinfo.Access = AccessType.Write; for (int i = 0; i < node.LValues.Count; i++) { if (node.LValues[i] != null) node.LValues[i] = node.LValues[i].Analyze(analyzer, sinfo).Expression; } return new Evaluation(node); } public override PhpTypeCode Emit(ListEx node, CodeGenerator codeGenerator) { Statistics.AST.AddNode("ListEx"); Debug.Assert(access == AccessType.Read || access == AccessType.None); Debug.Assert(node.RValue != null); // the root of the lists structure must have RValue assigned. list(whatever) = RValue codeGenerator.EmitBoxing(node.RValue.Emit(codeGenerator)); // put object on the top of the stack // assign the value from top of evaluation stack to the list return this.EmitAssign(node, codeGenerator); } /// <summary> /// Assigns items of array from the top of evaluation stack to the list. /// </summary> internal PhpTypeCode EmitAssign(ListEx listex, CodeGenerator codeGenerator) { LocalBuilder o1 = codeGenerator.IL.GetTemporaryLocal(Types.Object[0]); // temporary variable for object to be copied EmitAssignList(codeGenerator, listex.LValues, o1); // assign particular elements of the list, using the array from the stack // return temporary local codeGenerator.IL.ReturnTemporaryLocal(o1); // the original top of the stack is replaced with the instance of array or null if (access == AccessType.Read) { return PhpTypeCode.PhpArray; // return the top of the stack (null or array) } else { codeGenerator.IL.Emit(OpCodes.Pop); // remove the top of the stack, not used return PhpTypeCode.Void; } } /// <summary> /// Use the object on the top of the stack, the object here will stay untouched. /// /// Assigns recursively into lvalues. If the object is PhpArray, assign items, otherwise assign nulls. /// </summary> /// <param name="codeGenerator"></param> /// <param name="vals">Arguments of the list expression.</param> /// <param name="o1">Temporary local variable.</param> /// <remarks>After the method finishes, the top of the stack is the same.</remarks> private static void EmitAssignList(CodeGenerator codeGenerator, List<Expression> vals, LocalBuilder o1) { Label end_label = codeGenerator.IL.DefineLabel(); Label storearray_label = codeGenerator.IL.DefineLabel(); // PUSH stack[0] as PhpArray codeGenerator.IL.Emit(OpCodes.Dup); // copy of the value, keep original value on the top of the stack codeGenerator.IL.Emit(OpCodes.Isinst, Types.PhpArray[0]); // convert the top of the stack into PhpArray // the top of the stack points to array or null // if (stack[0] != null) goto storearray_label codeGenerator.IL.Emit(OpCodes.Dup); // copy of the value, keep original value on the top of the stack codeGenerator.IL.Emit(OpCodes.Brtrue, storearray_label); // jump to storearray_label if conversion succeeded // Conversion to array failed, assign null into lvalues EmitAssignListNulls(codeGenerator, vals); // fill vals with null recursively codeGenerator.IL.Emit(OpCodes.Br, end_label); // goto end_label // Conversion to PhpArray succeeded codeGenerator.IL.MarkLabel(storearray_label, true); // assign array items into lvalues EmitAssignListArray(codeGenerator, vals, o1); // End label codeGenerator.IL.MarkLabel(end_label, true); codeGenerator.IL.Emit(OpCodes.Pop); // remove the top of the stack (array or null), not used then } private static void EmitAssignListArray(CodeGenerator codeGenerator, List<Expression> vals, LocalBuilder o1) { // // the array is on the top of the evaluation stack, value will be kept, must be duplicated to be used // // Process in the reverse order ! for (int i = vals.Count - 1; i >= 0; i--) { if (vals[i] == null) continue; // push the array item onto the stack // LOAD array.GetArrayItem(i,false) codeGenerator.IL.Emit(OpCodes.Dup); // copy of the array codeGenerator.IL.Emit(OpCodes.Ldc_I4, i); // i codeGenerator.IL.Emit(OpCodes.Ldc_I4_0); // false (!quiet) codeGenerator.IL.Emit(OpCodes.Callvirt, Methods.PhpArray.GetArrayItem_Int32); // assign the item from the stack into vals[i] if (vals[i] is VariableUse) { // o1 = stack[0] codeGenerator.IL.Stloc(o1); // store the value into local variable o1 // PREPARE <variable>: codeGenerator.ChainBuilder.Create(); vals[i].Emit(codeGenerator); // LOAD o1 codeGenerator.IL.Ldloc(o1); // LOAD PhpVariable.Copy(STACK,CopyReason.Assigned) codeGenerator.EmitVariableCopy(CopyReason.Assigned, null); // STORE <variable>: VariableUseHelper.EmitAssign((VariableUse)vals[i], codeGenerator); codeGenerator.ChainBuilder.End(); } else if (vals[i] is ListEx) { EmitAssignList(codeGenerator, (vals[i] as ListEx).LValues, o1); codeGenerator.IL.Emit(OpCodes.Pop); // removes used value from the stack } else { codeGenerator.IL.Emit(OpCodes.Pop); // removes used value from the stack Debug.Fail("Unsupported list argument of type " + vals[i].GetType().ToString()); } } } /// <summary> /// Assigns null into given lvalues recursively. /// </summary> /// <param name="codeGenerator"></param> /// <param name="vals"></param> private static void EmitAssignListNulls(CodeGenerator codeGenerator, List<Expression> vals) { // clear lvalues recursively for (int i = 0; i < vals.Count; ++i) { if (vals[i] == null) continue; if (vals[i] is VariableUse) { // Prepare stack for writing result... codeGenerator.ChainBuilder.Create(); (vals[i] as VariableUse).Emit(codeGenerator); codeGenerator.IL.Emit(OpCodes.Ldnull); // Store result VariableUseHelper.EmitAssign((VariableUse)vals[i], codeGenerator); codeGenerator.ChainBuilder.End(); } else if (vals[i] is ListEx) { EmitAssignListNulls(codeGenerator, (vals[i] as ListEx).LValues); } else { Debug.Fail("Unsupported list argument of type " + vals[i].GetType().ToString()); } } } } } }
#region File Description //----------------------------------------------------------------------------- // HelpScreen.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content; using RolePlayingGameData; #endregion namespace RolePlaying { /// <summary> /// Shows the help screen, explaining the basic game idea to the user. /// </summary> class HelpScreen : GameScreen { #region Fields private Texture2D backgroundTexture; private Texture2D plankTexture; private Vector2 plankPosition; private Vector2 titlePosition; private string helpText = "Welcome, hero! You must meet new comrades, earn necessary " + "experience, gold, spells, and the equipment required to challenge " + "and defeat the evil Tamar, who resides in his lair, known as the " + "Unspoken Tower. Be wary! The Unspoken Tower is filled with " + "monstrosities that only the most hardened of heroes could possibly " + "face. Good luck!"; private List<string> textLines; private Texture2D scrollUpTexture; private readonly Vector2 scrollUpPosition = ScaledVector2.GetScaledVector(980, 200); private Texture2D scrollDownTexture; private readonly Vector2 scrollDownPosition = ScaledVector2.GetScaledVector(980, 460); private Texture2D lineBorderTexture; private readonly Vector2 linePosition = ScaledVector2.GetScaledVector(200, 570); private Texture2D backTexture; private readonly Vector2 backPosition = ScaledVector2.GetScaledVector(220, 600); private int startIndex; private const int maxLineDisplay = 8; #endregion #region Initialization public HelpScreen() : base() { textLines = Fonts.BreakTextIntoList(helpText, Fonts.DescriptionFont, (int)(590 * ScaledVector2.ScaleFactor)); } /// <summary> /// Loads the graphics content for this screen /// </summary> public override void LoadContent() { base.LoadContent(); ContentManager content = ScreenManager.Game.Content; backgroundTexture = content.Load<Texture2D>(@"Textures\MainMenu\MainMenu"); plankTexture = content.Load<Texture2D>(@"Textures\MainMenu\MainMenuPlank03"); backTexture = content.Load<Texture2D>(@"Textures\Buttons\rpgbtn"); scrollUpTexture = content.Load<Texture2D>(@"Textures\GameScreens\ScrollUp"); scrollDownTexture = content.Load<Texture2D>(@"Textures\GameScreens\ScrollDown"); lineBorderTexture = content.Load<Texture2D>(@"Textures\GameScreens\LineBorder"); plankPosition.X = backgroundTexture.Width * ScaledVector2.DrawFactor / 2 - plankTexture.Width *ScaledVector2.DrawFactor / 2; plankPosition.Y = 60 * ScaledVector2.ScaleFactor; titlePosition.X = plankPosition.X + (plankTexture.Width * ScaledVector2.DrawFactor - Fonts.HeaderFont.MeasureString("Help").X) / 2; titlePosition.Y = plankPosition.Y + (plankTexture.Height * ScaledVector2.DrawFactor - Fonts.HeaderFont.MeasureString("Help").Y) / 2; } #endregion #region Updating /// <summary> /// Handles user input. /// </summary> public override void HandleInput() { bool upperClicked = false; bool lowerClicked = false; bool backClicked = false; if (InputManager.IsButtonClicked(new Rectangle ((int)scrollUpPosition.X - scrollUpTexture.Width, (int)scrollUpPosition.Y - scrollUpTexture.Height, scrollUpTexture.Width * 2, scrollUpTexture.Height * 2))) { upperClicked = true; } if (InputManager.IsButtonClicked(new Rectangle ((int)scrollDownPosition.X - scrollDownTexture.Width, (int)scrollDownPosition.Y - scrollDownTexture.Height, scrollDownTexture.Width * 2, scrollDownTexture.Height * 2))) { lowerClicked = true; } if (InputManager.IsButtonClicked(new Rectangle ((int)backPosition.X, (int)backPosition.Y, (int)(backTexture.Width * ScaledVector2.DrawFactor), (int)(backTexture.Height * ScaledVector2.DrawFactor)))) { backClicked = true; } // exits the screen if (InputManager.IsActionTriggered(InputManager.Action.Back) || backClicked) { ExitScreen(); return; } // scroll down else if (InputManager.IsActionTriggered(InputManager.Action.CursorDown) || lowerClicked) { // Traverse down the help text if (startIndex + maxLineDisplay < textLines.Count) { startIndex += 1; } } // scroll up else if (InputManager.IsActionTriggered(InputManager.Action.CursorUp) || upperClicked) { // Traverse up the help text if (startIndex > 0) { startIndex -= 1; } } } #endregion #region Drawing /// <summary> /// Draws the help screen. /// </summary> public override void Draw(GameTime gameTime) { SpriteBatch spriteBatch = ScreenManager.SpriteBatch; spriteBatch.Begin(); spriteBatch.Draw(backgroundTexture, Vector2.Zero,null, Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); spriteBatch.Draw(plankTexture, plankPosition,null, Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); spriteBatch.Draw(backTexture, backPosition,null, Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); spriteBatch.Draw(lineBorderTexture, linePosition,null, Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); string text = "Back"; Vector2 textPosition = Fonts.GetCenterPositionInButton(Fonts.ButtonNamesFont, text, new Rectangle((int)backPosition.X, (int)backPosition.Y, backTexture.Width, backTexture.Height)); spriteBatch.DrawString(Fonts.ButtonNamesFont, text,textPosition,Color.White); spriteBatch.Draw(scrollUpTexture, scrollUpPosition,null, Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); spriteBatch.Draw(scrollDownTexture, scrollDownPosition,null, Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); spriteBatch.DrawString(Fonts.HeaderFont, "Help", titlePosition, Fonts.TitleColor); for (int i = 0; i < maxLineDisplay; i++) { spriteBatch.DrawString(Fonts.DescriptionFont, textLines[startIndex + i], ScaledVector2.GetScaledVector(360, 200 + (Fonts.DescriptionFont.LineSpacing + 10) * i), Color.Black); } spriteBatch.End(); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; namespace System.Net.Http.Headers { public class ContentRangeHeaderValue : ICloneable { private string _unit; private long? _from; private long? _to; private long? _length; public string Unit { get { return _unit; } set { HeaderUtilities.CheckValidToken(value, nameof(value)); _unit = value; } } public long? From { get { return _from; } } public long? To { get { return _to; } } public long? Length { get { return _length; } } public bool HasLength // e.g. "Content-Range: bytes 12-34/*" { get { return _length != null; } } public bool HasRange // e.g. "Content-Range: bytes */1234" { get { return _from != null; } } public ContentRangeHeaderValue(long from, long to, long length) { // Scenario: "Content-Range: bytes 12-34/5678" if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length)); } if ((to < 0) || (to > length)) { throw new ArgumentOutOfRangeException(nameof(to)); } if ((from < 0) || (from > to)) { throw new ArgumentOutOfRangeException(nameof(from)); } _from = from; _to = to; _length = length; _unit = HeaderUtilities.BytesUnit; } public ContentRangeHeaderValue(long length) { // Scenario: "Content-Range: bytes */1234" if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length)); } _length = length; _unit = HeaderUtilities.BytesUnit; } public ContentRangeHeaderValue(long from, long to) { // Scenario: "Content-Range: bytes 12-34/*" if (to < 0) { throw new ArgumentOutOfRangeException(nameof(to)); } if ((from < 0) || (from > to)) { throw new ArgumentOutOfRangeException(nameof(from)); } _from = from; _to = to; _unit = HeaderUtilities.BytesUnit; } private ContentRangeHeaderValue() { } private ContentRangeHeaderValue(ContentRangeHeaderValue source) { Debug.Assert(source != null); _from = source._from; _to = source._to; _length = source._length; _unit = source._unit; } public override bool Equals(object obj) { ContentRangeHeaderValue other = obj as ContentRangeHeaderValue; if (other == null) { return false; } return ((_from == other._from) && (_to == other._to) && (_length == other._length) && string.Equals(_unit, other._unit, StringComparison.OrdinalIgnoreCase)); } public override int GetHashCode() { int result = StringComparer.OrdinalIgnoreCase.GetHashCode(_unit); if (HasRange) { result = result ^ _from.GetHashCode() ^ _to.GetHashCode(); } if (HasLength) { result = result ^ _length.GetHashCode(); } return result; } public override string ToString() { StringBuilder sb = StringBuilderCache.Acquire(); sb.Append(_unit); sb.Append(' '); if (HasRange) { sb.Append(_from.Value.ToString(NumberFormatInfo.InvariantInfo)); sb.Append('-'); sb.Append(_to.Value.ToString(NumberFormatInfo.InvariantInfo)); } else { sb.Append('*'); } sb.Append('/'); if (HasLength) { sb.Append(_length.Value.ToString(NumberFormatInfo.InvariantInfo)); } else { sb.Append('*'); } return StringBuilderCache.GetStringAndRelease(sb); } public static ContentRangeHeaderValue Parse(string input) { int index = 0; return (ContentRangeHeaderValue)GenericHeaderParser.ContentRangeParser.ParseValue(input, null, ref index); } public static bool TryParse(string input, out ContentRangeHeaderValue parsedValue) { int index = 0; object output; parsedValue = null; if (GenericHeaderParser.ContentRangeParser.TryParseValue(input, null, ref index, out output)) { parsedValue = (ContentRangeHeaderValue)output; return true; } return false; } internal static int GetContentRangeLength(string input, int startIndex, out object parsedValue) { Debug.Assert(startIndex >= 0); parsedValue = null; if (string.IsNullOrEmpty(input) || (startIndex >= input.Length)) { return 0; } // Parse the unit string: <unit> in '<unit> <from>-<to>/<length>' int unitLength = HttpRuleParser.GetTokenLength(input, startIndex); if (unitLength == 0) { return 0; } string unit = input.Substring(startIndex, unitLength); int current = startIndex + unitLength; int separatorLength = HttpRuleParser.GetWhitespaceLength(input, current); if (separatorLength == 0) { return 0; } current = current + separatorLength; if (current == input.Length) { return 0; } // Read range values <from> and <to> in '<unit> <from>-<to>/<length>' int fromStartIndex = current; int fromLength = 0; int toStartIndex = 0; int toLength = 0; if (!TryGetRangeLength(input, ref current, out fromLength, out toStartIndex, out toLength)) { return 0; } // After the range is read we expect the length separator '/' if ((current == input.Length) || (input[current] != '/')) { return 0; } current++; // Skip '/' separator current = current + HttpRuleParser.GetWhitespaceLength(input, current); if (current == input.Length) { return 0; } // We may not have a length (e.g. 'bytes 1-2/*'). But if we do, parse the length now. int lengthStartIndex = current; int lengthLength = 0; if (!TryGetLengthLength(input, ref current, out lengthLength)) { return 0; } if (!TryCreateContentRange(input, unit, fromStartIndex, fromLength, toStartIndex, toLength, lengthStartIndex, lengthLength, out parsedValue)) { return 0; } return current - startIndex; } private static bool TryGetLengthLength(string input, ref int current, out int lengthLength) { lengthLength = 0; if (input[current] == '*') { current++; } else { // Parse length value: <length> in '<unit> <from>-<to>/<length>' lengthLength = HttpRuleParser.GetNumberLength(input, current, false); if ((lengthLength == 0) || (lengthLength > HttpRuleParser.MaxInt64Digits)) { return false; } current = current + lengthLength; } current = current + HttpRuleParser.GetWhitespaceLength(input, current); return true; } private static bool TryGetRangeLength(string input, ref int current, out int fromLength, out int toStartIndex, out int toLength) { fromLength = 0; toStartIndex = 0; toLength = 0; // Check if we have a value like 'bytes */133'. If yes, skip the range part and continue parsing the // length separator '/'. if (input[current] == '*') { current++; } else { // Parse first range value: <from> in '<unit> <from>-<to>/<length>' fromLength = HttpRuleParser.GetNumberLength(input, current, false); if ((fromLength == 0) || (fromLength > HttpRuleParser.MaxInt64Digits)) { return false; } current = current + fromLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); // After the first value, the '-' character must follow. if ((current == input.Length) || (input[current] != '-')) { // We need a '-' character otherwise this can't be a valid range. return false; } current++; // skip the '-' character current = current + HttpRuleParser.GetWhitespaceLength(input, current); if (current == input.Length) { return false; } // Parse second range value: <to> in '<unit> <from>-<to>/<length>' toStartIndex = current; toLength = HttpRuleParser.GetNumberLength(input, current, false); if ((toLength == 0) || (toLength > HttpRuleParser.MaxInt64Digits)) { return false; } current = current + toLength; } current = current + HttpRuleParser.GetWhitespaceLength(input, current); return true; } private static bool TryCreateContentRange(string input, string unit, int fromStartIndex, int fromLength, int toStartIndex, int toLength, int lengthStartIndex, int lengthLength, out object parsedValue) { parsedValue = null; long from = 0; if ((fromLength > 0) && !HeaderUtilities.TryParseInt64(input, fromStartIndex, fromLength, out from)) { return false; } long to = 0; if ((toLength > 0) && !HeaderUtilities.TryParseInt64(input, toStartIndex, toLength, out to)) { return false; } // 'from' must not be greater than 'to' if ((fromLength > 0) && (toLength > 0) && (from > to)) { return false; } long length = 0; if ((lengthLength > 0) && !HeaderUtilities.TryParseInt64(input, lengthStartIndex, lengthLength, out length)) { return false; } // 'from' and 'to' must be less than 'length' if ((toLength > 0) && (lengthLength > 0) && (to >= length)) { return false; } ContentRangeHeaderValue result = new ContentRangeHeaderValue(); result._unit = unit; if (fromLength > 0) { result._from = from; result._to = to; } if (lengthLength > 0) { result._length = length; } parsedValue = result; return true; } object ICloneable.Clone() { return new ContentRangeHeaderValue(this); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================ ** ** Class: ResourceWriter ** ** ** ** Purpose: Default way to write strings to a CLR resource ** file. ** ** ===========================================================*/ using System; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.Versioning; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Resources { // Generates a binary .resources file in the system default format // from name and value pairs. Create one with a unique file name, // call AddResource() at least once, then call Generate() to write // the .resources file to disk, then call Dispose() to close the file. // // The resources generally aren't written out in the same order // they were added. // // See the RuntimeResourceSet overview for details on the system // default file format. // public sealed class ResourceWriter : System.IDisposable { // An initial size for our internal sorted list, to avoid extra resizes. private const int AverageNameSize = 20 * 2; // chars in little endian Unicode private const int AverageValueSize = 40; private const string ResourceReaderFullyQualifiedName = "System.Resources.ResourceReader, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; private const string ResSetTypeName = "System.Resources.RuntimeResourceSet"; private const int ResSetVersion = 2; private const int ResourceTypeCodeString = 1; private const int ResourceManagerMagicNumber = unchecked((int)0xBEEFCACE); private const int ResourceManagerHeaderVersionNumber = 1; private SortedDictionary<String, String> _resourceList; private Stream _output; private Dictionary<String, String> _caseInsensitiveDups; public ResourceWriter(Stream stream) { if (stream == null) throw new ArgumentNullException("stream"); if (!stream.CanWrite) throw new ArgumentException(SR.Argument_StreamNotWritable); Contract.EndContractBlock(); _output = stream; _resourceList = new SortedDictionary<String, String>(FastResourceComparer.Default); _caseInsensitiveDups = new Dictionary<String, String>(StringComparer.OrdinalIgnoreCase); } // Adds a string resource to the list of resources to be written to a file. // They aren't written until Generate() is called. // public void AddResource(String name, String value) { if (name == null) throw new ArgumentNullException("name"); Contract.EndContractBlock(); if (_resourceList == null) throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved); // Check for duplicate resources whose names vary only by case. _caseInsensitiveDups.Add(name, null); _resourceList.Add(name, value); } public void Dispose() { if (_resourceList != null) { Generate(); } if (_output != null) { _output.Dispose(); GC.SuppressFinalize((object)_output); } _output = null; _caseInsensitiveDups = null; } // After calling AddResource, Generate() writes out all resources to the // output stream in the system default format. // If an exception occurs during object serialization or during IO, // the .resources file is closed and deleted, since it is most likely // invalid. public void Generate() { if (_resourceList == null) throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved); BinaryWriter bw = new BinaryWriter(_output, Encoding.UTF8); // Write out the ResourceManager header // Write out magic number bw.Write(ResourceManagerMagicNumber); // Write out ResourceManager header version number bw.Write(ResourceManagerHeaderVersionNumber); MemoryStream resMgrHeaderBlob = new MemoryStream(240); BinaryWriter resMgrHeaderPart = new BinaryWriter(resMgrHeaderBlob); // Write out class name of IResourceReader capable of handling // this file. resMgrHeaderPart.Write(ResourceReaderFullyQualifiedName); // Write out class name of the ResourceSet class best suited to // handling this file. // This needs to be the same even with multi-targeting. It's the // full name -- not the assembly qualified name. resMgrHeaderPart.Write(ResSetTypeName); resMgrHeaderPart.Flush(); // Write number of bytes to skip over to get past ResMgr header bw.Write((int)resMgrHeaderBlob.Length); // Write the rest of the ResMgr header resMgrHeaderBlob.Seek(0, SeekOrigin.Begin); resMgrHeaderBlob.CopyTo(bw.BaseStream, (int)resMgrHeaderBlob.Length); // End ResourceManager header // Write out the RuntimeResourceSet header // Version number bw.Write(ResSetVersion); // number of resources int numResources = _resourceList.Count; bw.Write(numResources); // Store values in temporary streams to write at end of file. int[] nameHashes = new int[numResources]; int[] namePositions = new int[numResources]; int curNameNumber = 0; MemoryStream nameSection = new MemoryStream(numResources * AverageNameSize); BinaryWriter names = new BinaryWriter(nameSection, Encoding.Unicode); Stream dataSection = new MemoryStream(); // Either a FileStream or a MemoryStream using (dataSection) { BinaryWriter data = new BinaryWriter(dataSection, Encoding.UTF8); // We've stored our resources internally in a Hashtable, which // makes no guarantees about the ordering while enumerating. // While we do our own sorting of the resource names based on their // hash values, that's only sorting the nameHashes and namePositions // arrays. That's all that is strictly required for correctness, // but for ease of generating a patch in the future that // modifies just .resources files, we should re-sort them. // Write resource name and position to the file, and the value // to our temporary buffer. Save Type as well. foreach (var items in _resourceList) { nameHashes[curNameNumber] = FastResourceComparer.HashFunction((String)items.Key); namePositions[curNameNumber++] = (int)names.Seek(0, SeekOrigin.Current); names.Write((String)items.Key); // key names.Write((int)data.Seek(0, SeekOrigin.Current)); // virtual offset of value. String value = items.Value; // Write out type code Write7BitEncodedInt(data, ResourceTypeCodeString); // Write out value data.Write(value); } // At this point, the ResourceManager header has been written. // Finish RuntimeResourceSet header // The reader expects a list of user defined type names // following the size of the list, write 0 for this // writer implementation bw.Write((int)0); // Write out the name-related items for lookup. // Note that the hash array and the namePositions array must // be sorted in parallel. Array.Sort(nameHashes, namePositions); // Prepare to write sorted name hashes (alignment fixup) // Note: For 64-bit machines, these MUST be aligned on 8 byte // boundaries! Pointers on IA64 must be aligned! And we'll // run faster on X86 machines too. bw.Flush(); int alignBytes = ((int)bw.BaseStream.Position) & 7; if (alignBytes > 0) { for (int i = 0; i < 8 - alignBytes; i++) bw.Write("PAD"[i % 3]); } // Write out sorted name hashes. // Align to 8 bytes. Debug.Assert((bw.BaseStream.Position & 7) == 0, "ResourceWriter: Name hashes array won't be 8 byte aligned! Ack!"); foreach (int hash in nameHashes) bw.Write(hash); // Write relative positions of all the names in the file. // Note: this data is 4 byte aligned, occurring immediately // after the 8 byte aligned name hashes (whose length may // potentially be odd). Debug.Assert((bw.BaseStream.Position & 3) == 0, "ResourceWriter: Name positions array won't be 4 byte aligned! Ack!"); foreach (int pos in namePositions) bw.Write(pos); // Flush all BinaryWriters to their underlying streams. bw.Flush(); names.Flush(); data.Flush(); // Write offset to data section int startOfDataSection = (int)(bw.Seek(0, SeekOrigin.Current) + nameSection.Length); startOfDataSection += 4; // We're writing an int to store this data, adding more bytes to the header bw.Write(startOfDataSection); // Write name section. nameSection.Seek(0, SeekOrigin.Begin); nameSection.CopyTo(bw.BaseStream, (int)nameSection.Length); names.Dispose(); // Write data section. Debug.Assert(startOfDataSection == bw.Seek(0, SeekOrigin.Current), "ResourceWriter::Generate - start of data section is wrong!"); dataSection.Position = 0; dataSection.CopyTo(bw.BaseStream); data.Dispose(); } // using(dataSection) <--- Closes dataSection, which was opened w/ FileOptions.DeleteOnClose bw.Flush(); // Indicate we've called Generate _resourceList = null; } private static void Write7BitEncodedInt(BinaryWriter store, int value) { Contract.Requires(store != null); // Write out an int 7 bits at a time. The high bit of the byte, // when on, tells reader to continue reading more bytes. uint v = (uint)value; // support negative numbers while (v >= 0x80) { store.Write((byte)(v | 0x80)); v >>= 7; } store.Write((byte)v); } } }
namespace android.database.sqlite { [global::MonoJavaBridge.JavaClass()] public partial class SQLiteDatabase : android.database.sqlite.SQLiteClosable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static SQLiteDatabase() { InitJNI(); } protected SQLiteDatabase(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaInterface(typeof(global::android.database.sqlite.SQLiteDatabase.CursorFactory_))] public interface CursorFactory : global::MonoJavaBridge.IJavaObject { global::android.database.Cursor newCursor(android.database.sqlite.SQLiteDatabase arg0, android.database.sqlite.SQLiteCursorDriver arg1, java.lang.String arg2, android.database.sqlite.SQLiteQuery arg3); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.database.sqlite.SQLiteDatabase.CursorFactory))] public sealed partial class CursorFactory_ : java.lang.Object, CursorFactory { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static CursorFactory_() { InitJNI(); } internal CursorFactory_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _newCursor2817; global::android.database.Cursor android.database.sqlite.SQLiteDatabase.CursorFactory.newCursor(android.database.sqlite.SQLiteDatabase arg0, android.database.sqlite.SQLiteCursorDriver arg1, java.lang.String arg2, android.database.sqlite.SQLiteQuery arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.database.Cursor>(@__env.CallObjectMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.CursorFactory_._newCursor2817, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.database.Cursor; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.database.Cursor>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.CursorFactory_.staticClass, global::android.database.sqlite.SQLiteDatabase.CursorFactory_._newCursor2817, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.database.Cursor; } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.database.sqlite.SQLiteDatabase.CursorFactory_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/database/sqlite/SQLiteDatabase$CursorFactory")); global::android.database.sqlite.SQLiteDatabase.CursorFactory_._newCursor2817 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.CursorFactory_.staticClass, "newCursor", "(Landroid/database/sqlite/SQLiteDatabase;Landroid/database/sqlite/SQLiteCursorDriver;Ljava/lang/String;Landroid/database/sqlite/SQLiteQuery;)Landroid/database/Cursor;"); } } internal static global::MonoJavaBridge.MethodId _finalize2818; protected override void finalize() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._finalize2818); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._finalize2818); } internal static global::MonoJavaBridge.MethodId _replace2819; public virtual long replace(java.lang.String arg0, java.lang.String arg1, android.content.ContentValues arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._replace2819, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._replace2819, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _close2820; public virtual void close() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._close2820); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._close2820); } internal static global::MonoJavaBridge.MethodId _delete2821; public virtual int delete(java.lang.String arg0, java.lang.String arg1, java.lang.String[] arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._delete2821, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._delete2821, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _insert2822; public virtual long insert(java.lang.String arg0, java.lang.String arg1, android.content.ContentValues arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._insert2822, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._insert2822, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _isReadOnly2823; public virtual bool isReadOnly() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._isReadOnly2823); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._isReadOnly2823); } internal static global::MonoJavaBridge.MethodId _getPath2824; public virtual global::java.lang.String getPath() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._getPath2824)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._getPath2824)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _query2825; public virtual global::android.database.Cursor query(bool arg0, java.lang.String arg1, java.lang.String[] arg2, java.lang.String arg3, java.lang.String[] arg4, java.lang.String arg5, java.lang.String arg6, java.lang.String arg7, java.lang.String arg8) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.database.Cursor>(@__env.CallObjectMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._query2825, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg8))) as android.database.Cursor; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.database.Cursor>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._query2825, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg8))) as android.database.Cursor; } internal static global::MonoJavaBridge.MethodId _query2826; public virtual global::android.database.Cursor query(java.lang.String arg0, java.lang.String[] arg1, java.lang.String arg2, java.lang.String[] arg3, java.lang.String arg4, java.lang.String arg5, java.lang.String arg6, java.lang.String arg7) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.database.Cursor>(@__env.CallObjectMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._query2826, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7))) as android.database.Cursor; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.database.Cursor>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._query2826, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7))) as android.database.Cursor; } internal static global::MonoJavaBridge.MethodId _query2827; public virtual global::android.database.Cursor query(java.lang.String arg0, java.lang.String[] arg1, java.lang.String arg2, java.lang.String[] arg3, java.lang.String arg4, java.lang.String arg5, java.lang.String arg6) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.database.Cursor>(@__env.CallObjectMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._query2827, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6))) as android.database.Cursor; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.database.Cursor>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._query2827, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6))) as android.database.Cursor; } internal static global::MonoJavaBridge.MethodId _create2828; public static global::android.database.sqlite.SQLiteDatabase create(android.database.sqlite.SQLiteDatabase.CursorFactory arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._create2828, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.database.sqlite.SQLiteDatabase; } internal static global::MonoJavaBridge.MethodId _isOpen2829; public virtual bool isOpen() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._isOpen2829); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._isOpen2829); } internal static global::MonoJavaBridge.MethodId _update2830; public virtual int update(java.lang.String arg0, android.content.ContentValues arg1, java.lang.String arg2, java.lang.String[] arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._update2830, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._update2830, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _getVersion2831; public virtual int getVersion() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._getVersion2831); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._getVersion2831); } internal static global::MonoJavaBridge.MethodId _setVersion2832; public virtual void setVersion(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._setVersion2832, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._setVersion2832, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setLocale2833; public virtual void setLocale(java.util.Locale arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._setLocale2833, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._setLocale2833, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _openOrCreateDatabase2834; public static global::android.database.sqlite.SQLiteDatabase openOrCreateDatabase(java.lang.String arg0, android.database.sqlite.SQLiteDatabase.CursorFactory arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._openOrCreateDatabase2834, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.database.sqlite.SQLiteDatabase; } internal static global::MonoJavaBridge.MethodId _openOrCreateDatabase2835; public static global::android.database.sqlite.SQLiteDatabase openOrCreateDatabase(java.io.File arg0, android.database.sqlite.SQLiteDatabase.CursorFactory arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._openOrCreateDatabase2835, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.database.sqlite.SQLiteDatabase; } internal static global::MonoJavaBridge.MethodId _onAllReferencesReleased2836; protected override void onAllReferencesReleased() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._onAllReferencesReleased2836); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._onAllReferencesReleased2836); } internal static global::MonoJavaBridge.MethodId _releaseMemory2837; public static int releaseMemory() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticIntMethod(android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._releaseMemory2837); } internal static global::MonoJavaBridge.MethodId _setLockingEnabled2838; public virtual void setLockingEnabled(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._setLockingEnabled2838, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._setLockingEnabled2838, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _beginTransaction2839; public virtual void beginTransaction() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._beginTransaction2839); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._beginTransaction2839); } internal static global::MonoJavaBridge.MethodId _beginTransactionWithListener2840; public virtual void beginTransactionWithListener(android.database.sqlite.SQLiteTransactionListener arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._beginTransactionWithListener2840, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._beginTransactionWithListener2840, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _endTransaction2841; public virtual void endTransaction() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._endTransaction2841); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._endTransaction2841); } internal static global::MonoJavaBridge.MethodId _setTransactionSuccessful2842; public virtual void setTransactionSuccessful() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._setTransactionSuccessful2842); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._setTransactionSuccessful2842); } internal static global::MonoJavaBridge.MethodId _inTransaction2843; public virtual bool inTransaction() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._inTransaction2843); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._inTransaction2843); } internal static global::MonoJavaBridge.MethodId _isDbLockedByCurrentThread2844; public virtual bool isDbLockedByCurrentThread() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._isDbLockedByCurrentThread2844); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._isDbLockedByCurrentThread2844); } internal static global::MonoJavaBridge.MethodId _isDbLockedByOtherThreads2845; public virtual bool isDbLockedByOtherThreads() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._isDbLockedByOtherThreads2845); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._isDbLockedByOtherThreads2845); } internal static global::MonoJavaBridge.MethodId _yieldIfContended2846; public virtual bool yieldIfContended() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._yieldIfContended2846); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._yieldIfContended2846); } internal static global::MonoJavaBridge.MethodId _yieldIfContendedSafely2847; public virtual bool yieldIfContendedSafely(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._yieldIfContendedSafely2847, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._yieldIfContendedSafely2847, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _yieldIfContendedSafely2848; public virtual bool yieldIfContendedSafely() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._yieldIfContendedSafely2848); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._yieldIfContendedSafely2848); } internal static global::MonoJavaBridge.MethodId _getSyncedTables2849; public virtual global::java.util.Map getSyncedTables() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Map>(@__env.CallObjectMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._getSyncedTables2849)) as java.util.Map; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Map>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._getSyncedTables2849)) as java.util.Map; } internal static global::MonoJavaBridge.MethodId _openDatabase2850; public static global::android.database.sqlite.SQLiteDatabase openDatabase(java.lang.String arg0, android.database.sqlite.SQLiteDatabase.CursorFactory arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._openDatabase2850, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.database.sqlite.SQLiteDatabase; } internal static global::MonoJavaBridge.MethodId _getMaximumSize2851; public virtual long getMaximumSize() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._getMaximumSize2851); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._getMaximumSize2851); } internal static global::MonoJavaBridge.MethodId _setMaximumSize2852; public virtual long setMaximumSize(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._setMaximumSize2852, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._setMaximumSize2852, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getPageSize2853; public virtual long getPageSize() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._getPageSize2853); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._getPageSize2853); } internal static global::MonoJavaBridge.MethodId _setPageSize2854; public virtual void setPageSize(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._setPageSize2854, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._setPageSize2854, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _markTableSyncable2855; public virtual void markTableSyncable(java.lang.String arg0, java.lang.String arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._markTableSyncable2855, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._markTableSyncable2855, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _markTableSyncable2856; public virtual void markTableSyncable(java.lang.String arg0, java.lang.String arg1, java.lang.String arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._markTableSyncable2856, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._markTableSyncable2856, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _findEditTable2857; public static global::java.lang.String findEditTable(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._findEditTable2857, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _compileStatement2858; public virtual global::android.database.sqlite.SQLiteStatement compileStatement(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._compileStatement2858, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.database.sqlite.SQLiteStatement; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._compileStatement2858, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.database.sqlite.SQLiteStatement; } internal static global::MonoJavaBridge.MethodId _queryWithFactory2859; public virtual global::android.database.Cursor queryWithFactory(android.database.sqlite.SQLiteDatabase.CursorFactory arg0, bool arg1, java.lang.String arg2, java.lang.String[] arg3, java.lang.String arg4, java.lang.String[] arg5, java.lang.String arg6, java.lang.String arg7, java.lang.String arg8, java.lang.String arg9) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.database.Cursor>(@__env.CallObjectMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._queryWithFactory2859, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg8), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg9))) as android.database.Cursor; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.database.Cursor>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._queryWithFactory2859, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg8), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg9))) as android.database.Cursor; } internal static global::MonoJavaBridge.MethodId _rawQuery2860; public virtual global::android.database.Cursor rawQuery(java.lang.String arg0, java.lang.String[] arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.database.Cursor>(@__env.CallObjectMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._rawQuery2860, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.database.Cursor; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.database.Cursor>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._rawQuery2860, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.database.Cursor; } internal static global::MonoJavaBridge.MethodId _rawQueryWithFactory2861; public virtual global::android.database.Cursor rawQueryWithFactory(android.database.sqlite.SQLiteDatabase.CursorFactory arg0, java.lang.String arg1, java.lang.String[] arg2, java.lang.String arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.database.Cursor>(@__env.CallObjectMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._rawQueryWithFactory2861, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.database.Cursor; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.database.Cursor>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._rawQueryWithFactory2861, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.database.Cursor; } internal static global::MonoJavaBridge.MethodId _insertOrThrow2862; public virtual long insertOrThrow(java.lang.String arg0, java.lang.String arg1, android.content.ContentValues arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._insertOrThrow2862, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._insertOrThrow2862, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _replaceOrThrow2863; public virtual long replaceOrThrow(java.lang.String arg0, java.lang.String arg1, android.content.ContentValues arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._replaceOrThrow2863, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._replaceOrThrow2863, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _insertWithOnConflict2864; public virtual long insertWithOnConflict(java.lang.String arg0, java.lang.String arg1, android.content.ContentValues arg2, int arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._insertWithOnConflict2864, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._insertWithOnConflict2864, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _updateWithOnConflict2865; public virtual int updateWithOnConflict(java.lang.String arg0, android.content.ContentValues arg1, java.lang.String arg2, java.lang.String[] arg3, int arg4) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._updateWithOnConflict2865, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._updateWithOnConflict2865, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } internal static global::MonoJavaBridge.MethodId _execSQL2866; public virtual void execSQL(java.lang.String arg0, java.lang.Object[] arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._execSQL2866, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._execSQL2866, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _execSQL2867; public virtual void execSQL(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._execSQL2867, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._execSQL2867, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _needUpgrade2868; public virtual bool needUpgrade(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase._needUpgrade2868, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.sqlite.SQLiteDatabase.staticClass, global::android.database.sqlite.SQLiteDatabase._needUpgrade2868, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public static int CONFLICT_ROLLBACK { get { return 1; } } public static int CONFLICT_ABORT { get { return 2; } } public static int CONFLICT_FAIL { get { return 3; } } public static int CONFLICT_IGNORE { get { return 4; } } public static int CONFLICT_REPLACE { get { return 5; } } public static int CONFLICT_NONE { get { return 0; } } public static int SQLITE_MAX_LIKE_PATTERN_LENGTH { get { return 50000; } } public static int OPEN_READWRITE { get { return 0; } } public static int OPEN_READONLY { get { return 1; } } public static int NO_LOCALIZED_COLLATORS { get { return 16; } } public static int CREATE_IF_NECESSARY { get { return 268435456; } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.database.sqlite.SQLiteDatabase.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/database/sqlite/SQLiteDatabase")); global::android.database.sqlite.SQLiteDatabase._finalize2818 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "finalize", "()V"); global::android.database.sqlite.SQLiteDatabase._replace2819 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "replace", "(Ljava/lang/String;Ljava/lang/String;Landroid/content/ContentValues;)J"); global::android.database.sqlite.SQLiteDatabase._close2820 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "close", "()V"); global::android.database.sqlite.SQLiteDatabase._delete2821 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "delete", "(Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;)I"); global::android.database.sqlite.SQLiteDatabase._insert2822 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "insert", "(Ljava/lang/String;Ljava/lang/String;Landroid/content/ContentValues;)J"); global::android.database.sqlite.SQLiteDatabase._isReadOnly2823 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "isReadOnly", "()Z"); global::android.database.sqlite.SQLiteDatabase._getPath2824 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "getPath", "()Ljava/lang/String;"); global::android.database.sqlite.SQLiteDatabase._query2825 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "query", "(ZLjava/lang/String;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;"); global::android.database.sqlite.SQLiteDatabase._query2826 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "query", "(Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;"); global::android.database.sqlite.SQLiteDatabase._query2827 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "query", "(Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;"); global::android.database.sqlite.SQLiteDatabase._create2828 = @__env.GetStaticMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "create", "(Landroid/database/sqlite/SQLiteDatabase$CursorFactory;)Landroid/database/sqlite/SQLiteDatabase;"); global::android.database.sqlite.SQLiteDatabase._isOpen2829 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "isOpen", "()Z"); global::android.database.sqlite.SQLiteDatabase._update2830 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "update", "(Ljava/lang/String;Landroid/content/ContentValues;Ljava/lang/String;[Ljava/lang/String;)I"); global::android.database.sqlite.SQLiteDatabase._getVersion2831 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "getVersion", "()I"); global::android.database.sqlite.SQLiteDatabase._setVersion2832 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "setVersion", "(I)V"); global::android.database.sqlite.SQLiteDatabase._setLocale2833 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "setLocale", "(Ljava/util/Locale;)V"); global::android.database.sqlite.SQLiteDatabase._openOrCreateDatabase2834 = @__env.GetStaticMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "openOrCreateDatabase", "(Ljava/lang/String;Landroid/database/sqlite/SQLiteDatabase$CursorFactory;)Landroid/database/sqlite/SQLiteDatabase;"); global::android.database.sqlite.SQLiteDatabase._openOrCreateDatabase2835 = @__env.GetStaticMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "openOrCreateDatabase", "(Ljava/io/File;Landroid/database/sqlite/SQLiteDatabase$CursorFactory;)Landroid/database/sqlite/SQLiteDatabase;"); global::android.database.sqlite.SQLiteDatabase._onAllReferencesReleased2836 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "onAllReferencesReleased", "()V"); global::android.database.sqlite.SQLiteDatabase._releaseMemory2837 = @__env.GetStaticMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "releaseMemory", "()I"); global::android.database.sqlite.SQLiteDatabase._setLockingEnabled2838 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "setLockingEnabled", "(Z)V"); global::android.database.sqlite.SQLiteDatabase._beginTransaction2839 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "beginTransaction", "()V"); global::android.database.sqlite.SQLiteDatabase._beginTransactionWithListener2840 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "beginTransactionWithListener", "(Landroid/database/sqlite/SQLiteTransactionListener;)V"); global::android.database.sqlite.SQLiteDatabase._endTransaction2841 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "endTransaction", "()V"); global::android.database.sqlite.SQLiteDatabase._setTransactionSuccessful2842 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "setTransactionSuccessful", "()V"); global::android.database.sqlite.SQLiteDatabase._inTransaction2843 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "inTransaction", "()Z"); global::android.database.sqlite.SQLiteDatabase._isDbLockedByCurrentThread2844 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "isDbLockedByCurrentThread", "()Z"); global::android.database.sqlite.SQLiteDatabase._isDbLockedByOtherThreads2845 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "isDbLockedByOtherThreads", "()Z"); global::android.database.sqlite.SQLiteDatabase._yieldIfContended2846 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "yieldIfContended", "()Z"); global::android.database.sqlite.SQLiteDatabase._yieldIfContendedSafely2847 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "yieldIfContendedSafely", "(J)Z"); global::android.database.sqlite.SQLiteDatabase._yieldIfContendedSafely2848 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "yieldIfContendedSafely", "()Z"); global::android.database.sqlite.SQLiteDatabase._getSyncedTables2849 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "getSyncedTables", "()Ljava/util/Map;"); global::android.database.sqlite.SQLiteDatabase._openDatabase2850 = @__env.GetStaticMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "openDatabase", "(Ljava/lang/String;Landroid/database/sqlite/SQLiteDatabase$CursorFactory;I)Landroid/database/sqlite/SQLiteDatabase;"); global::android.database.sqlite.SQLiteDatabase._getMaximumSize2851 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "getMaximumSize", "()J"); global::android.database.sqlite.SQLiteDatabase._setMaximumSize2852 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "setMaximumSize", "(J)J"); global::android.database.sqlite.SQLiteDatabase._getPageSize2853 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "getPageSize", "()J"); global::android.database.sqlite.SQLiteDatabase._setPageSize2854 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "setPageSize", "(J)V"); global::android.database.sqlite.SQLiteDatabase._markTableSyncable2855 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "markTableSyncable", "(Ljava/lang/String;Ljava/lang/String;)V"); global::android.database.sqlite.SQLiteDatabase._markTableSyncable2856 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "markTableSyncable", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V"); global::android.database.sqlite.SQLiteDatabase._findEditTable2857 = @__env.GetStaticMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "findEditTable", "(Ljava/lang/String;)Ljava/lang/String;"); global::android.database.sqlite.SQLiteDatabase._compileStatement2858 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "compileStatement", "(Ljava/lang/String;)Landroid/database/sqlite/SQLiteStatement;"); global::android.database.sqlite.SQLiteDatabase._queryWithFactory2859 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "queryWithFactory", "(Landroid/database/sqlite/SQLiteDatabase$CursorFactory;ZLjava/lang/String;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;"); global::android.database.sqlite.SQLiteDatabase._rawQuery2860 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "rawQuery", "(Ljava/lang/String;[Ljava/lang/String;)Landroid/database/Cursor;"); global::android.database.sqlite.SQLiteDatabase._rawQueryWithFactory2861 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "rawQueryWithFactory", "(Landroid/database/sqlite/SQLiteDatabase$CursorFactory;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;"); global::android.database.sqlite.SQLiteDatabase._insertOrThrow2862 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "insertOrThrow", "(Ljava/lang/String;Ljava/lang/String;Landroid/content/ContentValues;)J"); global::android.database.sqlite.SQLiteDatabase._replaceOrThrow2863 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "replaceOrThrow", "(Ljava/lang/String;Ljava/lang/String;Landroid/content/ContentValues;)J"); global::android.database.sqlite.SQLiteDatabase._insertWithOnConflict2864 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "insertWithOnConflict", "(Ljava/lang/String;Ljava/lang/String;Landroid/content/ContentValues;I)J"); global::android.database.sqlite.SQLiteDatabase._updateWithOnConflict2865 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "updateWithOnConflict", "(Ljava/lang/String;Landroid/content/ContentValues;Ljava/lang/String;[Ljava/lang/String;I)I"); global::android.database.sqlite.SQLiteDatabase._execSQL2866 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "execSQL", "(Ljava/lang/String;[Ljava/lang/Object;)V"); global::android.database.sqlite.SQLiteDatabase._execSQL2867 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "execSQL", "(Ljava/lang/String;)V"); global::android.database.sqlite.SQLiteDatabase._needUpgrade2868 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteDatabase.staticClass, "needUpgrade", "(I)Z"); } } }
//--------------------------------------------------------------------- // Author: Keith Hill, jachymko // // Description: Interface for writing and throwing exceptions // // Creation Date: Dec 29, 2006 //--------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Management.Automation; using System.Security; using System.Text; using System.Net.Mail; using System.Xml.XPath; namespace Pscx.Commands { public interface IPscxErrorHandler { void HandleError(bool terminating, ErrorRecord errorRecord); void HandleUnauthorizedAccessError(bool terminating, string objectName, Exception exc); void HandleFileAlreadyExistsError(bool terminating, string path, Exception exc); void HandleFileError(bool terminating, string path, Exception exc); void ThrowPlatformNotSupported(string message); void ThrowNoPreferenceVariable(string parameter, string preference); void ThrowIncompatiblePreferenceVariableType(string parameter, string expectedType, string actualType); void ThrowUnknownEncoding(string encodingName); void ThrowIllegalCharsInPath(string path); void ThrowIncompatibleArrayParameters(string paramName1, string paramName2, string errorMessage); void ThrowInvalidFileEncodingArgument(string parameterName, string specifiedValue, string validValues); void WriteDirectoryNotEmptyError(string path); void WriteDirectoryNotFoundError(string path); void WriteFileError(string path, Exception exc); void WriteFileNotFoundError(string path); void WriteFileAlreadyExistsError(string path, Exception exc); void WriteGetHostEntryError(string host, Exception exc); void WriteInvalidInputError(IEnumerable<Type> expected, object actual); void WriteInvalidIPAddressError(string invalidIPAddress); void WriteInvalidOperationError(object target, InvalidOperationException exc); void WriteIsNotReparsePointError(string path); void WriteLastWin32Error(string errorId, ErrorCategory category, object target); void WriteLastWin32Error(string errorId, object target); void WriteWin32Error(Exception exc, string errorId, ErrorCategory category, object target); void WriteProcessFailedToStart(Process target, Exception exc); void WriteSmtpSendMessageError(object target, SmtpException exc); void WriteHttpResourceError(string url, Exception exc); void WriteGetHttpResourceError(string url, Exception exc); void WriteRemoveHttpResourceError(string url, Exception exc); void WriteXmlError(Exception exc); void WriteXmlSchemaError(Exception exc); void WriteXsltError(Exception exc); void WriteXPathExpressionError(string xpathExpression, XPathException ex); void WriteAlternateDataStreamDoentExist(string adsName, string filename); } partial class PscxCmdlet : IPscxErrorHandler { void IPscxErrorHandler.HandleError(bool terminating, ErrorRecord record) { if (terminating) { ThrowTerminatingError(record); } else { WriteError(record); } } void IPscxErrorHandler.HandleUnauthorizedAccessError(bool terminating, string objectName, Exception inner) { string message = string.Format(Resources.Errors.UnauthorizedAccessException, objectName); Exception exc = new UnauthorizedAccessException(message, inner); ErrorRecord errorRecord = new ErrorRecord(exc, "UnauthorizedAccess", ErrorCategory.SecurityError, objectName); ErrorHandler.HandleError(terminating, errorRecord); } void IPscxErrorHandler.HandleFileAlreadyExistsError(bool terminating, string path, Exception exc) { ErrorRecord error = new ErrorRecord(exc, "FileAlreadyExists", ErrorCategory.InvalidOperation, path); if (terminating) ThrowTerminatingError(error); else WriteError(error); } void IPscxErrorHandler.HandleFileError(bool terminating, string path, Exception exc) { ErrorCategory errorCategory; if ((exc is UnauthorizedAccessException) || (exc is SecurityException)) { ErrorHandler.HandleUnauthorizedAccessError(terminating, path, exc); return; } else if ((exc is FileNotFoundException) || (exc is DirectoryNotFoundException)) { errorCategory = ErrorCategory.ObjectNotFound; } else { errorCategory = ErrorCategory.NotSpecified; } ErrorRecord error = new ErrorRecord(exc, "FileError", errorCategory, path); ErrorHandler.HandleError(terminating, error); } void IPscxErrorHandler.ThrowNoPreferenceVariable(string parameter, string preference) { string msg = string.Format(Resources.Errors.NeitherParameterNorPreferenceSpecified, parameter, preference); ArgumentException ex = new ArgumentException(msg); ThrowTerminatingError(new ErrorRecord(ex, "PreferenceVariableNotFound", ErrorCategory.InvalidArgument, null)); } void IPscxErrorHandler.ThrowIncompatiblePreferenceVariableType(string parameter, string expectedType, string actualType) { string msg = string.Format(Resources.Errors.PreferenceVariableIncompatibleType, parameter, expectedType, actualType); ArgumentException ex = new ArgumentException(msg); ThrowTerminatingError(new ErrorRecord(ex, "PreferenceVariableIncompatibleType", ErrorCategory.InvalidArgument, null)); } void IPscxErrorHandler.ThrowPlatformNotSupported(string message) { PlatformNotSupportedException ex = new PlatformNotSupportedException(message); ThrowTerminatingError(new ErrorRecord(ex, "PlatformNotSupported", ErrorCategory.NotImplemented, null)); } void IPscxErrorHandler.ThrowUnknownEncoding(string encodingName) { string msg = string.Format(Resources.Errors.UnknownEncoding, encodingName); ArgumentException ex = new ArgumentException(msg, "encodingName"); ThrowTerminatingError(new ErrorRecord(ex, "InvalidArgumentError", ErrorCategory.InvalidArgument, encodingName)); } void IPscxErrorHandler.ThrowIllegalCharsInPath(string path) { string msg = string.Format(Resources.Errors.IllegalCharsInPath, path); ArgumentException ex = new ArgumentException(msg); ThrowTerminatingError(new ErrorRecord(ex, "IllegalCharsInPathError", ErrorCategory.InvalidArgument, path)); } void IPscxErrorHandler.ThrowIncompatibleArrayParameters(string paramName1, string paramName2, string errorMessage) { string msg = string.Format(Resources.Errors.IncompatibleArrayParameters, paramName1, paramName2, errorMessage); var ex = new ArgumentException(msg); string parameters = "Parameters: " + paramName1 + " and " + paramName2; ThrowTerminatingError(new ErrorRecord(ex, "IncompatibleArrayParameters", ErrorCategory.InvalidArgument, parameters)); } void IPscxErrorHandler.ThrowInvalidFileEncodingArgument(string parameterName, string specifiedValue, string validValues) { string msg = string.Format(Resources.Errors.InvalidFileEncodingArgument, parameterName, specifiedValue, validValues); var ex = new ArgumentException(msg); ThrowTerminatingError(new ErrorRecord(ex, "InvalidFileEncodingArgument", ErrorCategory.InvalidArgument, (object)null)); } void IPscxErrorHandler.WriteDirectoryNotEmptyError(string path) { string msg = string.Format(Resources.Errors.DirectoryNotEmpty, path); Exception ex = new IOException(msg); WriteError(new ErrorRecord(ex, "DirectoryNotEmpty", ErrorCategory.InvalidArgument, path)); } void IPscxErrorHandler.WriteDirectoryNotFoundError(string path) { string msg = string.Format(Resources.Errors.DirectoryNotFound, path); Exception ex = new DirectoryNotFoundException(msg); ErrorHandler.WriteFileError(path, ex); } void IPscxErrorHandler.WriteFileNotFoundError(string path) { string msg = string.Format(Resources.Errors.FileNotFound, path); Exception ex = new FileNotFoundException(msg, path); ErrorHandler.WriteFileError(path, ex); } void IPscxErrorHandler.WriteFileAlreadyExistsError(string path, Exception exc) { ErrorHandler.HandleFileAlreadyExistsError(false, path, exc); } void IPscxErrorHandler.WriteFileError(string path, Exception exc) { ErrorHandler.HandleFileError(false, path, exc); } void IPscxErrorHandler.WriteInvalidIPAddressError(string invalidIPAddress) { WriteError(PscxErrorRecord.InvalidIPAddress(invalidIPAddress)); } void IPscxErrorHandler.WriteGetHostEntryError(string host, Exception exc) { WriteError(PscxErrorRecord.GetHostEntryError(host, exc)); } void IPscxErrorHandler.WriteIsNotReparsePointError(string path) { string msg = string.Format(Resources.Errors.IsNotReparsePoint, path); Exception ex = new ArgumentException(msg); WriteError(new ErrorRecord(ex, "PathIsNotReparsePoint", ErrorCategory.InvalidArgument, path)); } void IPscxErrorHandler.WriteInvalidInputError(IEnumerable<Type> expected, object actual) { const string Comma = ", "; Dictionary<Type, string> typeNames = new Dictionary<Type, string>(); foreach(Type t in expected) { if (t.IsGenericType) { if (t.GetGenericTypeDefinition() == Type.GetType("System.Collections.Generic.IEnumerable`1")) { Type itemType = t.GetGenericArguments()[0]; typeNames[itemType] = itemType.Name; } else { typeNames[t] = t.ToString(); } } else { typeNames[t] = t.Name; } } string[] typeNamesArray = new List<string>(typeNames.Values).ToArray(); string typeNamesString = string.Join(Comma, typeNamesArray); string msg = string.Format(Resources.Errors.InvalidInput, typeNamesString, actual.GetType()); ArgumentException ex = new ArgumentException(msg); WriteError(new ErrorRecord(ex, "InvalidPipelineObjectType", ErrorCategory.InvalidData, actual)); } void IPscxErrorHandler.WriteInvalidOperationError(object target, InvalidOperationException exc) { WriteError(new ErrorRecord(exc, "InvalidOperationError", ErrorCategory.InvalidOperation, target)); } void IPscxErrorHandler.WriteLastWin32Error(string errorId, object target) { ErrorHandler.WriteLastWin32Error(errorId, ErrorCategory.NotSpecified, target); } void IPscxErrorHandler.WriteLastWin32Error(string errorId, ErrorCategory category, object target) { ErrorHandler.WriteWin32Error(PscxException.LastWin32Exception(), errorId, category, target); } void IPscxErrorHandler.WriteWin32Error(Exception exc, string errorId, ErrorCategory category, object target) { WriteError(new ErrorRecord(exc, errorId, category, target)); } void IPscxErrorHandler.WriteProcessFailedToStart(Process target, Exception exc) { WriteError(new ErrorRecord(exc, "ProcessStartError", ErrorCategory.NotSpecified, target)); } void IPscxErrorHandler.WriteSmtpSendMessageError(object target, SmtpException exc) { WriteError(new ErrorRecord(exc, "SmtpError", ErrorCategory.NotSpecified, target)); } void IPscxErrorHandler.WriteHttpResourceError(string url, Exception exc) { WriteError(new ErrorRecord(exc, "HttpResourceCommandBase", ErrorCategory.NotSpecified, url)); } void IPscxErrorHandler.WriteGetHttpResourceError(string url, Exception exc) { WriteError(new ErrorRecord(exc, "GetHttpResource", ErrorCategory.NotSpecified, url)); } void IPscxErrorHandler.WriteRemoveHttpResourceError(string url, Exception exc) { WriteError(new ErrorRecord(exc, "RemoveHttpResource", ErrorCategory.NotSpecified, url)); } void IPscxErrorHandler.WriteXmlError(Exception exc) { ErrorCategory errorCategory = ErrorCategory.NotSpecified; if (exc is System.Xml.XmlException) { errorCategory = ErrorCategory.InvalidOperation; } WriteError(new ErrorRecord(exc, "XmlError", errorCategory, null)); } void IPscxErrorHandler.WriteXmlSchemaError(Exception exc) { ErrorCategory errorCategory = ErrorCategory.NotSpecified; if (exc is System.Xml.Schema.XmlSchemaException) { errorCategory = ErrorCategory.InvalidData; } WriteError(new ErrorRecord(exc, "XmlSchemaError", errorCategory, null)); } void IPscxErrorHandler.WriteXsltError(Exception exc) { ErrorCategory errorCategory = ErrorCategory.NotSpecified; if (exc is System.Xml.Xsl.XsltException) { errorCategory = ErrorCategory.InvalidOperation; } WriteError(new ErrorRecord(exc, "XsltError", errorCategory, null)); } void IPscxErrorHandler.WriteXPathExpressionError(string xpathExpression, XPathException ex) { ThrowTerminatingError(new ErrorRecord(ex, "InvalidXPathExpression", ErrorCategory.InvalidArgument, xpathExpression)); } void IPscxErrorHandler.WriteAlternateDataStreamDoentExist(string adsName, string filename) { var msg = String.Format("Alternate data stream named: {0} does not exist", adsName); Exception ex = new ArgumentException(msg); WriteError(new ErrorRecord(ex, "AlternateDataStreamDoesntExist", ErrorCategory.InvalidArgument, filename)); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using static System.Environment; namespace Bud { /// <summary> /// This class contains a bunch of static methods for batch execution of processes. /// The executed processes must not expect any input. /// </summary> /// <remarks> /// The naming of the functions is partially inspired by Python's subprocess API. /// </remarks> public static class Exec { /// <summary> /// Runs the executable at path '<paramref name="executablePath" />' /// with the given args '<paramref name="args" />' in the /// given working directory '<paramref name="cwd" />', /// waits for the executable to finish, /// and returns the exit code of the process. /// </summary> /// <param name="executablePath">the path of the executable to run.</param> /// <param name="args">the args to be passed to the executable.</param> /// <param name="cwd"> /// the working directory in which to run. If omitted, the executable will run in the current /// working directory. /// </param> /// <param name="env">environment variables to pass to the process.</param> /// <param name="stdout"> /// the text writer to which the standard output of the process should be written. /// If no text writer is given, then the output will be streamed to the standard output of the calling process /// </param> /// <param name="stderr"> /// the text writer to which the standard error of the process should be written. /// If no text writer is given, then the standard error will be streamed to the standard error of the calling process /// </param> /// <param name="stdin">the contents of this text reader will be </param> /// <returns>the process object that was used to run the process.</returns> /// <remarks> /// The standard output and standard error of the process are redirected to standard output and /// standard error of this process. /// <para>This method blocks until the process finishes.</para> /// </remarks> public static Process Run(string executablePath, string args = null, string cwd = null, IDictionary<string, string> env = null, TextWriter stdout = null, TextWriter stderr = null, TextReader stdin = null) { var process = CreateProcess(executablePath, args, cwd, env); HandleStdout(stdout, process); HandleStderr(stderr, process); process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); HandleStdin(stdin, process); process.WaitForExit(); return process; } /// <summary> /// Runs the executable at path '<paramref name="executablePath" />' /// with the given args '<paramref name="args" />' in the /// given working directory '<paramref name="cwd" />', /// waits for the executable to finish, /// and returns the exit code of the process. /// </summary> /// <param name="executablePath">the path of the executable to run.</param> /// <param name="args">the args to be passed to the executable.</param> /// <param name="cwd"> /// the working directory in which to run. If omitted, the executable will run in the current /// working directory. /// </param> /// <param name="env">environment variables to pass to the process.</param> /// <param name="stdin">the contents of this text reader will be </param> /// <returns>the process object that was used to run the process.</returns> /// <remarks> /// The standard output and standard error of the process are suppressed. /// <para>This method blocks until the process finishes.</para> /// </remarks> public static Process Call(string executablePath, string args = null, string cwd = null, IDictionary<string, string> env = null, TextReader stdin = null) => Run(executablePath, args, cwd, env, stdout: TextWriter.Null, stderr: TextWriter.Null, stdin: stdin); /// <summary> /// Runs the command in batch mode (without any input), suppresses all output, and throws an exception /// if it returns a no-zero error code. /// </summary> /// <param name="executablePath">the path of the executable to run.</param> /// <param name="args">the args to be passed to the executable.</param> /// <param name="cwd"> /// the working directory in which to run. If omitted, the executable will run in the current /// working directory. /// </param> /// <param name="env">environment variables to pass to the process.</param> /// <param name="stdin">the contents of this text reader will be </param> /// <returns>the <see cref="Process" />object used to run the executable.</returns> /// <exception cref="ExecException"> /// thrown if the output exits with non-zero error code. The message /// of the exception will contain the error output and the exit code. /// </exception> public static Process CheckCall(string executablePath, string args = null, string cwd = null, IDictionary<string, string> env = null, TextReader stdin = null) { var stderr = new StringWriter(); var process = Run(executablePath, args, cwd, env, TextWriter.Null, stderr, stdin); AssertProcessSucceeded(executablePath, args, cwd, stderr.ToString(), process.ExitCode); return process; } /// <summary> /// Runs the executable at <paramref name="executablePath" /> in batch mode (not passing any input /// to the process), captures all its standard output (ignoring standard error) into a string, /// waits for the process to finish, and returns the captured output as a string upon completion. /// </summary> /// <param name="executablePath">the path of the executable to run.</param> /// <param name="args">the args to be passed to the executable.</param> /// <param name="cwd"> /// the working directory in which to run. If omitted, the executable will run in the current /// working directory. /// </param> /// <param name="env">environment variables to pass to the process.</param> /// <param name="stdin">the contents of this text reader will be </param> /// <returns>the captured output of the executed process.</returns> /// <exception cref="ExecException"> /// thrown if the output exits with non-zero error code. The message /// of the exception will contain the error output and the exit code. /// </exception> public static string CheckOutput(string executablePath, string args = null, string cwd = null, IDictionary<string, string> env = null, TextReader stdin = null) { var stderr = new StringWriter(); var stdout = new StringWriter(); var process = Run(executablePath, args, cwd, env, stdout, stderr, stdin); AssertProcessSucceeded(executablePath, args, cwd, stderr.ToString(), process.ExitCode); return stdout.ToString(); } /// <summary> /// Converts a list of command-line parameters to a string. This implementation conforms to the /// specification at https://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.arguments. /// </summary> /// <param name="args">a list of command-line parameters.</param> /// <returns> /// A string that can be used as the <paramref name="args" /> parameter /// to the process-invoking functions like <see cref="CheckOutput" /> and others. /// </returns> public static string Args(params string[] args) => Args((IEnumerable<string>) args); /// <summary> /// Converts a list of command-line parameters to a string. This implementation conforms to the /// specification at https://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.arguments. /// </summary> /// <param name="args">a list of command-line parameters.</param> /// <returns> /// A string that can be used as the <paramref name="args" /> parameter /// to the process-invoking functions like <see cref="CheckOutput" /> and others. /// </returns> public static string Args(IEnumerable<string> args) => string.Join(" ", args.Select(Arg)); /// <summary> /// Turns the given string into a command-line argument usable in functions like <see cref="Run"/>. /// If necessary, this function will escape special characters the string or enclose the string in /// quotation marks. /// /// <para> /// Example use: /// <code> /// Run("git", $"commit -am {Arg("This is a commit message.")}"); /// </code> /// </para> /// </summary> /// <param name="arg"></param> /// <returns>a (potentially escaped and quoted) string that can be inserted as an argument into /// a command line.</returns> public static string Arg(string arg) { var containsSpaces = arg.Contains(" "); var quotesEscaped = arg.Replace("\"", containsSpaces ? GetQuotedArgQuoteEscape() : GetArgQuoteEscape()); return containsSpaces ? $"\"{quotesEscaped}\"" : quotesEscaped; } /// <returns>a copy of the current processes' environment.</returns> public static IDictionary<string, string> EnvCopy(params Tuple<string, string>[] overrides) { var envCopy = ToStringDictionary(GetEnvironmentVariables()); foreach (var envVar in overrides) { envCopy[envVar.Item1] = envVar.Item2; } return envCopy; } /// <param name="varName">The name of the environment variable.</param> /// <param name="varValue">The value of the environment variable.</param> /// <returns>a 2-element tuple that can be used in the <see cref="EnvCopy" /> method.</returns> public static Tuple<string, string> EnvVar(string varName, string varValue) => Tuple.Create(varName, varValue); private static void AssertProcessSucceeded(string executablePath, string args, string cwd, string errorOutput, int exitCode) { if (exitCode != 0) { throw new ExecException(executablePath, args, cwd, errorOutput, exitCode); } } private static Process CreateProcess(string executablePath, string args = null, string cwd = null, IDictionary<string, string> env = null) { var process = new Process(); var argumentsString = args ?? string.Empty; process.StartInfo = new ProcessStartInfo(executablePath) { CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = true, Arguments = argumentsString, }; if (env != null) { process.StartInfo.Environment.Clear(); foreach (var envVar in env) { process.StartInfo.Environment[envVar.Key] = envVar.Value; } } if (cwd != null) { process.StartInfo.WorkingDirectory = cwd; } return process; } private static Dictionary<string, string> ToStringDictionary(IDictionary originalDict) { var dictEnum = originalDict.GetEnumerator(); var stringDictionary = new Dictionary<string, string>(); while (dictEnum.MoveNext()) { stringDictionary.Add((string) dictEnum.Key, (string) dictEnum.Value); } return stringDictionary; } private static void HandleStdout(TextWriter stdout, Process process) { if (stdout == null) { process.OutputDataReceived += ProcessOnOutputDataReceived; } else { process.OutputDataReceived += (sender, eventArgs) => { if (eventArgs.Data != null) { stdout.WriteLine(eventArgs.Data); } }; } } private static void HandleStderr(TextWriter stderr, Process process) { if (stderr == null) { process.ErrorDataReceived += ProcessOnErrorDataReceived; } else { process.ErrorDataReceived += (sender, eventArgs) => { if (eventArgs.Data != null) { stderr.WriteLine(eventArgs.Data); } }; } } private static void HandleStdin(TextReader stdin, Process process) { if (stdin == null) { return; } const int bufferLength = 8192; var buffer = new char[bufferLength]; int readCount; while ((readCount = stdin.Read(buffer, 0, bufferLength)) > 0) { process.StandardInput.Write(buffer, 0, readCount); } } private static void ProcessOnOutputDataReceived(object sender, DataReceivedEventArgs outputLine) { if (outputLine.Data != null) { Console.WriteLine(outputLine.Data); } } private static void ProcessOnErrorDataReceived(object sender, DataReceivedEventArgs outputLine) { if (outputLine.Data != null) { Console.Error.WriteLine(outputLine.Data); } } private static string GetQuotedArgQuoteEscape() => OSVersion.Platform == PlatformID.Unix ? "\\\"" : "\"\""; private static string GetArgQuoteEscape() => OSVersion.Platform == PlatformID.Unix ? "\\\"" : "\"\"\""; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal sealed partial class SolutionCrawlerRegistrationService { private sealed partial class WorkCoordinator { private sealed partial class IncrementalAnalyzerProcessor { private sealed class LowPriorityProcessor : GlobalOperationAwareIdleProcessor { private readonly Lazy<ImmutableArray<IIncrementalAnalyzer>> _lazyAnalyzers; private readonly AsyncProjectWorkItemQueue _workItemQueue; public LowPriorityProcessor( IAsynchronousOperationListener listener, IncrementalAnalyzerProcessor processor, Lazy<ImmutableArray<IIncrementalAnalyzer>> lazyAnalyzers, IGlobalOperationNotificationService globalOperationNotificationService, int backOffTimeSpanInMs, CancellationToken shutdownToken) : base(listener, processor, globalOperationNotificationService, backOffTimeSpanInMs, shutdownToken) { _lazyAnalyzers = lazyAnalyzers; _workItemQueue = new AsyncProjectWorkItemQueue(processor._registration.ProgressReporter, processor._registration.Workspace); Start(); } internal ImmutableArray<IIncrementalAnalyzer> Analyzers { get { return _lazyAnalyzers.Value; } } protected override Task WaitAsync(CancellationToken cancellationToken) { return _workItemQueue.WaitAsync(cancellationToken); } protected override async Task ExecuteAsync() { try { // we wait for global operation, higher and normal priority processor to finish its working await WaitForHigherPriorityOperationsAsync().ConfigureAwait(false); // process any available project work, preferring the active project. WorkItem workItem; CancellationTokenSource projectCancellation; if (_workItemQueue.TryTakeAnyWork( this.Processor.GetActiveProject(), this.Processor.DependencyGraph, this.Processor.DiagnosticAnalyzerService, out workItem, out projectCancellation)) { await ProcessProjectAsync(this.Analyzers, workItem, projectCancellation).ConfigureAwait(false); } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } protected override Task HigherQueueOperationTask { get { return Task.WhenAll(this.Processor._highPriorityProcessor.Running, this.Processor._normalPriorityProcessor.Running); } } protected override bool HigherQueueHasWorkItem { get { return this.Processor._highPriorityProcessor.HasAnyWork || this.Processor._normalPriorityProcessor.HasAnyWork; } } protected override void PauseOnGlobalOperation() { _workItemQueue.RequestCancellationOnRunningTasks(); } public void Enqueue(WorkItem item) { this.UpdateLastAccessTime(); // Project work item = item.With(documentId: null, projectId: item.ProjectId, asyncToken: this.Processor._listener.BeginAsyncOperation("WorkItem")); var added = _workItemQueue.AddOrReplace(item); // lower priority queue gets lowest time slot possible. if there is any activity going on in higher queue, it drop whatever it has // and let higher work item run CancelRunningTaskIfHigherQueueHasWorkItem(); Logger.Log(FunctionId.WorkCoordinator_Project_Enqueue, s_enqueueLogger, Environment.TickCount, item.ProjectId, !added); SolutionCrawlerLogger.LogWorkItemEnqueue(this.Processor._logAggregator, item.ProjectId); } private void CancelRunningTaskIfHigherQueueHasWorkItem() { if (!HigherQueueHasWorkItem) { return; } _workItemQueue.RequestCancellationOnRunningTasks(); } private async Task ProcessProjectAsync(ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, CancellationTokenSource source) { if (this.CancellationToken.IsCancellationRequested) { return; } // we do have work item for this project var projectId = workItem.ProjectId; var processedEverything = false; var processingSolution = this.Processor.CurrentSolution; try { using (Logger.LogBlock(FunctionId.WorkCoordinator_ProcessProjectAsync, source.Token)) { var cancellationToken = source.Token; var project = processingSolution.GetProject(projectId); if (project != null) { var semanticsChanged = workItem.InvocationReasons.Contains(PredefinedInvocationReasons.SemanticChanged) || workItem.InvocationReasons.Contains(PredefinedInvocationReasons.SolutionRemoved); using (Processor.EnableCaching(project.Id)) { await RunAnalyzersAsync(analyzers, project, (a, p, c) => a.AnalyzeProjectAsync(p, semanticsChanged, c), cancellationToken).ConfigureAwait(false); } } else { SolutionCrawlerLogger.LogProcessProjectNotExist(this.Processor._logAggregator); RemoveProject(projectId); } } processedEverything = true; } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } finally { // we got cancelled in the middle of processing the project. // let's make sure newly enqueued work item has all the flag needed. if (!processedEverything) { _workItemQueue.AddOrReplace(workItem.Retry(this.Listener.BeginAsyncOperation("ReenqueueWorkItem"))); } SolutionCrawlerLogger.LogProcessProject(this.Processor._logAggregator, projectId.Id, processedEverything); // remove one that is finished running _workItemQueue.RemoveCancellationSource(projectId); } } private void RemoveProject(ProjectId projectId) { foreach (var analyzer in this.Analyzers) { analyzer.RemoveProject(projectId); } } public override void Shutdown() { base.Shutdown(); _workItemQueue.Dispose(); } internal void WaitUntilCompletion_ForTestingPurposesOnly(ImmutableArray<IIncrementalAnalyzer> analyzers, List<WorkItem> items) { CancellationTokenSource source = new CancellationTokenSource(); var uniqueIds = new HashSet<ProjectId>(); foreach (var item in items) { if (uniqueIds.Add(item.ProjectId)) { ProcessProjectAsync(analyzers, item, source).Wait(); } } } internal void WaitUntilCompletion_ForTestingPurposesOnly() { // this shouldn't happen. would like to get some diagnostic while (_workItemQueue.HasAnyWork) { Environment.FailFast("How?"); } } } } } } }
/* * TestXmlDocument.cs - Tests for the "System.Xml.XmlDocument" class. * * Copyright (C) 2002 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using CSUnit; using System; using System.IO; using System.Xml; #if !ECMA_COMPAT public class TestXmlDocument : TestCase { private String[] xml = new String[] { ("<UI version='3.1' stdsetdef='1'>" + " <class>Form1</class>" + " <widget class='QDialog'>" + " <property name='name'>" + " <cstring>Form1</cstring>" + " </property>" + " <property name='geometry'>" + " <rect>" + " <x>0</x>" + " <y>0</y>" + " <width>179</width>" + " <height>158</height>" + " </rect>" + " </property>" + " <property name='caption'>" + " <string>Form1</string>" + " </property>" + " </widget>" + "</UI>"), ("<?xml version='1.0'?>" + "<!DOCTYPE test [" + " <!ELEMENT test (#PCDATA) >" + " <!ENTITY hello 'hello world'>" + "]>" + "<!-- a sample comment -->" + "<test>Brave GNU <![CDATA[World]]> &hello;</test>" + " " + "<?pi HeLlO wOrLd ?>"), ("<test><testempty/></test>"), }; // Constructor. public TestXmlDocument(String name) : base(name) { // Nothing to do here. } // Set up for the tests. protected override void Setup() { // Nothing to do here. } // Clean up after the tests. protected override void Cleanup() { // Nothing to do here. } // Test document construction. public void TestXmlDocumentConstruct() { XmlDocument doc1, doc2; // Simple creation. doc1 = new XmlDocument(); AssertNotNull("Construct (1)", doc1.Implementation); // Create a document from the same name table, // but a different implementation. doc2 = new XmlDocument(doc1.NameTable); AssertEquals("Construct (2)", doc1.NameTable, doc2.NameTable); } // Test the properties of an XmlDocument node. public void TestXmlDocumentProperties() { XmlDocument doc = new XmlDocument(); // Verify the initial conditions. AssertNull("Properties (1)", doc.Attributes); AssertEquals("Properties (2)", "", doc.BaseURI); AssertNotNull("Properties (3)", doc.ChildNodes); AssertNull("Properties (4)", doc.DocumentElement); AssertNull("Properties (5)", doc.DocumentType); AssertNull("Properties (6)", doc.FirstChild); Assert("Properties (7)", !doc.HasChildNodes); Assert("Properties (8)", !doc.IsReadOnly); AssertEquals("Properties (9)", "#document", doc.LocalName); AssertEquals("Properties (10)", "#document", doc.Name); AssertEquals("Properties (11)", "", doc.NamespaceURI); AssertNull("Properties (12)", doc.NextSibling); AssertEquals("Properties (13)", XmlNodeType.Document, doc.NodeType); AssertNull("Properties (14)", doc.OwnerDocument); AssertNull("Properties (15)", doc.ParentNode); AssertEquals("Properties (16)", "", doc.Prefix); AssertNull("Properties (17)", doc.PreviousSibling); AssertEquals("Properties (18)", "", doc.Value); } // Test adding an XML declaration to the document. public void TestXmlDocumentAddXmlDeclaration() { XmlDocument doc = new XmlDocument(); // Add the declaration. XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", null, null); AssertNull("XmlDeclaration (1)", decl.ParentNode); AssertEquals("XmlDeclaration (2)", doc, decl.OwnerDocument); doc.AppendChild(decl); AssertEquals("XmlDeclaration (3)", doc, decl.ParentNode); AssertEquals("XmlDeclaration (4)", doc, decl.OwnerDocument); // Try to add it again, which should fail this time. try { doc.AppendChild(decl); Fail("adding XmlDeclaration node twice"); } catch(InvalidOperationException) { // Success } try { doc.PrependChild(decl); Fail("prepending XmlDeclaration node twice"); } catch(InvalidOperationException) { // Success } // Adding a document type before should fail. XmlDocumentType type = doc.CreateDocumentType("foo", null, null, null); try { doc.PrependChild(type); Fail("prepending XmlDocumentType"); } catch(InvalidOperationException) { // Success } // Adding a document type after should succeed. doc.AppendChild(type); // Adding an element before should fail. XmlElement element = doc.CreateElement("foo"); try { doc.PrependChild(element); Fail("prepending XmlElement"); } catch(InvalidOperationException) { // Success } // Adding the element between decl and type should fail. try { doc.InsertAfter(element, decl); Fail("inserting XmlElement between XmlDeclaration " + "and XmlDocumentType"); } catch(InvalidOperationException) { // Success } try { doc.InsertBefore(element, type); Fail("inserting XmlElement between XmlDeclaration " + "and XmlDocumentType (2)"); } catch(InvalidOperationException) { // Success } // Adding an element after should succeed. doc.AppendChild(element); } // Test adding a document type to the document. public void TestXmlDocumentAddDocumentType() { XmlDocument doc = new XmlDocument(); // Add the document type. XmlDocumentType type = doc.CreateDocumentType("foo", null, null, null); AssertNull("XmlDocumentType (1)", type.ParentNode); AssertEquals("XmlDocumentType (2)", doc, type.OwnerDocument); doc.AppendChild(type); AssertEquals("XmlDocumentType (3)", doc, type.ParentNode); AssertEquals("XmlDocumentType (4)", doc, type.OwnerDocument); // Try to add it again, which should fail this time. try { doc.AppendChild(type); Fail("adding XmlDocumentType node twice"); } catch(InvalidOperationException) { // Success } try { doc.PrependChild(type); Fail("prepending XmlDocumentType node twice"); } catch(InvalidOperationException) { // Success } // Adding an XmlDeclaration after should fail. XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", null, null); try { doc.AppendChild(decl); Fail("appending XmlDeclaration after XmlDocumentType"); } catch(InvalidOperationException) { // Success } // But adding XmlDeclaration before should succeed. doc.PrependChild(decl); } // Test adding an element to the document. public void TestXmlDocumentAddElement() { XmlDocument doc = new XmlDocument(); // Add an element to the document. XmlElement element = doc.CreateElement("foo"); AssertNull("XmlElement (1)", element.ParentNode); AssertEquals("XmlElement (2)", doc, element.OwnerDocument); doc.AppendChild(element); AssertEquals("XmlElement (3)", doc, element.ParentNode); AssertEquals("XmlElement (4)", doc, element.OwnerDocument); // Try to add it again, which should fail this time. try { doc.AppendChild(element); Fail("adding XmlElement node twice"); } catch(InvalidOperationException) { // Success } try { doc.PrependChild(element); Fail("prepending XmlElement node twice"); } catch(InvalidOperationException) { // Success } // Adding an XmlDeclaration after should fail. XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", null, null); try { doc.AppendChild(decl); Fail("appending XmlDeclaration after XmlElement"); } catch(InvalidOperationException) { // Success } // But adding XmlDeclaration before should succeed. doc.PrependChild(decl); // Adding a document type after should fail. XmlDocumentType type = doc.CreateDocumentType("foo", null, null, null); try { doc.AppendChild(type); Fail("appending XmlDocumentType"); } catch(InvalidOperationException) { // Success } // Adding a document type before should succeed. doc.InsertBefore(type, element); } // Test searching children ie: doc["elementname"] public void TestXmlDocumentFindElement() { XmlDocument doc = new XmlDocument(); doc.Load(new StringReader(xml[0])); XmlElement e = doc["UI"]; AssertEquals("XmlFindElement (1)", "UI", e.Name); AssertEquals("XmlFindElement (2)", "Form1", e["class"].InnerText); AssertEquals("XmlFindElement (3)", "Form1", e["widget"]["property"].InnerText); XmlElement n = doc["notgonnabefound"]; AssertNull("XmlFindElement (4)", n); } // Test loading xml. public void TestXmlDocumentLoadXml() { XmlDocument doc; doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.LoadXml(xml[1]); AssertNotNull("LoadXml (1)", doc.FirstChild); AssertNotNull("LoadXml (2)", doc.DocumentType); AssertNotNull("LoadXml (3)", doc.DocumentElement); Assert("LoadXml (4)", (doc.FirstChild is XmlDeclaration)); doc = new XmlDocument(); doc.LoadXml(xml[2]); AssertNotNull("LoadXml (3)", doc.DocumentElement); } // Test loading xml. public void TestXmlDocumentSave() { XmlDocument doc; doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.LoadXml(xml[1]); doc.Save("Save.xml"); doc = new XmlDocument(); doc.Load("Save.xml"); AssertNotNull("SaveXml (1)", doc.DocumentElement); } }; // class TestXmlDocument #endif // !ECMA_COMPAT
// Jacqueline Kory Westlund // June 2016 // // The MIT License (MIT) // Copyright (c) 2016 Personal Robots Group // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using UnityEngine; namespace opal { /// <summary> /// Log event. Use when firing log events. Anyone who listens /// for log events can pull all the relevant information out /// of this object for whatever kind of message is being /// logged. /// </summary> public class LogEvent { // log message event -- fire when you want to log something // so others who do logging can listen for the messages public delegate void LogEventHandler(object sender, LogEvent logme); /// <summary> /// the Logger can use the log message type to /// figure out which fields matter for that type /// </summary> public enum EventType { Action, Scene, Message } ; /// <summary> /// the type of this log message /// </summary> public EventType? type = null; /// <summary> /// name of the relevant game object - e.g., the object on which the /// action occurred or the background object /// </summary> public string name = ""; /// <summary> /// name of the relevant game object - e.g., the object on which the /// action occurred or the background object /// </summary> public string nameTwo = ""; /// <summary> /// name of action that occurred /// </summary> public string action = ""; /// <summary> /// x,y,z position of object /// </summary> public Vector3? position = null; /// <summary> /// x,y,z position of object /// </summary> public Vector3? positionTwo = null; /// <summary> /// state of object or miscellanous string message /// </summary> public string message = ""; /// <summary> /// state of an object in the scene /// </summary> public struct SceneObject { public string name; public float[] position; public string tag; public bool draggable; public string audio; public float[] scale; public int correctSlot; public bool isCorrect; public bool isIncorrect; } public SceneObject[] sceneObjects = null; /// <summary> /// Initializes a new instance of the <see cref="LogEvent"/> class. /// </summary> /// <param name="type">event type</param> /// <param name="state">State or miscellanous string message</param> public LogEvent(EventType type, string message) { this.type = type; this.message = message; } /// <summary> /// Initializes a new instance of the <see cref="LogEvent"/> class. /// </summary> /// <param name="type">event type</param> /// <param name="background">Name of current background image or "" if none</param> /// <param name="sceneObjects">Array of current objects in scene</param> public LogEvent(EventType type, SceneObject[] sceneObjects) { this.type = type; this.sceneObjects = sceneObjects; } /// <summary> /// Initializes a new instance of the <see cref="LogEvent"/> class. /// </summary> /// <param name="type">event type</param> /// <param name="name">Name.</param> /// <param name="action">Action.</param> /// <param name="position">Position.</param> public LogEvent(EventType type, string name, string action, Vector3? position) { this.type = type; this.name = name; this.action = action; this.position = position; } /// <summary> /// Initializes a new instance of the <see cref="LogEvent"/> class. /// </summary> /// <param name="type">Event Type.</param> /// <param name="name">Name.</param> /// <param name="action">Action.</param> /// <param name="position">Position.</param> /// <param name="state">State.</param> public LogEvent(EventType type, string name, string action, Vector3? position, string message) { this.type = type; this.name = name; this.action = action; this.position = position; this.message = message; } /// <summary> /// Initializes a new instance of the <see cref="opal.LogEvent"/> class. /// </summary> /// <param name="type">Type.</param> /// <param name="name">Name of first object involved in the action.</param> /// <param name="nameTwo">Name of second object</param> /// <param name="action">Action.</param> /// <param name="position">Position of first object.</param> /// <param name="positionTwo">Position of second object</param> /// <param name="state">State.</param> public LogEvent(EventType type, string name, string nameTwo, string action, Vector3? position, Vector3? positionTwo) { this.type = type; this.name = name; this.action = action; this.position = position; this.positionTwo = positionTwo; this.nameTwo = nameTwo; } /// <summary> /// Initializes a new instance of the <see cref="opal.LogEvent"/> class. /// </summary> /// <param name="type">Type.</param> /// <param name="name">Name.</param> /// <param name="nameTwo">Name two.</param> /// <param name="action">Action.</param> /// <param name="position">Position.</param> /// <param name="positionTwo">Position two.</param> /// <param name="message">Message.</param> public LogEvent(EventType type, string name, string nameTwo, string action, Vector3? position, Vector3? positionTwo, string message) { this.type = type; this.name = name; this.action = action; this.position = position; this.positionTwo = positionTwo; this.nameTwo = nameTwo; this.message = message; } } }
/* * Copyright 2010-2014 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. */ /* * Do not modify this file. This file is generated from the cloudtrail-2013-11-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.CloudTrail.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.CloudTrail.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for UpdateTrail operation /// </summary> public class UpdateTrailResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { UpdateTrailResponse response = new UpdateTrailResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("CloudWatchLogsLogGroupArn", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.CloudWatchLogsLogGroupArn = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("CloudWatchLogsRoleArn", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.CloudWatchLogsRoleArn = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("IncludeGlobalServiceEvents", targetDepth)) { var unmarshaller = BoolUnmarshaller.Instance; response.IncludeGlobalServiceEvents = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("KmsKeyId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.KmsKeyId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("LogFileValidationEnabled", targetDepth)) { var unmarshaller = BoolUnmarshaller.Instance; response.LogFileValidationEnabled = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Name", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.Name = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("S3BucketName", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.S3BucketName = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("S3KeyPrefix", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.S3KeyPrefix = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("SnsTopicName", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.SnsTopicName = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("TrailARN", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.TrailARN = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); if (errorResponse.Code != null && errorResponse.Code.Equals("CloudWatchLogsDeliveryUnavailable")) { return new CloudWatchLogsDeliveryUnavailableException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InsufficientEncryptionPolicy")) { return new InsufficientEncryptionPolicyException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InsufficientS3BucketPolicy")) { return new InsufficientS3BucketPolicyException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InsufficientSnsTopicPolicy")) { return new InsufficientSnsTopicPolicyException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidCloudWatchLogsLogGroupArn")) { return new InvalidCloudWatchLogsLogGroupArnException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidCloudWatchLogsRoleArn")) { return new InvalidCloudWatchLogsRoleArnException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidKmsKeyId")) { return new InvalidKmsKeyIdException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidS3BucketName")) { return new InvalidS3BucketNameException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidS3Prefix")) { return new InvalidS3PrefixException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidSnsTopicName")) { return new InvalidSnsTopicNameException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidTrailName")) { return new InvalidTrailNameException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("KmsKeyDisabled")) { return new KmsKeyDisabledException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("KmsKeyNotFound")) { return new KmsKeyNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("OperationNotPermitted")) { return new OperationNotPermittedException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("S3BucketDoesNotExist")) { return new S3BucketDoesNotExistException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("TrailNotFound")) { return new TrailNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("TrailNotProvided")) { return new TrailNotProvidedException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("UnsupportedOperation")) { return new UnsupportedOperationException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } return new AmazonCloudTrailException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static UpdateTrailResponseUnmarshaller _instance = new UpdateTrailResponseUnmarshaller(); internal static UpdateTrailResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static UpdateTrailResponseUnmarshaller Instance { get { return _instance; } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Web.UI.WebControls.TreeView.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web.UI.WebControls { public partial class TreeView : HierarchicalDataBoundControl, System.Web.UI.IPostBackEventHandler, System.Web.UI.IPostBackDataHandler, System.Web.UI.ICallbackEventHandler { #region Methods and constructors protected override void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer) { } public void CollapseAll() { } protected override System.Web.UI.ControlCollection CreateControlCollection() { return default(System.Web.UI.ControlCollection); } protected internal virtual new TreeNode CreateNode() { return default(TreeNode); } public sealed override void DataBind() { } public void ExpandAll() { } public TreeNode FindNode(string valuePath) { return default(TreeNode); } protected virtual new string GetCallbackResult() { return default(string); } protected virtual new bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection) { return default(bool); } protected override void LoadViewState(Object state) { } protected internal override void OnInit(EventArgs e) { } protected internal override void OnPreRender(EventArgs e) { } protected virtual new void OnSelectedNodeChanged(EventArgs e) { } protected virtual new void OnTreeNodeCheckChanged(TreeNodeEventArgs e) { } protected virtual new void OnTreeNodeCollapsed(TreeNodeEventArgs e) { } protected virtual new void OnTreeNodeDataBound(TreeNodeEventArgs e) { } protected virtual new void OnTreeNodeExpanded(TreeNodeEventArgs e) { } protected virtual new void OnTreeNodePopulate(TreeNodeEventArgs e) { } protected internal override void PerformDataBinding() { } protected virtual new void RaiseCallbackEvent(string eventArgument) { } protected virtual new void RaisePostBackEvent(string eventArgument) { } protected virtual new void RaisePostDataChangedEvent() { } public override void RenderBeginTag(System.Web.UI.HtmlTextWriter writer) { } protected internal override void RenderContents(System.Web.UI.HtmlTextWriter writer) { } public override void RenderEndTag(System.Web.UI.HtmlTextWriter writer) { } protected override Object SaveViewState() { return default(Object); } protected void SetNodeDataBound(TreeNode node, bool dataBound) { } protected void SetNodeDataItem(TreeNode node, Object dataItem) { } protected void SetNodeDataPath(TreeNode node, string dataPath) { } string System.Web.UI.ICallbackEventHandler.GetCallbackResult() { return default(string); } void System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent(string eventArgument) { } bool System.Web.UI.IPostBackDataHandler.LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection) { return default(bool); } void System.Web.UI.IPostBackDataHandler.RaisePostDataChangedEvent() { } void System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(string eventArgument) { } protected override void TrackViewState() { } public TreeView() { } #endregion #region Properties and indexers public bool AutoGenerateDataBindings { get { return default(bool); } set { } } public TreeNodeCollection CheckedNodes { get { return default(TreeNodeCollection); } } public string CollapseImageToolTip { get { return default(string); } set { } } public string CollapseImageUrl { get { return default(string); } set { } } public TreeNodeBindingCollection DataBindings { get { return default(TreeNodeBindingCollection); } } public bool EnableClientScript { get { return default(bool); } set { } } public int ExpandDepth { get { return default(int); } set { } } public string ExpandImageToolTip { get { return default(string); } set { } } public string ExpandImageUrl { get { return default(string); } set { } } public Style HoverNodeStyle { get { return default(Style); } } public TreeViewImageSet ImageSet { get { return default(TreeViewImageSet); } set { } } public TreeNodeStyle LeafNodeStyle { get { return default(TreeNodeStyle); } } public TreeNodeStyleCollection LevelStyles { get { return default(TreeNodeStyleCollection); } } public string LineImagesFolder { get { return default(string); } set { } } public int MaxDataBindDepth { get { return default(int); } set { } } public int NodeIndent { get { return default(int); } set { } } public TreeNodeCollection Nodes { get { return default(TreeNodeCollection); } } public TreeNodeStyle NodeStyle { get { return default(TreeNodeStyle); } } public bool NodeWrap { get { return default(bool); } set { } } public string NoExpandImageUrl { get { return default(string); } set { } } public TreeNodeStyle ParentNodeStyle { get { return default(TreeNodeStyle); } } public char PathSeparator { get { return default(char); } set { } } public bool PopulateNodesFromClient { get { return default(bool); } set { } } public TreeNodeStyle RootNodeStyle { get { return default(TreeNodeStyle); } } public TreeNode SelectedNode { get { return default(TreeNode); } } public TreeNodeStyle SelectedNodeStyle { get { return default(TreeNodeStyle); } } public string SelectedValue { get { return default(string); } } public TreeNodeTypes ShowCheckBoxes { get { return default(TreeNodeTypes); } set { } } public bool ShowExpandCollapse { get { return default(bool); } set { } } public bool ShowLines { get { return default(bool); } set { } } public string SkipLinkText { get { return default(string); } set { } } protected override System.Web.UI.HtmlTextWriterTag TagKey { get { return default(System.Web.UI.HtmlTextWriterTag); } } public string Target { get { return default(string); } set { } } public override bool Visible { get { return default(bool); } set { } } #endregion #region Events public event EventHandler SelectedNodeChanged { add { } remove { } } public event TreeNodeEventHandler TreeNodeCheckChanged { add { } remove { } } public event TreeNodeEventHandler TreeNodeCollapsed { add { } remove { } } public event TreeNodeEventHandler TreeNodeDataBound { add { } remove { } } public event TreeNodeEventHandler TreeNodeExpanded { add { } remove { } } public event TreeNodeEventHandler TreeNodePopulate { add { } remove { } } #endregion } }
// // AudioSession.cs: AudioSession bindings // // Authors: // Miguel de Icaza ([email protected]) // Marek Safar ([email protected]) // // Copyright 2009 Novell, Inc // Copyright 2011, 2012 Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using MonoMac.CoreFoundation; using MonoMac.ObjCRuntime; using MonoMac.Foundation; using OSStatus = System.Int32; namespace MonoMac.AudioToolbox { public class AudioSessionException : Exception { static string Lookup (int k) { switch ((AudioSessionErrors)k){ case AudioSessionErrors.NotInitialized: return "AudioSession.Initialize has not been called"; case AudioSessionErrors.AlreadyInitialized: return "You called AudioSession.Initialize more than once"; case AudioSessionErrors.InitializationError: return "There was an error during the AudioSession.initialization"; case AudioSessionErrors.UnsupportedPropertyError: return "The audio session property is not supported"; case AudioSessionErrors.BadPropertySizeError: return "The size of the audio property was not correct"; case AudioSessionErrors.NotActiveError: return "Application Audio Session is not active"; case AudioSessionErrors.NoHardwareError: return "The device has no Audio Input capability"; case AudioSessionErrors.IncompatibleCategory: return "The specified AudioSession.Category can not be used with this audio operation"; case AudioSessionErrors.NoCategorySet: return "This operation requries AudioSession.Category to be explicitly set"; } return String.Format ("Unknown error code: 0x{0:x}", k); } internal AudioSessionException (int k) : base (Lookup (k)) { ErrorCode = (AudioSessionErrors) k; } public AudioSessionErrors ErrorCode { get; private set; } } public class AccessoryInfo { internal AccessoryInfo (int id, string description) { ID = id; Description = description; } public int ID { get; private set; } public string Description { get; private set; } } public class AudioSessionPropertyEventArgs :EventArgs { public AudioSessionPropertyEventArgs (AudioSessionProperty prop, int size, IntPtr data) { this.Property = prop; this.Size = size; this.Data = data; } public AudioSessionProperty Property { get; set; } public int Size { get; set; } public IntPtr Data { get; set; } } public static class AudioSession { static bool initialized; public static event EventHandler Interrupted; public static event EventHandler Resumed; static NSString AudioRouteKey_Type; static NSString AudioRouteKey_Inputs; static NSString AudioRouteKey_Outputs; static NSString InputRoute_LineIn; static NSString InputRoute_BuiltInMic; static NSString InputRoute_HeadsetMic; static NSString InputRoute_BluetoothHFP; static NSString InputRoute_USBAudio; static NSString OutputRoute_LineOut; static NSString OutputRoute_Headphones; static NSString OutputRoute_BluetoothHFP; static NSString OutputRoute_BluetoothA2DP; static NSString OutputRoute_BuiltInReceiver; static NSString OutputRoute_BuiltInSpeaker; static NSString OutputRoute_USBAudio; static NSString OutputRoute_HDMI; static NSString OutputRoute_AirPlay; static NSString InputSourceKey_ID; static NSString InputSourceKey_Description; static NSString OutputDestinationKey_ID; static NSString OutputDestinationKey_Description; [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioSessionInitialize(IntPtr cfRunLoop, IntPtr cfstr_runMode, InterruptionListener listener, IntPtr userData); public static void Initialize () { Initialize (null, null); } public static void Initialize (CFRunLoop runLoop, string runMode) { CFString s = runMode == null ? null : new CFString (runMode); int k = AudioSessionInitialize (runLoop == null ? IntPtr.Zero : runLoop.Handle, s == null ? IntPtr.Zero : s.Handle, Interruption, IntPtr.Zero); if (k != 0 && k != (int)AudioSessionErrors.AlreadyInitialized) throw new AudioSessionException (k); if (initialized) return; IntPtr lib = Dlfcn.dlopen (Constants.AudioToolboxLibrary, 0); AudioRouteKey_Inputs = new NSString (Dlfcn.GetIntPtr (lib, "kAudioSession_AudioRouteKey_Inputs")); AudioRouteKey_Outputs = new NSString (Dlfcn.GetIntPtr (lib, "kAudioSession_AudioRouteKey_Outputs")); AudioRouteKey_Type = new NSString (Dlfcn.GetIntPtr (lib, "kAudioSession_AudioRouteKey_Type")); InputRoute_LineIn = new NSString (Dlfcn.GetIntPtr (lib, "kAudioSessionInputRoute_LineIn")); InputRoute_BuiltInMic = new NSString (Dlfcn.GetIntPtr (lib, "kAudioSessionInputRoute_BuiltInMic")); InputRoute_HeadsetMic = new NSString (Dlfcn.GetIntPtr (lib, "kAudioSessionInputRoute_HeadsetMic")); InputRoute_BluetoothHFP = new NSString (Dlfcn.GetIntPtr (lib, "kAudioSessionInputRoute_BluetoothHFP")); InputRoute_USBAudio = new NSString (Dlfcn.GetIntPtr (lib, "kAudioSessionInputRoute_USBAudio")); OutputRoute_LineOut = new NSString (Dlfcn.GetIntPtr (lib, "kAudioSessionOutputRoute_LineOut")); OutputRoute_Headphones = new NSString (Dlfcn.GetIntPtr (lib, "kAudioSessionOutputRoute_Headphones")); OutputRoute_BluetoothHFP = new NSString (Dlfcn.GetIntPtr (lib, "kAudioSessionOutputRoute_BluetoothHFP")); OutputRoute_BluetoothA2DP = new NSString (Dlfcn.GetIntPtr (lib, "kAudioSessionOutputRoute_BluetoothA2DP")); OutputRoute_BuiltInReceiver = new NSString (Dlfcn.GetIntPtr (lib, "kAudioSessionOutputRoute_BuiltInReceiver")); OutputRoute_BuiltInSpeaker = new NSString (Dlfcn.GetIntPtr (lib, "kAudioSessionOutputRoute_BuiltInSpeaker")); OutputRoute_USBAudio = new NSString (Dlfcn.GetIntPtr (lib, "kAudioSessionOutputRoute_USBAudio")); OutputRoute_HDMI = new NSString (Dlfcn.GetIntPtr (lib, "kAudioSessionOutputRoute_HDMI")); OutputRoute_AirPlay = new NSString (Dlfcn.GetIntPtr (lib, "kAudioSessionOutputRoute_AirPlay")); InputSourceKey_ID = new NSString (Dlfcn.GetIntPtr (lib, "kAudioSession_InputSourceKey_ID")); InputSourceKey_Description = new NSString (Dlfcn.GetIntPtr (lib, "kAudioSession_InputSourceKey_Description")); OutputDestinationKey_ID = new NSString (Dlfcn.GetIntPtr (lib, "kAudioSession_OutputDestinationKey_ID")); OutputDestinationKey_Description = new NSString (Dlfcn.GetIntPtr (lib, "kAudioSession_OutputDestinationKey_Description")); Dlfcn.dlclose (lib); initialized = true; } delegate void InterruptionListener (IntPtr userData, uint state); [MonoPInvokeCallback (typeof (InterruptionListener))] static void Interruption (IntPtr userData, uint state) { EventHandler h; h = (state == 1) ? Interrupted : Resumed; if (h != null) h (null, EventArgs.Empty); } [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioSessionSetActive (int active); public static void SetActive (bool active) { int k = AudioSessionSetActive (active ? 1 : 0); if (k != 0) throw new AudioSessionException (k); } [DllImport (Constants.AudioToolboxLibrary)] extern static AudioSessionErrors AudioSessionSetActive (int active, AudioSessionActiveFlags inFlags); [Since (4,0)] public static AudioSessionErrors SetActive (bool active, AudioSessionActiveFlags flags) { return AudioSessionSetActive (active ? 1 : 0, flags); } [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioSessionGetProperty(AudioSessionProperty id, ref int size, IntPtr data); [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioSessionSetProperty (AudioSessionProperty id, int size, IntPtr data); [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioSessionGetPropertySize (AudioSessionProperty id, out int size); static double GetDouble (AudioSessionProperty property) { unsafe { double val = 0; int size = 8; int k = AudioSessionGetProperty (property, ref size, (IntPtr) (&val)); if (k != 0) throw new AudioSessionException (k); return val; } } static float GetFloat (AudioSessionProperty property) { unsafe { float val = 0; int size = 4; int k = AudioSessionGetProperty (property, ref size, (IntPtr) (&val)); if (k != 0) throw new AudioSessionException (k); return val; } } static int GetInt (AudioSessionProperty property) { unsafe { int val = 0; int size = 4; int k = AudioSessionGetProperty (property, ref size, (IntPtr) (&val)); if (k != 0) throw new AudioSessionException (k); return val; } } static void SetDouble (AudioSessionProperty property, double val) { unsafe { int k = AudioSessionSetProperty (property, 8, (IntPtr) (&val)); if (k != 0) throw new AudioSessionException (k); } } static void SetInt (AudioSessionProperty property, int val) { unsafe { int k = AudioSessionSetProperty (property, 4, (IntPtr) (&val)); if (k != 0) throw new AudioSessionException (k); } } static void SetFloat (AudioSessionProperty property, float val) { unsafe { int k = AudioSessionSetProperty (property, 4, (IntPtr) (&val)); if (k != 0) throw new AudioSessionException (k); } } static public double PreferredHardwareSampleRate { get { return GetDouble (AudioSessionProperty.PreferredHardwareSampleRate); } set { SetDouble (AudioSessionProperty.PreferredHardwareSampleRate, value); } } static public float PreferredHardwareIOBufferDuration { get { return GetFloat (AudioSessionProperty.PreferredHardwareIOBufferDuration); } set { SetFloat (AudioSessionProperty.PreferredHardwareIOBufferDuration, value); } } static public AudioSessionCategory Category { get { return (AudioSessionCategory) GetInt (AudioSessionProperty.AudioCategory); } set { SetInt (AudioSessionProperty.AudioCategory, (int) value); } } [Since (4,0)] public static AudioSessionInterruptionType InterruptionType { get { return (AudioSessionInterruptionType) GetInt (AudioSessionProperty.InterruptionType); } } [Obsolete ("Use InputRoute or OutputRoute instead")] static public string AudioRoute { get { return CFString.FetchString ((IntPtr) GetInt (AudioSessionProperty.AudioRoute)); } } [Since (5,0)] static public AccessoryInfo[] InputSources { get { using (var array = new CFArray ((IntPtr) GetInt (AudioSessionProperty.InputSources))) { var res = new AccessoryInfo [array.Count]; for (int i = 0; i < res.Length; ++i) { var dict = array.GetValue (i); var id = new NSNumber (CFDictionary.GetValue (dict, InputSourceKey_ID.Handle)); var desc = CFString.FetchString (CFDictionary.GetValue (dict, InputSourceKey_Description.Handle)); res [i] = new AccessoryInfo ((int) id, desc); id.Dispose (); } return res; } } } [Since (5,0)] static public AccessoryInfo[] OutputDestinations { get { using (var array = new CFArray ((IntPtr) GetInt (AudioSessionProperty.OutputDestinations))) { var res = new AccessoryInfo [array.Count]; for (int i = 0; i < res.Length; ++i) { var dict = array.GetValue (i); var id = new NSNumber (CFDictionary.GetValue (dict, OutputDestinationKey_ID.Handle)); var desc = CFString.FetchString (CFDictionary.GetValue (dict, OutputDestinationKey_Description.Handle)); res [i] = new AccessoryInfo ((int) id, desc); id.Dispose (); } return res; } } } /* Could not test what sort of unique CFNumberRef value it's [Since (5,0)] static public int InputSource { get { return GetInt (AudioSessionProperty.InputSource); } set { SetInt (AudioSessionProperty.InputSource, value); } } [Since (5,0)] static public int OutputDestination { get { return GetInt (AudioSessionProperty.OutputDestination); } set { SetInt (AudioSessionProperty.OutputDestination, value); } } */ // TODO: Wrong can return more than 1 value [Since (5,0)] static public AudioSessionInputRouteKind InputRoute { get { var arr = (NSArray) AudioRouteDescription [AudioRouteKey_Inputs]; if (arr == null || arr.Count == 0) return AudioSessionInputRouteKind.None; var dict = new NSDictionary (arr.ValueAt (0)); if (dict == null || dict.Count == 0) return AudioSessionInputRouteKind.None; var val = (NSString) dict [AudioRouteKey_Type]; if (val == null) return AudioSessionInputRouteKind.None; if (val == InputRoute_LineIn) { return AudioSessionInputRouteKind.LineIn; } else if (val == InputRoute_BuiltInMic) { return AudioSessionInputRouteKind.BuiltInMic; } else if (val == InputRoute_HeadsetMic) { return AudioSessionInputRouteKind.HeadsetMic; } else if (val == InputRoute_BluetoothHFP) { return AudioSessionInputRouteKind.BluetoothHFP; } else if (val == InputRoute_USBAudio) { return AudioSessionInputRouteKind.USBAudio; } else { // now what? throw new Exception (); // return AudioSessionInputRouteKind.None; } } } [Since (5,0)] static public AudioSessionOutputRouteKind [] OutputRoutes { get { var arr = (NSArray) AudioRouteDescription [AudioRouteKey_Outputs]; if (arr == null || arr.Count == 0) return null; var result = new AudioSessionOutputRouteKind [arr.Count]; for (uint i = 0; i < arr.Count; i++) { var dict = new NSDictionary ((IntPtr) arr.ValueAt (i)); result [i] = AudioSessionOutputRouteKind.None; if (dict == null || dict.Count == 0) continue; var val = (NSString) dict [AudioRouteKey_Type]; if (val == null) continue; if (val == OutputRoute_LineOut) { result [i] = AudioSessionOutputRouteKind.LineOut; } else if (val == OutputRoute_Headphones) { result [i] = AudioSessionOutputRouteKind.Headphones; } else if (val == OutputRoute_BluetoothHFP) { result [i] = AudioSessionOutputRouteKind.BluetoothHFP; } else if (val == OutputRoute_BluetoothA2DP) { result [i] = AudioSessionOutputRouteKind.BluetoothA2DP; } else if (val == OutputRoute_BuiltInReceiver) { result [i] = AudioSessionOutputRouteKind.BuiltInReceiver; } else if (val == OutputRoute_BuiltInSpeaker) { result [i] = AudioSessionOutputRouteKind.BuiltInSpeaker; } else if (val == OutputRoute_USBAudio) { result [i] = AudioSessionOutputRouteKind.USBAudio; } else if (val == OutputRoute_HDMI) { result [i] = AudioSessionOutputRouteKind.HDMI; } else if (val == OutputRoute_AirPlay) { result [i] = AudioSessionOutputRouteKind.AirPlay; } } return result; } } static NSDictionary AudioRouteDescription { get { NSDictionary dict = new NSDictionary ((IntPtr) GetInt (AudioSessionProperty.AudioRouteDescription)); dict.Release (); return dict; } } static public double CurrentHardwareSampleRate { get { return GetDouble (AudioSessionProperty.CurrentHardwareSampleRate); } } static public int CurrentHardwareInputNumberChannels { get { return GetInt (AudioSessionProperty.CurrentHardwareInputNumberChannels); } } static public int CurrentHardwareOutputNumberChannels { get { return GetInt (AudioSessionProperty.CurrentHardwareOutputNumberChannels); } } static public float CurrentHardwareOutputVolume { get { return GetFloat (AudioSessionProperty.CurrentHardwareOutputVolume); } } static public float CurrentHardwareInputLatency { get { return GetFloat (AudioSessionProperty.CurrentHardwareInputLatency); } } static public float CurrentHardwareOutputLatency { get { return GetFloat (AudioSessionProperty.CurrentHardwareOutputLatency); } } static public float CurrentHardwareIOBufferDuration { get { return GetFloat (AudioSessionProperty.CurrentHardwareIOBufferDuration); } } static public bool OtherAudioIsPlaying { get { return GetInt (AudioSessionProperty.OtherAudioIsPlaying) != 0; } } static public AudioSessionRoutingOverride RoutingOverride { set { SetInt (AudioSessionProperty.OverrideAudioRoute, (int) value); } } static public bool AudioInputAvailable { get { return GetInt (AudioSessionProperty.AudioInputAvailable) != 0; } } static public bool AudioShouldDuck { get { return GetInt (AudioSessionProperty.OtherMixableAudioShouldDuck) != 0; } set { SetInt (AudioSessionProperty.OtherMixableAudioShouldDuck, value ? 1 : 0); } } static public bool OverrideCategoryMixWithOthers { get { return GetInt (AudioSessionProperty.OverrideCategoryMixWithOthers) != 0; } set { SetInt (AudioSessionProperty.OverrideCategoryMixWithOthers, value ? 1 : 0); } } static public bool OverrideCategoryDefaultToSpeaker { get { return GetInt (AudioSessionProperty.OverrideCategoryDefaultToSpeaker) != 0; } set { SetInt (AudioSessionProperty.OverrideCategoryDefaultToSpeaker, value ? 1 : 0); } } static public bool OverrideCategoryEnableBluetoothInput { get { return GetInt (AudioSessionProperty.OverrideCategoryEnableBluetoothInput) != 0; } set { SetInt (AudioSessionProperty.OverrideCategoryEnableBluetoothInput, value ? 1 : 0); } } [Since (5,0)] static public AudioSessionMode Mode { get { return (AudioSessionMode) GetInt (AudioSessionProperty.Mode); } set { SetInt (AudioSessionProperty.Mode, (int) value); } } // InputSources [Since (5,0)] static public bool InputGainAvailable { get { return GetInt (AudioSessionProperty.InputGainAvailable) != 0; } } [Since (5,0)] static public float InputGainScalar { get { return GetFloat (AudioSessionProperty.InputGainScalar); } set { SetFloat (AudioSessionProperty.InputGainScalar, value); } } delegate void _PropertyListener (IntPtr userData, AudioSessionProperty prop, int size, IntPtr data); public delegate void PropertyListener (AudioSessionProperty prop, int size, IntPtr data); [MonoPInvokeCallback (typeof (_PropertyListener))] static void Listener (IntPtr userData, AudioSessionProperty prop, int size, IntPtr data) { ArrayList a = (ArrayList) listeners [prop]; if (a == null){ // Should never happen return; } foreach (PropertyListener pl in a){ pl (prop, size, data); } } [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioSessionAddPropertyListener(AudioSessionProperty id, _PropertyListener inProc, IntPtr userData); static Hashtable listeners; public static void AddListener (AudioSessionProperty property, PropertyListener listener) { if (listener == null) throw new ArgumentNullException ("listener"); if (listeners == null) listeners = new Hashtable (); ArrayList a = (ArrayList) listeners [property]; if (a == null) listeners [property] = a = new ArrayList (); a.Add (listener); if (a.Count == 1) AudioSessionAddPropertyListener (property, Listener, IntPtr.Zero); } public static void RemoveListener (AudioSessionProperty property, PropertyListener listener) { if (listener == null) throw new ArgumentNullException ("listener"); ArrayList a = (ArrayList) listeners [property]; if (a == null) return; a.Remove (listener); if (a.Count == 0) listeners [property] = null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection; using System.Text; using System.Collections; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; namespace System { [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public abstract class Enum : ValueType, IComparable, IFormattable, IConvertible { #region Private Constants private const char enumSeparatorChar = ','; private const String enumSeparatorString = ", "; #endregion #region Private Static Methods [System.Security.SecuritySafeCritical] // auto-generated private static TypeValuesAndNames GetCachedValuesAndNames(RuntimeType enumType, bool getNames) { TypeValuesAndNames entry = enumType.GenericCache as TypeValuesAndNames; if (entry == null || (getNames && entry.Names == null)) { ulong[] values = null; String[] names = null; bool isFlags = enumType.IsDefined(typeof(System.FlagsAttribute), false); GetEnumValuesAndNames( enumType.GetTypeHandleInternal(), JitHelpers.GetObjectHandleOnStack(ref values), JitHelpers.GetObjectHandleOnStack(ref names), getNames); entry = new TypeValuesAndNames(isFlags, values, names); enumType.GenericCache = entry; } return entry; } [System.Security.SecuritySafeCritical] private unsafe String InternalFormattedHexString() { fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data) { switch (InternalGetCorElementType()) { case CorElementType.I1: case CorElementType.U1: return (*(byte*)pValue).ToString("X2", null); case CorElementType.Boolean: // direct cast from bool to byte is not allowed return Convert.ToByte(*(bool*)pValue).ToString("X2", null); case CorElementType.I2: case CorElementType.U2: case CorElementType.Char: return (*(ushort*)pValue).ToString("X4", null); case CorElementType.I4: case CorElementType.U4: return (*(uint*)pValue).ToString("X8", null); case CorElementType.I8: case CorElementType.U8: return (*(ulong*)pValue).ToString("X16", null); default: Contract.Assert(false, "Invalid Object type in Format"); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType")); } } } private static String InternalFormattedHexString(object value) { TypeCode typeCode = Convert.GetTypeCode(value); switch (typeCode) { case TypeCode.SByte: return ((byte)(sbyte)value).ToString("X2", null); case TypeCode.Byte: return ((byte)value).ToString("X2", null); case TypeCode.Boolean: // direct cast from bool to byte is not allowed return Convert.ToByte((bool)value).ToString("X2", null); case TypeCode.Int16: return ((UInt16)(Int16)value).ToString("X4", null); case TypeCode.UInt16: return ((UInt16)value).ToString("X4", null); case TypeCode.Char: return ((UInt16)(Char)value).ToString("X4", null); case TypeCode.UInt32: return ((UInt32)value).ToString("X8", null); case TypeCode.Int32: return ((UInt32)(Int32)value).ToString("X8", null); case TypeCode.UInt64: return ((UInt64)value).ToString("X16", null); case TypeCode.Int64: return ((UInt64)(Int64)value).ToString("X16", null); // All unsigned types will be directly cast default: Contract.Assert(false, "Invalid Object type in Format"); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType")); } } internal static String GetEnumName(RuntimeType eT, ulong ulValue) { Contract.Requires(eT != null); ulong[] ulValues = Enum.InternalGetValues(eT); int index = Array.BinarySearch(ulValues, ulValue); if (index >= 0) { string[] names = Enum.InternalGetNames(eT); return names[index]; } return null; // return null so the caller knows to .ToString() the input } private static String InternalFormat(RuntimeType eT, ulong value) { Contract.Requires(eT != null); // These values are sorted by value. Don't change this TypeValuesAndNames entry = GetCachedValuesAndNames(eT, true); if (!entry.IsFlag) // Not marked with Flags attribute { return Enum.GetEnumName(eT, value); } else // These are flags OR'ed together (We treat everything as unsigned types) { return InternalFlagsFormat(eT, entry, value); } } private static String InternalFlagsFormat(RuntimeType eT,ulong result) { // These values are sorted by value. Don't change this TypeValuesAndNames entry = GetCachedValuesAndNames(eT, true); return InternalFlagsFormat(eT, entry, result); } private static String InternalFlagsFormat(RuntimeType eT, TypeValuesAndNames entry, ulong result) { Contract.Requires(eT != null); String[] names = entry.Names; ulong[] values = entry.Values; Contract.Assert(names.Length == values.Length); int index = values.Length - 1; StringBuilder retval = new StringBuilder(); bool firstTime = true; ulong saveResult = result; // We will not optimize this code further to keep it maintainable. There are some boundary checks that can be applied // to minimize the comparsions required. This code works the same for the best/worst case. In general the number of // items in an enum are sufficiently small and not worth the optimization. while (index >= 0) { if ((index == 0) && (values[index] == 0)) break; if ((result & values[index]) == values[index]) { result -= values[index]; if (!firstTime) retval.Insert(0, enumSeparatorString); retval.Insert(0, names[index]); firstTime = false; } index--; } // We were unable to represent this number as a bitwise or of valid flags if (result != 0) return null; // return null so the caller knows to .ToString() the input // For the case when we have zero if (saveResult == 0) { if (values.Length > 0 && values[0] == 0) return names[0]; // Zero was one of the enum values. else return "0"; } else { return retval.ToString(); // Return the string representation } } internal static ulong ToUInt64(Object value) { // Helper function to silently convert the value to UInt64 from the other base types for enum without throwing an exception. // This is need since the Convert functions do overflow checks. TypeCode typeCode = Convert.GetTypeCode(value); ulong result; switch (typeCode) { case TypeCode.SByte: result = (ulong)(sbyte)value; break; case TypeCode.Byte: result = (byte)value; break; case TypeCode.Boolean: // direct cast from bool to byte is not allowed result = Convert.ToByte((bool)value); break; case TypeCode.Int16: result = (ulong)(Int16)value; break; case TypeCode.UInt16: result = (UInt16)value; break; case TypeCode.Char: result = (UInt16)(Char)value; break; case TypeCode.UInt32: result = (UInt32)value; break; case TypeCode.Int32: result = (ulong)(int)value; break; case TypeCode.UInt64: result = (ulong)value; break; case TypeCode.Int64: result = (ulong)(Int64)value; break; // All unsigned types will be directly cast default: Contract.Assert(false, "Invalid Object type in ToUInt64"); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType")); } return result; } [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int InternalCompareTo(Object o1, Object o2); [System.Security.SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern RuntimeType InternalGetUnderlyingType(RuntimeType enumType); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [System.Security.SuppressUnmanagedCodeSecurity] private static extern void GetEnumValuesAndNames(RuntimeTypeHandle enumType, ObjectHandleOnStack values, ObjectHandleOnStack names, bool getNames); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern Object InternalBoxEnum(RuntimeType enumType, long value); #endregion #region Public Static Methods private enum ParseFailureKind { None = 0, Argument = 1, ArgumentNull = 2, ArgumentWithParameter = 3, UnhandledException = 4 } // This will store the result of the parsing. private struct EnumResult { internal object parsedEnum; internal bool canThrow; internal ParseFailureKind m_failure; internal string m_failureMessageID; internal string m_failureParameter; internal object m_failureMessageFormatArgument; internal Exception m_innerException; internal void SetFailure(Exception unhandledException) { m_failure = ParseFailureKind.UnhandledException; m_innerException = unhandledException; } internal void SetFailure(ParseFailureKind failure, string failureParameter) { m_failure = failure; m_failureParameter = failureParameter; if (canThrow) throw GetEnumParseException(); } internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument) { m_failure = failure; m_failureMessageID = failureMessageID; m_failureMessageFormatArgument = failureMessageFormatArgument; if (canThrow) throw GetEnumParseException(); } internal Exception GetEnumParseException() { switch (m_failure) { case ParseFailureKind.Argument: return new ArgumentException(Environment.GetResourceString(m_failureMessageID)); case ParseFailureKind.ArgumentNull: return new ArgumentNullException(m_failureParameter); case ParseFailureKind.ArgumentWithParameter: return new ArgumentException(Environment.GetResourceString(m_failureMessageID, m_failureMessageFormatArgument)); case ParseFailureKind.UnhandledException: return m_innerException; default: Contract.Assert(false, "Unknown EnumParseFailure: " + m_failure); return new ArgumentException(Environment.GetResourceString("Arg_EnumValueNotFound")); } } } public static bool TryParse(Type enumType, String value, out Object result) { return TryParse(enumType, value, false, out result); } public static bool TryParse(Type enumType, String value, bool ignoreCase, out Object result) { result = null; EnumResult parseResult = new EnumResult(); bool retValue; if (retValue = TryParseEnum(enumType, value, ignoreCase, ref parseResult)) result = parseResult.parsedEnum; return retValue; } public static bool TryParse<TEnum>(String value, out TEnum result) where TEnum : struct { return TryParse(value, false, out result); } public static bool TryParse<TEnum>(String value, bool ignoreCase, out TEnum result) where TEnum : struct { result = default(TEnum); EnumResult parseResult = new EnumResult(); bool retValue; if (retValue = TryParseEnum(typeof(TEnum), value, ignoreCase, ref parseResult)) result = (TEnum)parseResult.parsedEnum; return retValue; } [System.Runtime.InteropServices.ComVisible(true)] public static Object Parse(Type enumType, String value) { return Parse(enumType, value, false); } [System.Runtime.InteropServices.ComVisible(true)] public static Object Parse(Type enumType, String value, bool ignoreCase) { EnumResult parseResult = new EnumResult() { canThrow = true }; if (TryParseEnum(enumType, value, ignoreCase, ref parseResult)) return parseResult.parsedEnum; else throw parseResult.GetEnumParseException(); } public static TEnum Parse<TEnum>(String value) where TEnum : struct { return Parse<TEnum>(value, false); } public static TEnum Parse<TEnum>(String value, bool ignoreCase) where TEnum : struct { EnumResult parseResult = new EnumResult() { canThrow = true }; if (TryParseEnum(typeof(TEnum), value, ignoreCase, ref parseResult)) return (TEnum)parseResult.parsedEnum; else throw parseResult.GetEnumParseException(); } private static bool TryParseEnum(Type enumType, String value, bool ignoreCase, ref EnumResult parseResult) { if (enumType == null) throw new ArgumentNullException("enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); if (value == null) { parseResult.SetFailure(ParseFailureKind.ArgumentNull, "value"); return false; } int firstNonWhitespaceIndex = -1; for (int i = 0; i < value.Length; i++) { if (!Char.IsWhiteSpace(value[i])) { firstNonWhitespaceIndex = i; break; } } if (firstNonWhitespaceIndex == -1) { parseResult.SetFailure(ParseFailureKind.Argument, "Arg_MustContainEnumInfo", null); return false; } // We have 2 code paths here. One if they are values else if they are Strings. // values will have the first character as as number or a sign. ulong result = 0; char firstNonWhitespaceChar = value[firstNonWhitespaceIndex]; if (Char.IsDigit(firstNonWhitespaceChar) || firstNonWhitespaceChar == '-' || firstNonWhitespaceChar == '+') { Type underlyingType = GetUnderlyingType(enumType); Object temp; try { value = value.Trim(); temp = Convert.ChangeType(value, underlyingType, CultureInfo.InvariantCulture); parseResult.parsedEnum = ToObject(enumType, temp); return true; } catch (FormatException) { // We need to Parse this as a String instead. There are cases // when you tlbimp enums that can have values of the form "3D". // Don't fix this code. } catch (Exception ex) { if (parseResult.canThrow) throw; else { parseResult.SetFailure(ex); return false; } } } // Find the field. Let's assume that these are always static classes // because the class is an enum. TypeValuesAndNames entry = GetCachedValuesAndNames(rtType, true); String[] enumNames = entry.Names; ulong[] enumValues = entry.Values; StringComparison comparison = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; int valueIndex = firstNonWhitespaceIndex; while (valueIndex <= value.Length) // '=' is to handle invalid case of an ending comma { // Find the next separator, if there is one, otherwise the end of the string. int endIndex = value.IndexOf(enumSeparatorChar, valueIndex); if (endIndex == -1) { endIndex = value.Length; } // Shift the starting and ending indices to eliminate whitespace int endIndexNoWhitespace = endIndex; while (valueIndex < endIndex && Char.IsWhiteSpace(value[valueIndex])) valueIndex++; while (endIndexNoWhitespace > valueIndex && Char.IsWhiteSpace(value[endIndexNoWhitespace - 1])) endIndexNoWhitespace--; int valueSubstringLength = endIndexNoWhitespace - valueIndex; // Try to match this substring against each enum name bool success = false; for (int i = 0; i < enumNames.Length; i++) { if (enumNames[i].Length == valueSubstringLength && string.Compare(enumNames[i], 0, value, valueIndex, valueSubstringLength, comparison) == 0) { result |= enumValues[i]; success = true; break; } } // If we couldn't find a match, throw an argument exception. if (!success) { // Not found, throw an argument exception. parseResult.SetFailure(ParseFailureKind.ArgumentWithParameter, "Arg_EnumValueNotFound", value); return false; } // Move our pointer to the ending index to go again. valueIndex = endIndex + 1; } try { parseResult.parsedEnum = ToObject(enumType, result); return true; } catch (Exception ex) { if (parseResult.canThrow) throw; else { parseResult.SetFailure(ex); return false; } } } [System.Runtime.InteropServices.ComVisible(true)] public static Type GetUnderlyingType(Type enumType) { if (enumType == null) throw new ArgumentNullException("enumType"); Contract.Ensures(Contract.Result<Type>() != null); Contract.EndContractBlock(); return enumType.GetEnumUnderlyingType(); } [System.Runtime.InteropServices.ComVisible(true)] public static Array GetValues(Type enumType) { if (enumType == null) throw new ArgumentNullException("enumType"); Contract.Ensures(Contract.Result<Array>() != null); Contract.EndContractBlock(); return enumType.GetEnumValues(); } internal static ulong[] InternalGetValues(RuntimeType enumType) { // Get all of the values return GetCachedValuesAndNames(enumType, false).Values; } [System.Runtime.InteropServices.ComVisible(true)] public static String GetName(Type enumType, Object value) { if (enumType == null) throw new ArgumentNullException("enumType"); Contract.EndContractBlock(); return enumType.GetEnumName(value); } [System.Runtime.InteropServices.ComVisible(true)] public static String[] GetNames(Type enumType) { if (enumType == null) throw new ArgumentNullException("enumType"); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return enumType.GetEnumNames(); } internal static String[] InternalGetNames(RuntimeType enumType) { // Get all of the names return GetCachedValuesAndNames(enumType, true).Names; } [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, Object value) { if (value == null) throw new ArgumentNullException("value"); Contract.EndContractBlock(); // Delegate rest of error checking to the other functions TypeCode typeCode = Convert.GetTypeCode(value); switch (typeCode) { case TypeCode.Int32 : return ToObject(enumType, (int)value); case TypeCode.SByte : return ToObject(enumType, (sbyte)value); case TypeCode.Int16 : return ToObject(enumType, (short)value); case TypeCode.Int64 : return ToObject(enumType, (long)value); case TypeCode.UInt32 : return ToObject(enumType, (uint)value); case TypeCode.Byte : return ToObject(enumType, (byte)value); case TypeCode.UInt16 : return ToObject(enumType, (ushort)value); case TypeCode.UInt64 : return ToObject(enumType, (ulong)value); case TypeCode.Char: return ToObject(enumType, (char)value); case TypeCode.Boolean: return ToObject(enumType, (bool)value); default: // All unsigned types will be directly cast throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnumBaseTypeOrEnum"), "value"); } } [Pure] [System.Runtime.InteropServices.ComVisible(true)] public static bool IsDefined(Type enumType, Object value) { if (enumType == null) throw new ArgumentNullException("enumType"); Contract.EndContractBlock(); return enumType.IsEnumDefined(value); } [System.Runtime.InteropServices.ComVisible(true)] public static String Format(Type enumType, Object value, String format) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); if (value == null) throw new ArgumentNullException("value"); if (format == null) throw new ArgumentNullException("format"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); // Check if both of them are of the same type Type valueType = value.GetType(); Type underlyingType = GetUnderlyingType(enumType); // If the value is an Enum then we need to extract the underlying value from it if (valueType.IsEnum) { if (!valueType.IsEquivalentTo(enumType)) throw new ArgumentException(Environment.GetResourceString("Arg_EnumAndObjectMustBeSameType", valueType.ToString(), enumType.ToString())); if (format.Length != 1) { // all acceptable format string are of length 1 throw new FormatException(Environment.GetResourceString("Format_InvalidEnumFormatSpecification")); } return ((Enum)value).ToString(format); } // The value must be of the same type as the Underlying type of the Enum else if (valueType != underlyingType) { throw new ArgumentException(Environment.GetResourceString("Arg_EnumFormatUnderlyingTypeAndObjectMustBeSameType", valueType.ToString(), underlyingType.ToString())); } if (format.Length != 1) { // all acceptable format string are of length 1 throw new FormatException(Environment.GetResourceString("Format_InvalidEnumFormatSpecification")); } char formatCh = format[0]; if (formatCh == 'G' || formatCh == 'g') return GetEnumName(rtType, ToUInt64(value)); if (formatCh == 'D' || formatCh == 'd') return value.ToString(); if (formatCh == 'X' || formatCh == 'x') return InternalFormattedHexString(value); if (formatCh == 'F' || formatCh == 'f') return Enum.InternalFlagsFormat(rtType, ToUInt64(value)) ?? value.ToString(); throw new FormatException(Environment.GetResourceString("Format_InvalidEnumFormatSpecification")); } #endregion #region Definitions private class TypeValuesAndNames { // Each entry contains a list of sorted pair of enum field names and values, sorted by values public TypeValuesAndNames(bool isFlag, ulong[] values, String[] names) { this.IsFlag = isFlag; this.Values = values; this.Names = names; } public bool IsFlag; public ulong[] Values; public String[] Names; } #endregion #region Private Methods [System.Security.SecuritySafeCritical] internal unsafe Object GetValue() { fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data) { switch (InternalGetCorElementType()) { case CorElementType.I1: return *(sbyte*)pValue; case CorElementType.U1: return *(byte*)pValue; case CorElementType.Boolean: return *(bool*)pValue; case CorElementType.I2: return *(short*)pValue; case CorElementType.U2: return *(ushort*)pValue; case CorElementType.Char: return *(char*)pValue; case CorElementType.I4: return *(int*)pValue; case CorElementType.U4: return *(uint*)pValue; case CorElementType.R4: return *(float*)pValue; case CorElementType.I8: return *(long*)pValue; case CorElementType.U8: return *(ulong*)pValue; case CorElementType.R8: return *(double*)pValue; case CorElementType.I: return *(IntPtr*)pValue; case CorElementType.U: return *(UIntPtr*)pValue; default: Contract.Assert(false, "Invalid primitive type"); return null; } } } [System.Security.SecuritySafeCritical] private unsafe ulong ToUInt64() { fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data) { switch (InternalGetCorElementType()) { case CorElementType.I1: return (ulong)*(sbyte*)pValue; case CorElementType.U1: return *(byte*)pValue; case CorElementType.Boolean: return Convert.ToUInt64(*(bool*)pValue, CultureInfo.InvariantCulture); case CorElementType.I2: return (ulong)*(short*)pValue; case CorElementType.U2: case CorElementType.Char: return *(ushort*)pValue; case CorElementType.I4: return (ulong)*(int*)pValue; case CorElementType.U4: case CorElementType.R4: return *(uint*)pValue; case CorElementType.I8: return (ulong)*(long*)pValue; case CorElementType.U8: case CorElementType.R8: return *(ulong*)pValue; case CorElementType.I: if (IntPtr.Size == 8) { return *(ulong*)pValue; } else { return (ulong)*(int*)pValue; } case CorElementType.U: if (IntPtr.Size == 8) { return *(ulong*)pValue; } else { return *(uint*)pValue; } default: Contract.Assert(false, "Invalid primitive type"); return 0; } } } [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern bool InternalHasFlag(Enum flags); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern CorElementType InternalGetCorElementType(); #endregion #region Object Overrides [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern override bool Equals(Object obj); [System.Security.SecuritySafeCritical] public override unsafe int GetHashCode() { // Avoid boxing by inlining GetValue() // return GetValue().GetHashCode(); fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data) { switch (InternalGetCorElementType()) { case CorElementType.I1: return (*(sbyte*)pValue).GetHashCode(); case CorElementType.U1: return (*(byte*)pValue).GetHashCode(); case CorElementType.Boolean: return (*(bool*)pValue).GetHashCode(); case CorElementType.I2: return (*(short*)pValue).GetHashCode(); case CorElementType.U2: return (*(ushort*)pValue).GetHashCode(); case CorElementType.Char: return (*(char*)pValue).GetHashCode(); case CorElementType.I4: return (*(int*)pValue).GetHashCode(); case CorElementType.U4: return (*(uint*)pValue).GetHashCode(); case CorElementType.R4: return (*(float*)pValue).GetHashCode(); case CorElementType.I8: return (*(long*)pValue).GetHashCode(); case CorElementType.U8: return (*(ulong*)pValue).GetHashCode(); case CorElementType.R8: return (*(double*)pValue).GetHashCode(); case CorElementType.I: return (*(IntPtr*)pValue).GetHashCode(); case CorElementType.U: return (*(UIntPtr*)pValue).GetHashCode(); default: Contract.Assert(false, "Invalid primitive type"); return 0; } } } public override String ToString() { // Returns the value in a human readable format. For PASCAL style enums who's value maps directly the name of the field is returned. // For PASCAL style enums who's values do not map directly the decimal value of the field is returned. // For BitFlags (indicated by the Flags custom attribute): If for each bit that is set in the value there is a corresponding constant //(a pure power of 2), then the OR string (ie "Red | Yellow") is returned. Otherwise, if the value is zero or if you can't create a string that consists of // pure powers of 2 OR-ed together, you return a hex value // Try to see if its one of the enum values, then we return a String back else the value return Enum.InternalFormat((RuntimeType)GetType(), ToUInt64()) ?? GetValue().ToString(); } #endregion #region IFormattable [Obsolete("The provider argument is not used. Please use ToString(String).")] public String ToString(String format, IFormatProvider provider) { return ToString(format); } #endregion #region IComparable [System.Security.SecuritySafeCritical] // auto-generated public int CompareTo(Object target) { const int retIncompatibleMethodTables = 2; // indicates that the method tables did not match const int retInvalidEnumType = 3; // indicates that the enum was of an unknown/unsupported unerlying type if (this == null) throw new NullReferenceException(); Contract.EndContractBlock(); int ret = InternalCompareTo(this, target); if (ret < retIncompatibleMethodTables) { // -1, 0 and 1 are the normal return codes return ret; } else if (ret == retIncompatibleMethodTables) { Type thisType = this.GetType(); Type targetType = target.GetType(); throw new ArgumentException(Environment.GetResourceString("Arg_EnumAndObjectMustBeSameType", targetType.ToString(), thisType.ToString())); } else { // assert valid return code (3) Contract.Assert(ret == retInvalidEnumType, "Enum.InternalCompareTo return code was invalid"); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType")); } } #endregion #region Public Methods public String ToString(String format) { char formatCh; if (format == null || format.Length == 0) formatCh = 'G'; else if (format.Length != 1) throw new FormatException(Environment.GetResourceString("Format_InvalidEnumFormatSpecification")); else formatCh = format[0]; if (formatCh == 'G' || formatCh == 'g') return ToString(); if (formatCh == 'D' || formatCh == 'd') return GetValue().ToString(); if (formatCh == 'X' || formatCh == 'x') return InternalFormattedHexString(); if (formatCh == 'F' || formatCh == 'f') return InternalFlagsFormat((RuntimeType)GetType(), ToUInt64()) ?? GetValue().ToString(); throw new FormatException(Environment.GetResourceString("Format_InvalidEnumFormatSpecification")); } [Obsolete("The provider argument is not used. Please use ToString().")] public String ToString(IFormatProvider provider) { return ToString(); } [System.Security.SecuritySafeCritical] public Boolean HasFlag(Enum flag) { if (flag == null) throw new ArgumentNullException("flag"); Contract.EndContractBlock(); if (!this.GetType().IsEquivalentTo(flag.GetType())) { throw new ArgumentException(Environment.GetResourceString("Argument_EnumTypeDoesNotMatch", flag.GetType(), this.GetType())); } return InternalHasFlag(flag); } #endregion #region IConvertable public TypeCode GetTypeCode() { Type enumType = this.GetType(); Type underlyingType = GetUnderlyingType(enumType); if (underlyingType == typeof(Int32)) { return TypeCode.Int32; } if (underlyingType == typeof(sbyte)) { return TypeCode.SByte; } if (underlyingType == typeof(Int16)) { return TypeCode.Int16; } if (underlyingType == typeof(Int64)) { return TypeCode.Int64; } if (underlyingType == typeof(UInt32)) { return TypeCode.UInt32; } if (underlyingType == typeof(byte)) { return TypeCode.Byte; } if (underlyingType == typeof(UInt16)) { return TypeCode.UInt16; } if (underlyingType == typeof(UInt64)) { return TypeCode.UInt64; } if (underlyingType == typeof(Boolean)) { return TypeCode.Boolean; } if (underlyingType == typeof(Char)) { return TypeCode.Char; } Contract.Assert(false, "Unknown underlying type."); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType")); } /// <internalonly/> bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Enum", "DateTime")); } /// <internalonly/> Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } #endregion #region ToObject [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, sbyte value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, short value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, int value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, byte value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, ushort value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, uint value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, long value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, ulong value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, unchecked((long)value)); } [System.Security.SecuritySafeCritical] // auto-generated private static Object ToObject(Type enumType, char value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated private static Object ToObject(Type enumType, bool value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value ? 1 : 0); } #endregion } }
using System.Linq; using EntityFramework.Extensions; using EntityFramework.Future; using Xunit; using Tracker.SqlServer.CodeFirst; using Tracker.SqlServer.CodeFirst.Entities; namespace Tracker.SqlServer.Test { public class FutureDbContext { [Fact] public void PageTest() { var db = new TrackerContext(); // base query var q = db.Tasks .Where(p => p.PriorityId == 2) .OrderByDescending(t => t.CreatedDate); // get total count var q1 = q.FutureCount(); // get first page var q2 = q.Skip(0).Take(10).Future(); // triggers sql execute as a batch var tasks = q2.ToList(); int total = q1.Value; Assert.NotNull(tasks); } [Fact] public void SimpleTest() { var db = new TrackerContext(); // build up queries string emailDomain = "@battlestar.com"; var q1 = db.Users .Where(p => p.EmailAddress.EndsWith(emailDomain)) .Future(); string search = "Earth"; var q2 = db.Tasks .Where(t => t.Summary.Contains(search)) .Future(); // should be 2 queries //Assert.Equal(2, db.FutureQueries.Count); // this triggers the loading of all the future queries var users = q1.ToList(); Assert.NotNull(users); // should be cleared at this point //Assert.Equal(0, db.FutureQueries.Count); // this should already be loaded Assert.True(((IFutureQuery)q2).IsLoaded); var tasks = q2.ToList(); Assert.NotNull(tasks); } [Fact] public void FutureCountTest() { var db = new TrackerContext(); // build up queries string emailDomain = "@battlestar.com"; var q1 = db.Users .Where(p => p.EmailAddress.EndsWith(emailDomain)) .Future(); string search = "Earth"; var q2 = db.Tasks .Where(t => t.Summary.Contains(search)) .FutureCount(); // should be 2 queries //Assert.Equal(2, db.FutureQueries.Count); // this triggers the loading of all the future queries var users = q1.ToList(); Assert.NotNull(users); // should be cleared at this point //Assert.Equal(0, db.FutureQueries.Count); // this should already be loaded Assert.True(((IFutureQuery)q2).IsLoaded); int count = q2; Assert.NotEqual(count, 0); } [Fact] public void FutureCountReverseTest() { var db = new TrackerContext(); // build up queries string emailDomain = "@battlestar.com"; var q1 = db.Users .Where(p => p.EmailAddress.EndsWith(emailDomain)) .Future(); string search = "Earth"; var q2 = db.Tasks .Where(t => t.Summary.Contains(search)) .FutureCount(); // should be 2 queries //Assert.Equal(2, db.FutureQueries.Count); // access q2 first to trigger loading, testing loading from FutureCount // this triggers the loading of all the future queries var count = q2.Value; Assert.NotEqual(count, 0); // should be cleared at this point //Assert.Equal(0, db.FutureQueries.Count); // this should already be loaded Assert.True(((IFutureQuery)q1).IsLoaded); var users = q1.ToList(); Assert.NotNull(users); } [Fact] public void FutureValueTest() { var db = new TrackerContext(); // build up queries string emailDomain = "@battlestar.com"; var q1 = db.Users .Where(p => p.EmailAddress.EndsWith(emailDomain)) .FutureFirstOrDefault(); string search = "Earth"; var q2 = db.Tasks .Where(t => t.Summary.Contains(search)) .FutureCount(); // duplicate query except count var q3 = db.Tasks .Where(t => t.Summary.Contains(search)) .Future(); // should be 3 queries //Assert.Equal(3, db.FutureQueries.Count); // this triggers the loading of all the future queries User user = q1; Assert.NotNull(user); // should be cleared at this point //Assert.Equal(0, db.FutureQueries.Count); // this should already be loaded Assert.True(((IFutureQuery)q2).IsLoaded); var count = q2.Value; Assert.NotEqual(count, 0); var tasks = q3.ToList(); Assert.NotNull(tasks); } [Fact] public void FutureValueReverseTest() { var db = new TrackerContext(); // build up queries string emailDomain = "@battlestar.com"; var q1 = db.Users .Where(p => p.EmailAddress.EndsWith(emailDomain)) .FutureFirstOrDefault(); string search = "Earth"; var q2 = db.Tasks .Where(t => t.Summary.Contains(search)) .FutureCount(); // duplicate query except count var q3 = db.Tasks .Where(t => t.Summary.Contains(search)) .Future(); // should be 3 queries //Assert.Equal(3, db.FutureQueries.Count); // access q2 first to trigger loading, testing loading from FutureCount // this triggers the loading of all the future queries var count = q2.Value; Assert.NotEqual(count, 0); // should be cleared at this point //Assert.Equal(0, db.FutureQueries.Count); // this should already be loaded Assert.True(((IFutureQuery)q1).IsLoaded); var users = q1.Value; Assert.NotNull(users); var tasks = q3.ToList(); Assert.NotNull(tasks); } [Fact] public void FutureValueWithAggregateFunctions() { var db = new TrackerContext(); var q1 = db.Users.Where(x => x.EmailAddress.EndsWith("@battlestar.com")).FutureValue(x => x.Count()); var q2 = db.Users.Where(x => x.EmailAddress.EndsWith("@battlestar.com")).FutureValue(x => x.Min(t => t.LastName)); var q3 = db.Tasks.FutureValue(x => x.Sum(t => t.Priority.Order)); Assert.False(((IFutureQuery)q1).IsLoaded); Assert.False(((IFutureQuery)q2).IsLoaded); Assert.False(((IFutureQuery)q3).IsLoaded); var r1 = q1.Value; var r2 = q2.Value; var r3 = q3.Value; Assert.True(((IFutureQuery)q1).IsLoaded); Assert.True(((IFutureQuery)q2).IsLoaded); Assert.True(((IFutureQuery)q3).IsLoaded); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Linq; namespace Shielded { #if USE_STD_HASHSET internal class SimpleHashSet : HashSet<IShielded> { /// <summary> /// Performs the commit check on the enlisted items. /// </summary> public bool CanCommit(WriteStamp ws) { foreach (var item in this) if (!item.CanCommit(ws)) return false; return true; } /// <summary> /// Commits the enlisted items. /// </summary> public List<IShielded> Commit() { List<IShielded> changes = new List<IShielded>(); foreach (var item in this) { if (item.HasChanges) changes.Add(item); item.Commit(); } return changes; } /// <summary> /// Commits items without preparing a list of changed ones, to use /// when you know that there are no changes. /// </summary> public void CommitWoChanges() { foreach (var item in this) item.Commit(); } /// <summary> /// Rolls the enlisted items back. /// </summary> public void Rollback() { foreach (var item in this) item.Rollback(); } /// <summary> /// Helper for trimming. /// </summary> public void TrimCopies(long minOpenTransaction) { foreach (var item in this) item.TrimCopies(minOpenTransaction); } } #else internal class SimpleHashSet : ICollection<IShielded> { private int _count; private const int SizeShift = 3; private const int InitSize = 1 << SizeShift; private int _mask; private IShielded[] _array; private int _bloom; public SimpleHashSet() { _mask = InitSize - 1; _array = new IShielded[InitSize]; } bool AddInternal(IShielded item) { if (Place(item)) { _bloom = _bloom | (1 << (item.GetHashCode() & 0x1F)); if (++_count >= (_mask ^ (_mask >> 2))) Increase(); return true; } return false; } bool Place(IShielded item) { var i = item.GetHashCode() & _mask; for ( ; _array[i] != null && _array[i] != item; i = (++i & _mask)) ; if (_array[i] == null) { _array[i] = item; return true; } return false; } void Increase() { var oldCount = _mask + 1; var newCount = oldCount << 1; var oldArray = _array; _array = new IShielded[newCount]; _mask = newCount - 1; for (int i = 0; i < oldCount; i++) { if (oldArray[i] != null) Place(oldArray[i]); } } /// <summary> /// Performs the commit check on the enlisted items. /// </summary> public bool CanCommit(WriteStamp ws) { for (int i = 0; i < _array.Length; i++) if (_array[i] != null && !_array[i].CanCommit(ws)) return false; return true; } /// <summary> /// Commits the enlisted items. /// </summary> public List<IShielded> Commit() { List<IShielded> changes = new List<IShielded>(); for (int i = 0; i < _array.Length; i++) { var item = _array[i]; if (item != null) { if (item.HasChanges) changes.Add(item); item.Commit(); } } return changes; } /// <summary> /// Commits items without preparing a list of changed ones, to use /// when you know that there are no changes. /// </summary> public void CommitWoChanges() { for (int i = 0; i < _array.Length; i++) if (_array[i] != null) _array[i].Commit(); } /// <summary> /// Rolls the enlisted items back. /// </summary> public void Rollback() { for (int i = 0; i < _array.Length; i++) if (_array[i] != null) _array[i].Rollback(); } /// <summary> /// Helper for trimming. /// </summary> public void TrimCopies(long minOpenTransaction) { for (int i = 0; i < _array.Length; i++) if (_array[i] != null) _array[i].TrimCopies(minOpenTransaction); } #region IEnumerable implementation IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<IShielded>)this).GetEnumerator(); } #endregion #region IEnumerable implementation public IEnumerator<IShielded> GetEnumerator() { for (int i = 0; i < _array.Length; i++) { if (_array[i] != null) yield return _array[i]; } } #endregion #region ICollection implementation void ICollection<IShielded>.Add(IShielded item) { throw new System.NotImplementedException(); } void ICollection<IShielded>.Clear() { throw new System.NotImplementedException(); } public bool Contains(IShielded item) { var hash = item.GetHashCode(); if (((1 << (hash & 0x1F)) & _bloom) == 0) return false; var i = hash & _mask; for ( ; _array[i] != null && _array[i] != item; i = (++i & _mask)) ; return _array[i] != null; } void ICollection<IShielded>.CopyTo(IShielded[] target, int arrayIndex) { if (_count + arrayIndex > target.Length) throw new IndexOutOfRangeException(); for (int i = 0; i < _array.Length; i++) if (_array[i] != null) target[arrayIndex++] = _array[i]; } bool ICollection<IShielded>.Remove(IShielded item) { throw new System.NotImplementedException(); } public int Count { get { return _count; } } bool ICollection<IShielded>.IsReadOnly { get { return false; } } #endregion #region Partial ISet impl public bool Add(IShielded item) { return AddInternal(item); } public bool Overlaps(SimpleHashSet other) { if ((other._bloom & this._bloom) == 0) return false; for (int i = 0; i < other._array.Length; i++) if (other._array[i] != null && Contains(other._array[i])) return true; return false; } public bool Overlaps(IShielded[] other) { for (int i = 0; i < other.Length; i++) if (Contains(other[i])) return true; return false; } public bool Overlaps(IEnumerable<IShielded> other) { return other.Any(Contains); } public bool SetEquals(SimpleHashSet other) { if (other._bloom != this._bloom || other._count != _count) return false; for (int i = 0; i < other._array.Length; i++) if (other._array[i] != null && !Contains(other._array[i])) return false; return true; } public void UnionWith(SimpleHashSet otherAsSet) { for (int i = 0; i < otherAsSet._array.Length; i++) if (otherAsSet._array[i] != null) AddInternal(otherAsSet._array[i]); } public void UnionWith(IEnumerable<IShielded> other) { var otherAsSet = other as SimpleHashSet; if (otherAsSet != null) { UnionWith(otherAsSet); return; } var otherAsList = other as List<IShielded>; if (otherAsList != null) { for (int i = 0; i < otherAsList.Count; i++) AddInternal(otherAsList[i]); return; } foreach (var item in other) AddInternal(item); } #endregion } #endif }
// ReSharper disable InconsistentNaming namespace Orders.com.WPF { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; /* * * License: * * Microsoft Public License (MS-PL) * * This license governs use of the accompanying software. If you use the software, you * accept this license. If you do not accept the license, do not use the software. * * 1. Definitions * The terms "reproduce," "reproduction," "derivative works," and "distribution" have the * same meaning here as under U.S. copyright law. * A "contribution" is the original software, or any additions or changes to the software. * A "contributor" is any person that distributes its contribution under this license. * "Licensed patents" are a contributor's patent claims that read directly on its contribution. * * 2. Grant of Rights * (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. * (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. * * 3. Conditions and Limitations * (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. * (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. * (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. * (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. * (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. * * Little bit of history: * EventAggregator origins based on work from StatLight's EventAggregator. Which * is based on original work by Jermey Miller's EventAggregator in StoryTeller * with some concepts pulled from Rob Eisenberg in caliburnmicro. * * TODO: * - Possibly provide well defined initial thread marshalling actions (depending on platform (WinForm, WPF, Silverlight, WP7???) * - Document the public API better. * * Thanks to: * - Jermey Miller - initial implementation * - Rob Eisenberg - pulled some ideas from the caliburn micro event aggregator * - Jake Ginnivan - https://github.com/JakeGinnivan - thanks for the pull requests * */ /// <summary> /// Specifies a class that would like to receive particular messages. /// </summary> /// <typeparam name="TMessage">The type of message object to subscribe to.</typeparam> #if WINDOWS_PHONE public interface IListener<TMessage> #else public interface IListener<in TMessage> #endif { /// <summary> /// This will be called every time a TMessage is published through the event aggregator /// </summary> void Handle(TMessage message); } /// <summary> /// Provides a way to add and remove a listener object from the EventAggregator /// </summary> public interface IEventSubscriptionManager { /// <summary> /// Adds the given listener object to the EventAggregator. /// </summary> /// <param name="listener">Object that should be implementing IListener(of T's), this overload is used when your listeners to multiple message types</param> /// <param name="holdStrongReference">determines if the EventAggregator should hold a weak or strong reference to the listener object. If null it will use the Config level option unless overriden by the parameter.</param> /// <returns>Returns the current IEventSubscriptionManager to allow for easy fluent additions.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")] IEventSubscriptionManager AddListener(object listener, bool? holdStrongReference = null); /// <summary> /// Adds the given listener object to the EventAggregator. /// </summary> /// <typeparam name="T">Listener Message type</typeparam> /// <param name="listener"></param> /// <param name="holdStrongReference">determines if the EventAggregator should hold a weak or strong reference to the listener object. If null it will use the Config level option unless overriden by the parameter.</param> /// <returns>Returns the current IEventSubscriptionManager to allow for easy fluent additions.</returns> IEventSubscriptionManager AddListener<T>(IListener<T> listener, bool? holdStrongReference = null); /// <summary> /// Removes the listener object from the EventAggregator /// </summary> /// <param name="listener">The object to be removed</param> /// <returns>Returnes the current IEventSubscriptionManager for fluent removals.</returns> IEventSubscriptionManager RemoveListener(object listener); } public interface IEventPublisher { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")] void SendMessage<TMessage>(TMessage message, Action<Action> marshal = null); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")] void SendMessage<TMessage>(Action<Action> marshal = null) where TMessage : new(); } public interface IEventAggregator : IEventPublisher, IEventSubscriptionManager { } public class EventAggregator : IEventAggregator { private readonly ListenerWrapperCollection _listeners; private readonly Config _config; public EventAggregator() : this(new Config()) { } public EventAggregator(Config config) { _config = config; _listeners = new ListenerWrapperCollection(); } /// <summary> /// This will send the message to each IListener that is subscribing to TMessage. /// </summary> /// <typeparam name="TMessage">The type of message being sent</typeparam> /// <param name="message">The message instance</param> /// <param name="marshal">You can optionally override how the message publication action is marshalled</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")] public void SendMessage<TMessage>(TMessage message, Action<Action> marshal = null) { if (marshal == null) marshal = _config.DefaultThreadMarshaler; Call<IListener<TMessage>>(message, marshal); } /// <summary> /// This will create a new default instance of TMessage and send the message to each IListener that is subscribing to TMessage. /// </summary> /// <typeparam name="TMessage">The type of message being sent</typeparam> /// <param name="marshal">You can optionally override how the message publication action is marshalled</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")] public void SendMessage<TMessage>(Action<Action> marshal = null) where TMessage : new() { SendMessage(new TMessage(), marshal); } private void Call<TListener>(object message, Action<Action> marshaller) where TListener : class { var listenerCalledCount = 0; marshaller(() => { foreach (ListenerWrapper o in _listeners.Where(o => o.Handles<TListener>() || o.HandlesMessage(message))) { bool wasThisOneCalled; o.TryHandle<TListener>(message, out wasThisOneCalled); if (wasThisOneCalled) listenerCalledCount++; } }); var wasAnyListenerCalled = listenerCalledCount > 0; if (!wasAnyListenerCalled) { _config.OnMessageNotPublishedBecauseZeroListeners(message); } } public IEventSubscriptionManager AddListener(object listener) { return AddListener(listener, null); } public IEventSubscriptionManager AddListener(object listener, bool? holdStrongReference) { if (listener == null) throw new ArgumentNullException("listener"); bool holdRef = _config.HoldReferences; if (holdStrongReference.HasValue) holdRef = holdStrongReference.Value; bool supportMessageInheritance = _config.SupportMessageInheritance; _listeners.AddListener(listener, holdRef, supportMessageInheritance); return this; } public IEventSubscriptionManager AddListener<T>(IListener<T> listener, bool? holdStrongReference) { AddListener((object) listener, holdStrongReference); return this; } public IEventSubscriptionManager RemoveListener(object listener) { _listeners.RemoveListener(listener); return this; } /// <summary> /// Wrapper collection of ListenerWrappers to manage things like /// threadsafe manipulation to the collection, and convenience /// methods to configure the collection /// </summary> private class ListenerWrapperCollection : IEnumerable<ListenerWrapper> { private readonly List<ListenerWrapper> _listeners = new List<ListenerWrapper>(); private readonly object _sync = new object(); public void RemoveListener(object listener) { ListenerWrapper listenerWrapper; lock (_sync) if (TryGetListenerWrapperByListener(listener, out listenerWrapper)) _listeners.Remove(listenerWrapper); } private void RemoveListenerWrapper(ListenerWrapper listenerWrapper) { lock (_sync) _listeners.Remove(listenerWrapper); } public IEnumerator<ListenerWrapper> GetEnumerator() { lock (_sync) return _listeners.ToList().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private bool ContainsListener(object listener) { ListenerWrapper listenerWrapper; return TryGetListenerWrapperByListener(listener, out listenerWrapper); } private bool TryGetListenerWrapperByListener(object listener, out ListenerWrapper listenerWrapper) { lock (_sync) listenerWrapper = _listeners.SingleOrDefault(x => x.ListenerInstance == listener); return listenerWrapper != null; } public void AddListener(object listener, bool holdStrongReference, bool supportMessageInheritance) { lock (_sync) { if (ContainsListener(listener)) return; var listenerWrapper = new ListenerWrapper(listener, RemoveListenerWrapper, holdStrongReference, supportMessageInheritance); if (listenerWrapper.Count == 0) throw new ArgumentException("IListener<T> is not implemented", "listener"); _listeners.Add(listenerWrapper); } } } #region IReference private interface IReference { object Target { get; } } private class WeakReferenceImpl : IReference { private readonly WeakReference _reference; public WeakReferenceImpl(object listener) { _reference = new WeakReference(listener); } public object Target { get { return _reference.Target; } } } private class StrongReferenceImpl : IReference { private readonly object _target; public StrongReferenceImpl(object target) { _target = target; } public object Target { get { return _target; } } } #endregion private class ListenerWrapper { private const string HandleMethodName = "Handle"; private readonly Action<ListenerWrapper> _onRemoveCallback; private readonly List<HandleMethodWrapper> _handlers = new List<HandleMethodWrapper>(); private readonly IReference _reference; public ListenerWrapper(object listener, Action<ListenerWrapper> onRemoveCallback, bool holdReferences, bool supportMessageInheritance) { _onRemoveCallback = onRemoveCallback; if (holdReferences) _reference = new StrongReferenceImpl(listener); else _reference = new WeakReferenceImpl(listener); var listenerInterfaces = TypeHelper.GetBaseInterfaceType(listener.GetType()) .Where(w => TypeHelper.DirectlyClosesGeneric(w, typeof (IListener<>))); foreach (var listenerInterface in listenerInterfaces) { var messageType = TypeHelper.GetFirstGenericType(listenerInterface); var handleMethod = TypeHelper.GetMethod(listenerInterface, HandleMethodName); HandleMethodWrapper handler = new HandleMethodWrapper(handleMethod, listenerInterface, messageType,supportMessageInheritance ); _handlers.Add(handler); } } public object ListenerInstance { get { return _reference.Target; } } public bool Handles<TListener>() where TListener : class { return _handlers.Aggregate(false, (current, handler) => current | handler.Handles<TListener>()); } public bool HandlesMessage(object message) { return message != null && _handlers.Aggregate(false, (current, handler) => current | handler.HandlesMessage(message)); } public void TryHandle<TListener>(object message, out bool wasHandled) where TListener : class { var target = _reference.Target; wasHandled = false; if (target == null) { _onRemoveCallback(this); return; } foreach (var handler in _handlers) { bool thisOneHandled = false; handler.TryHandle<TListener>(target, message, out thisOneHandled); wasHandled |= thisOneHandled; } } public int Count { get { return _handlers.Count; } } } private class HandleMethodWrapper { private readonly Type _listenerInterface; private readonly Type _messageType; private readonly MethodInfo _handlerMethod; private readonly bool _supportMessageInheritance; private readonly Dictionary<Type, bool> supportedMessageTypes = new Dictionary<Type, bool>(); public HandleMethodWrapper(MethodInfo handlerMethod, Type listenerInterface, Type messageType, bool supportMessageInheritance) { _handlerMethod = handlerMethod; _listenerInterface = listenerInterface; _messageType = messageType; _supportMessageInheritance = supportMessageInheritance; supportedMessageTypes[messageType] = true; } public bool Handles<TListener>() where TListener : class { return _listenerInterface == typeof (TListener); } public bool HandlesMessage(object message) { if (message == null) { return false; } bool handled; Type messageType = message.GetType(); bool previousMessageType = supportedMessageTypes.TryGetValue(messageType, out handled); if (!previousMessageType && _supportMessageInheritance) { handled = TypeHelper.IsAssignableFrom(_messageType, messageType); supportedMessageTypes[messageType] = handled; } return handled; } public void TryHandle<TListener>(object target, object message, out bool wasHandled) where TListener : class { wasHandled = false; if (target == null) { return; } if (!Handles<TListener>() && !HandlesMessage(message)) return; _handlerMethod.Invoke(target, new[] {message}); wasHandled = true; } } internal static class TypeHelper { internal static IEnumerable<Type> GetBaseInterfaceType(Type type) { if (type == null) return new Type[0]; #if NETFX_CORE var interfaces = type.GetTypeInfo().ImplementedInterfaces.ToList(); #else var interfaces = type.GetInterfaces().ToList(); #endif foreach (var @interface in interfaces.ToArray()) { interfaces.AddRange(GetBaseInterfaceType(@interface)); } #if NETFX_CORE if (type.GetTypeInfo().IsInterface) #else if (type.IsInterface) #endif { interfaces.Add(type); } return interfaces.Distinct(); } internal static bool DirectlyClosesGeneric(Type type, Type openType) { if (type == null) return false; #if NETFX_CORE if (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == openType) #else if (type.IsGenericType && type.GetGenericTypeDefinition() == openType) #endif { return true; } return false; } internal static Type GetFirstGenericType<T>() where T : class { return GetFirstGenericType(typeof (T)); } internal static Type GetFirstGenericType(Type type) { #if NETFX_CORE var messageType = type.GetTypeInfo().GenericTypeArguments.First(); #else var messageType = type.GetGenericArguments().First(); #endif return messageType; } internal static MethodInfo GetMethod(Type type, string methodName) { #if NETFX_CORE var typeInfo = type.GetTypeInfo(); var handleMethod = typeInfo.GetDeclaredMethod(methodName); #else var handleMethod = type.GetMethod(methodName); #endif return handleMethod; } internal static bool IsAssignableFrom(Type type, Type specifiedType) { #if NETFX_CORE return type.GetTypeInfo().IsAssignableFrom(specifiedType.GetTypeInfo()); #else return type.IsAssignableFrom(specifiedType); #endif } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] public class Config { private Action<object> _onMessageNotPublishedBecauseZeroListeners = msg => { /* TODO: possibly Trace message?*/ }; public Action<object> OnMessageNotPublishedBecauseZeroListeners { get { return _onMessageNotPublishedBecauseZeroListeners; } set { _onMessageNotPublishedBecauseZeroListeners = value; } } private Action<Action> _defaultThreadMarshaler = action => action(); public Action<Action> DefaultThreadMarshaler { get { return _defaultThreadMarshaler; } set { _defaultThreadMarshaler = value; } } /// <summary> /// If true instructs the EventAggregator to hold onto a reference to all listener objects. You will then have to explicitly remove them from the EventAggrator. /// If false then a WeakReference is used and the garbage collector can remove the listener when not in scope any longer. /// </summary> public bool HoldReferences { get; set; } /// <summary> /// If true then EventAggregator will support registering listeners for base messages. /// If false then EventAggregator will only match the message type to the listener. /// </summary> public bool SupportMessageInheritance { get; set; } } } } // ReSharper enable InconsistentNaming
/* * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using Aurora.DataManager; using Aurora.Simulation.Base; using Nini.Config; using OpenMetaverse; using Aurora.Framework; using OpenSim.Services.Interfaces; namespace OpenSim.Services.AssetService { public class AssetService : ConnectorBase, IAssetService, IService { #region Declares protected IAssetDataPlugin m_database; protected bool doDatabaseCaching = false; #endregion #region IService Members public virtual string Name { get { return GetType().Name; } } public virtual void Initialize(IConfigSource config, IRegistryCore registry) { IConfig handlerConfig = config.Configs["Handlers"]; if (handlerConfig.GetString("AssetHandler", "") != Name) return; Configure(config, registry); Init(registry, Name); } public virtual void Configure(IConfigSource config, IRegistryCore registry) { m_registry = registry; m_database = DataManager.RequestPlugin<IAssetDataPlugin>(); if (m_database == null) throw new Exception("Could not find a storage interface in the given module"); registry.RegisterModuleInterface<IAssetService>(this); if (MainConsole.Instance != null) { MainConsole.Instance.Commands.AddCommand("show digest", "show digest <ID>", "Show asset digest", HandleShowDigest); MainConsole.Instance.Commands.AddCommand("delete asset", "delete asset <ID>", "Delete asset from database", HandleDeleteAsset); } MainConsole.Instance.Debug("[ASSET SERVICE]: Local asset service enabled"); } public virtual void Start(IConfigSource config, IRegistryCore registry) { } public virtual void FinishedStartup() { } #endregion #region IAssetService Members public IAssetService InnerService { get { return this; } } [CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)] public virtual AssetBase Get(string id) { IImprovedAssetCache cache = m_registry.RequestModuleInterface<IImprovedAssetCache>(); if (doDatabaseCaching && cache != null) { bool found; AssetBase cachedAsset = cache.Get(id, out found); if (found && (cachedAsset == null || cachedAsset.Data.Length != 0)) return cachedAsset; } object remoteValue = DoRemote(id); if (remoteValue != null || m_doRemoteOnly) { if (doDatabaseCaching && cache != null) cache.Cache(id, (AssetBase)remoteValue); return (AssetBase)remoteValue; } AssetBase asset = m_database.GetAsset(UUID.Parse(id)); if (doDatabaseCaching && cache != null) cache.Cache(id, asset); return asset; } [CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)] public virtual AssetBase GetCached(string id) { IImprovedAssetCache cache = m_registry.RequestModuleInterface<IImprovedAssetCache>(); if (doDatabaseCaching && cache != null) return cache.Get(id); return null; } [CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)] public virtual byte[] GetData(string id) { IImprovedAssetCache cache = m_registry.RequestModuleInterface<IImprovedAssetCache>(); if (doDatabaseCaching && cache != null) { bool found; AssetBase cachedAsset = cache.Get(id, out found); if (found && (cachedAsset == null || cachedAsset.Data.Length != 0)) return cachedAsset.Data; } object remoteValue = DoRemote(id); if (remoteValue != null || m_doRemoteOnly) return (byte[])remoteValue; AssetBase asset = m_database.GetAsset(UUID.Parse(id)); if (doDatabaseCaching && cache != null) cache.Cache(id, asset); if (asset != null) return asset.Data; return new byte[0]; } [CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)] public virtual bool GetExists(string id) { object remoteValue = DoRemote(id); if (remoteValue != null || m_doRemoteOnly) return remoteValue == null ? false : (bool)remoteValue; return m_database.ExistsAsset(UUID.Parse(id)); } [CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)] public virtual void Get(String id, Object sender, AssetRetrieved handler) { Util.FireAndForget((o) => { handler(id, sender, Get(id)); }); } [CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)] public virtual UUID Store(AssetBase asset) { object remoteValue = DoRemote(asset); if (remoteValue != null || m_doRemoteOnly) asset.ID = (UUID)remoteValue; else //MainConsole.Instance.DebugFormat("[ASSET SERVICE]: Store asset {0} {1}", asset.Name, asset.ID); asset.ID = m_database.Store(asset); IImprovedAssetCache cache = m_registry.RequestModuleInterface<IImprovedAssetCache>(); if (doDatabaseCaching && cache != null && asset != null && asset.Data != null && asset.Data.Length != 0) { cache.Expire(asset.ID.ToString()); cache.Cache(asset.ID.ToString(), asset); } return asset != null ? asset.ID : UUID.Zero; } [CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)] public virtual UUID UpdateContent(UUID id, byte[] data) { object remoteValue = DoRemote(id, data); if (remoteValue != null || m_doRemoteOnly) return remoteValue == null ? UUID.Zero : (UUID)remoteValue; UUID newID; m_database.UpdateContent(id, data, out newID); IImprovedAssetCache cache = m_registry.RequestModuleInterface<IImprovedAssetCache>(); if (doDatabaseCaching && cache != null) cache.Expire(id.ToString()); return newID; } [CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)] public virtual bool Delete(UUID id) { object remoteValue = DoRemote(id); if (remoteValue != null || m_doRemoteOnly) return remoteValue == null ? false : (bool)remoteValue; return m_database.Delete(id); } #endregion #region Console Commands private void HandleShowDigest(string[] args) { if (args.Length < 3) { MainConsole.Instance.Info("Syntax: show digest <ID>"); return; } AssetBase asset = Get(args[2]); if (asset == null || asset.Data.Length == 0) { MainConsole.Instance.Info("Asset not found"); return; } int i; MainConsole.Instance.Info(String.Format("Name: {0}", asset.Name)); MainConsole.Instance.Info(String.Format("Description: {0}", asset.Description)); MainConsole.Instance.Info(String.Format("Type: {0}", asset.TypeAsset)); MainConsole.Instance.Info(String.Format("Content-type: {0}", asset.TypeAsset.ToString())); MainConsole.Instance.Info(String.Format("Flags: {0}", asset.Flags)); for (i = 0; i < 5; i++) { int off = i*16; if (asset.Data.Length <= off) break; int len = 16; if (asset.Data.Length < off + len) len = asset.Data.Length - off; byte[] line = new byte[len]; Array.Copy(asset.Data, off, line, 0, len); string text = BitConverter.ToString(line); MainConsole.Instance.Info(String.Format("{0:x4}: {1}", off, text)); } } private void HandleDeleteAsset(string[] args) { if (args.Length < 3) { MainConsole.Instance.Info("Syntax: delete asset <ID>"); return; } AssetBase asset = Get(args[2]); if (asset == null || asset.Data.Length == 0) { MainConsole.Instance.Info("Asset not found"); return; } Delete(UUID.Parse(args[2])); MainConsole.Instance.Info("Asset deleted"); } #endregion } }
#region Copyright (C) 2013 // Project hw.nuget // Copyright (C) 2013 - 2013 Harald Hoyer // // 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 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // Comments, bugs and suggestions to hahoyer at yahoo.de #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using hw.Helper; namespace hw.Debug { public sealed class Profiler { sealed class Dumper { readonly int? _count; readonly ProfileItem[] _data; readonly TimeSpan _sumMax; readonly TimeSpan _sumAll; int _index; TimeSpan _sum; public Dumper(Profiler profiler, int? count, double hidden) { _count = count; _data = profiler._profileItems.Values.OrderByDescending(x => x.Duration).ToArray(); _sumAll = _data.Sum(x => x.Duration); _sumMax = new TimeSpan((long) (_sumAll.Ticks * (1.0 - hidden))); _index = 0; _sum = new TimeSpan(); } public string Format() { if(_data.Length == 0) return "\n=========== Profile empty ============\n"; var result = ""; for(; _index < _data.Length && _index != _count && _sum <= _sumMax; _index++) { var item = _data[_index]; result += item.Format(_index.ToString()); _sum += item.Duration; } var stringAligner = new StringAligner(); stringAligner.AddFloatingColumn("#"); stringAligner.AddFloatingColumn(" "); stringAligner.AddFloatingColumn(" "); stringAligner.AddFloatingColumn(" "); result = "\n=========== Profile ==================\n" + stringAligner.Format(result); result += "Total:\t" + _sumAll.Format3Digits(); if(_index < _data.Length) result += " (" + (_data.Length - _index) + " not-shown-items " + (_sumAll - _sum).Format3Digits() + ")"; result += "\n======================================\n"; return result; } } /// <summary> /// Measures the specified expression. /// </summary> /// <typeparam name="T"> The type the specitied expression returns </typeparam> /// <param name="expression"> a function without parameters returning something. </param> /// <returns> the result of the invokation of the specified expression </returns> public static T Measure<T>(Func<T> expression) { return _instance.InternalMeasure("", expression, 1); } /// <summary> /// Measures the specified action. /// </summary> /// <param name="action"> The action. </param> public static void Measure(Action action) { _instance.InternalMeasure("", action, 1); } /// <summary> /// Measures the specified expression. /// </summary> /// <typeparam name="T"> The type the specitied expression returns </typeparam> /// <param name="flag"> A flag that is used in dump. </param> /// <param name="expression"> a function without parameters returning something. </param> /// <returns> the result of the invokation of the specified expression </returns> public static T Measure<T>(string flag, Func<T> expression) { return _instance.InternalMeasure(flag, expression, 1); } /// <summary> /// Measures the specified action. /// </summary> /// <param name="flag"> A flag that is used in dump. </param> /// <param name="action"> The action. </param> public static void Measure(string flag, Action action) { _instance.InternalMeasure(flag, action, 1); } /// <summary> /// Resets the profiler data. /// </summary> public static void Reset() { lock(_instance) _instance.InternalReset(); _instance = new Profiler(); } /// <summary> /// Formats the data accumulated so far. /// </summary> /// <param name="count"> The number of measured expressions in result. </param> /// <param name="hidden"> The relative amount of time that will be hidden in result. </param> /// <returns> The formatted data. </returns> /// <remarks> /// The result contains one line for each measured expression, that is not ignored. Each line contains /// <para> /// - the file path, the line and the start column of the measuered expression in the source file, /// (The information is formatted in a way, that within VisualStudio doubleclicking on such a line will open it.) /// </para> /// <para>- the flag, if provided,</para> /// <para>- the ranking,</para> /// <para>- the execution count,</para> /// <para>- the average duration of one execution,</para> /// <para>- the duration,</para> /// of the expression. The the lines are sorted by descending duration. by use of /// <paramref /// name="count" /> /// and <paramref name="hidden" /> the number of lines can be restricted. /// </remarks> public static string Format(int? count = null, double hidden = 0.1) { lock(_instance) return new Dumper(_instance, count, hidden).Format(); } static Profiler _instance = new Profiler(); readonly Dictionary<string, ProfileItem> _profileItems = new Dictionary<string, ProfileItem>(); readonly Stopwatch _stopwatch; readonly Stack<ProfileItem> _stack = new Stack<ProfileItem>(); ProfileItem _current; Profiler() { _current = new ProfileItem(""); _stopwatch = new Stopwatch(); _current.Start(_stopwatch.Elapsed); _stopwatch.Start(); } void InternalMeasure(string flag, Action action, int depth) { BeforeAction(flag, depth + 1); action(); AfterAction(); } T InternalMeasure<T>(string flag, Func<T> expression, int depth) { BeforeAction(flag, depth + 1); var result = expression(); AfterAction(); return result; } void BeforeAction(string flag, int depth) { lock(this) { _stopwatch.Stop(); var start = _stopwatch.Elapsed; _current.Suspend(start); _stack.Push(_current); var position = Tracer.MethodHeader(depth + 1, FilePositionTag.Profiler) + flag; if(!_profileItems.TryGetValue(position, out _current)) { _current = new ProfileItem(position); _profileItems.Add(position, _current); } _current.Start(start); _stopwatch.Start(); } } void AfterAction() { lock(this) { _stopwatch.Stop(); var end = _stopwatch.Elapsed; _current.End(end); _current = _stack.Pop(); _current.Resume(end); _stopwatch.Start(); } } void InternalReset() { Tracer.Assert(_stack.Count == 0); } } sealed class ProfileItem { readonly string _position; TimeSpan _duration; long _countStart; long _countEnd; long _suspendCount; public ProfileItem(string position) { _position = position; } public TimeSpan Duration { get { return _duration; } } TimeSpan AverageDuration { get { return new TimeSpan(_duration.Ticks / _countEnd); } } bool IsValid { get { return _countStart == _countEnd && _suspendCount == 0; } } public void Start(TimeSpan duration) { _countStart++; _duration -= duration; if(IsValid) Tracer.Assert(_duration.Ticks >= 0); } public void End(TimeSpan duration) { _countEnd++; _duration += duration; if(IsValid) Tracer.Assert(_duration.Ticks >= 0); } public string Format(string tag) { Tracer.Assert(IsValid); return _position + " #" + tag + ": " + _countEnd.Format3Digits() + "x " + AverageDuration.Format3Digits() + " " + _duration.Format3Digits() + "\n"; } public void Suspend(TimeSpan start) { _suspendCount++; _duration += start; if(IsValid) Tracer.Assert(_duration.Ticks >= 0); } public void Resume(TimeSpan end) { _suspendCount--; _duration -= end; if(IsValid) Tracer.Assert(_duration.Ticks >= 0); } } }
/* * 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.Cache.Store { using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.Serialization; using System.Threading; using Apache.Ignite.Core.Cache.Store; using Apache.Ignite.Core.Resource; [SuppressMessage("ReSharper", "FieldCanBeMadeReadOnly.Local")] public class CacheTestStore : ICacheStore<object, object> { public static readonly IDictionary Map = new ConcurrentDictionary<object, object>(); public static bool LoadMultithreaded; public static bool LoadObjects; public static bool ThrowError; [InstanceResource] private IIgnite _grid = null; [StoreSessionResource] #pragma warning disable 649 private ICacheStoreSession _ses; #pragma warning restore 649 public static int intProperty; public static string stringProperty; public static void Reset() { Map.Clear(); LoadMultithreaded = false; LoadObjects = false; ThrowError = false; } public void LoadCache(Action<object, object> act, params object[] args) { ThrowIfNeeded(); Debug.Assert(_grid != null); if (args == null || args.Length == 0) return; if (args.Length == 3 && args[0] == null) { // Testing arguments passing. var key = args[1]; var val = args[2]; act(key, val); return; } if (LoadMultithreaded) { int cnt = 0; TestUtils.RunMultiThreaded(() => { int i; while ((i = Interlocked.Increment(ref cnt) - 1) < 1000) act(i, "val_" + i); }, 8); } else { int start = (int)args[0]; int cnt = (int)args[1]; for (int i = start; i < start + cnt; i++) { if (LoadObjects) act(new Key(i), new Value(i)); else act(i, "val_" + i); } } } public object Load(object key) { ThrowIfNeeded(); Debug.Assert(_grid != null); return Map[key]; } public IEnumerable<KeyValuePair<object, object>> LoadAll(IEnumerable<object> keys) { ThrowIfNeeded(); Debug.Assert(_grid != null); return keys.ToDictionary(key => key, key =>(object)( "val_" + key)); } public void Write(object key, object val) { ThrowIfNeeded(); Debug.Assert(_grid != null); Map[key] = val; } public void WriteAll(IEnumerable<KeyValuePair<object, object>> map) { ThrowIfNeeded(); Debug.Assert(_grid != null); foreach (var e in map) Map[e.Key] = e.Value; } public void Delete(object key) { ThrowIfNeeded(); Debug.Assert(_grid != null); Map.Remove(key); } public void DeleteAll(IEnumerable<object> keys) { ThrowIfNeeded(); Debug.Assert(_grid != null); foreach (object key in keys) Map.Remove(key); } public void SessionEnd(bool commit) { Debug.Assert(_grid != null); Debug.Assert(_ses != null); } public int IntProperty { get { return intProperty; } set { intProperty = value; } } public string StringProperty { get { return stringProperty; } set { stringProperty = value; } } private static void ThrowIfNeeded() { if (ThrowError) throw new CustomStoreException("Exception in cache store"); } [Serializable] public class CustomStoreException : Exception, ISerializable { public string Details { get; private set; } public CustomStoreException(string message) : base(message) { Details = message; } protected CustomStoreException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { Details = info.GetString("details"); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("details", Details); base.GetObjectData(info, context); } } } }
namespace Orleans.CodeGenerator { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.Serialization; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Orleans.CodeGeneration; using Orleans.CodeGenerator.Utilities; using Orleans.Concurrency; using Orleans.Runtime; using Orleans.Serialization; using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory; /// <summary> /// Code generator which generates serializers. /// </summary> public static class SerializerGenerator { private static readonly TypeFormattingOptions GeneratedTypeNameOptions = new TypeFormattingOptions( ClassSuffix, includeGenericParameters: false, includeTypeParameters: false, nestedClassSeparator: '_', includeGlobal: false); /// <summary> /// The suffix appended to the name of generated classes. /// </summary> private const string ClassSuffix = "Serializer"; /// <summary> /// The suffix appended to the name of the generic serializer registration class. /// </summary> private const string RegistererClassSuffix = "Registerer"; /// <summary> /// Generates the class for the provided grain types. /// </summary> /// <param name="type">The grain interface type.</param> /// <param name="onEncounteredType"> /// The callback invoked when a type is encountered. /// </param> /// <returns> /// The generated class. /// </returns> internal static IEnumerable<TypeDeclarationSyntax> GenerateClass(Type type, Action<Type> onEncounteredType) { var typeInfo = type.GetTypeInfo(); var genericTypes = typeInfo.IsGenericTypeDefinition ? typeInfo.GetGenericArguments().Select(_ => SF.TypeParameter(_.ToString())).ToArray() : new TypeParameterSyntax[0]; var attributes = new List<AttributeSyntax> { CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax(), #if !NETSTANDARD SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax()), #endif SF.Attribute(typeof(SerializerAttribute).GetNameSyntax()) .AddArgumentListArguments( SF.AttributeArgument(SF.TypeOfExpression(type.GetTypeSyntax(includeGenericParameters: false)))) }; var className = CodeGeneratorCommon.ClassPrefix + type.GetParseableName(GeneratedTypeNameOptions); var fields = GetFields(type); // Mark each field type for generation foreach (var field in fields) { var fieldType = field.FieldInfo.FieldType; onEncounteredType(fieldType); } var members = new List<MemberDeclarationSyntax>(GenerateStaticFields(fields)) { GenerateDeepCopierMethod(type, fields), GenerateSerializerMethod(type, fields), GenerateDeserializerMethod(type, fields), }; if (typeInfo.IsConstructedGenericType || !typeInfo.IsGenericTypeDefinition) { members.Add(GenerateRegisterMethod(type)); members.Add(GenerateConstructor(className)); attributes.Add(SF.Attribute(typeof(RegisterSerializerAttribute).GetNameSyntax())); } var classDeclaration = SF.ClassDeclaration(className) .AddModifiers(SF.Token(SyntaxKind.InternalKeyword)) .AddAttributeLists(SF.AttributeList().AddAttributes(attributes.ToArray())) .AddMembers(members.ToArray()) .AddConstraintClauses(type.GetTypeConstraintSyntax()); if (genericTypes.Length > 0) { classDeclaration = classDeclaration.AddTypeParameterListParameters(genericTypes); } var classes = new List<TypeDeclarationSyntax> { classDeclaration }; if (typeInfo.IsGenericTypeDefinition) { // Create a generic representation of the serializer type. var serializerType = SF.GenericName(classDeclaration.Identifier) .WithTypeArgumentList( SF.TypeArgumentList() .AddArguments( type.GetGenericArguments() .Select(_ => SF.OmittedTypeArgument()) .Cast<TypeSyntax>() .ToArray())); var registererClassName = className + "_" + string.Join("_", type.GetTypeInfo().GenericTypeParameters.Select(_ => _.Name)) + "_" + RegistererClassSuffix; classes.Add( SF.ClassDeclaration(registererClassName) .AddModifiers(SF.Token(SyntaxKind.InternalKeyword)) .AddAttributeLists( SF.AttributeList() .AddAttributes( CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax(), #if !NETSTANDARD SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax()), #endif SF.Attribute(typeof(RegisterSerializerAttribute).GetNameSyntax()))) .AddMembers( GenerateMasterRegisterMethod(type, serializerType), GenerateConstructor(registererClassName))); } return classes; } /// <summary> /// Returns syntax for the deserializer method. /// </summary> /// <param name="type">The type.</param> /// <param name="fields">The fields.</param> /// <returns>Syntax for the deserializer method.</returns> private static MemberDeclarationSyntax GenerateDeserializerMethod(Type type, List<FieldInfoMember> fields) { Expression<Action> deserializeInner = () => SerializationManager.DeserializeInner(default(Type), default(BinaryTokenStreamReader)); var streamParameter = SF.IdentifierName("stream"); var resultDeclaration = SF.LocalDeclarationStatement( SF.VariableDeclaration(type.GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("result") .WithInitializer(SF.EqualsValueClause(GetObjectCreationExpressionSyntax(type))))); var resultVariable = SF.IdentifierName("result"); var body = new List<StatementSyntax> { resultDeclaration }; // Value types cannot be referenced, only copied, so there is no need to box & record instances of value types. if (!type.IsValueType) { // Record the result for cyclic deserialization. Expression<Action> recordObject = () => DeserializationContext.Current.RecordObject(default(object)); var currentSerializationContext = SyntaxFactory.AliasQualifiedName( SF.IdentifierName(SF.Token(SyntaxKind.GlobalKeyword)), SF.IdentifierName("Orleans")) .Qualify("Serialization") .Qualify("DeserializationContext") .Qualify("Current"); body.Add( SF.ExpressionStatement( recordObject.Invoke(currentSerializationContext) .AddArgumentListArguments(SF.Argument(resultVariable)))); } // Deserialize all fields. foreach (var field in fields) { var deserialized = deserializeInner.Invoke() .AddArgumentListArguments( SF.Argument(SF.TypeOfExpression(field.Type)), SF.Argument(streamParameter)); body.Add( SF.ExpressionStatement( field.GetSetter( resultVariable, SF.CastExpression(field.Type, deserialized)))); } body.Add(SF.ReturnStatement(SF.CastExpression(type.GetTypeSyntax(), resultVariable))); return SF.MethodDeclaration(typeof(object).GetTypeSyntax(), "Deserializer") .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword)) .AddParameterListParameters( SF.Parameter(SF.Identifier("expected")).WithType(typeof(Type).GetTypeSyntax()), SF.Parameter(SF.Identifier("stream")).WithType(typeof(BinaryTokenStreamReader).GetTypeSyntax())) .AddBodyStatements(body.ToArray()) .AddAttributeLists( SF.AttributeList() .AddAttributes(SF.Attribute(typeof(DeserializerMethodAttribute).GetNameSyntax()))); } private static MemberDeclarationSyntax GenerateSerializerMethod(Type type, List<FieldInfoMember> fields) { Expression<Action> serializeInner = () => SerializationManager.SerializeInner(default(object), default(BinaryTokenStreamWriter), default(Type)); var body = new List<StatementSyntax> { SF.LocalDeclarationStatement( SF.VariableDeclaration(type.GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("input") .WithInitializer( SF.EqualsValueClause( SF.CastExpression(type.GetTypeSyntax(), SF.IdentifierName("untypedInput")))))) }; var inputExpression = SF.IdentifierName("input"); // Serialize all members. foreach (var field in fields) { body.Add( SF.ExpressionStatement( serializeInner.Invoke() .AddArgumentListArguments( SF.Argument(field.GetGetter(inputExpression, forceAvoidCopy: true)), SF.Argument(SF.IdentifierName("stream")), SF.Argument(SF.TypeOfExpression(field.FieldInfo.FieldType.GetTypeSyntax()))))); } return SF.MethodDeclaration(typeof(void).GetTypeSyntax(), "Serializer") .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword)) .AddParameterListParameters( SF.Parameter(SF.Identifier("untypedInput")).WithType(typeof(object).GetTypeSyntax()), SF.Parameter(SF.Identifier("stream")).WithType(typeof(BinaryTokenStreamWriter).GetTypeSyntax()), SF.Parameter(SF.Identifier("expected")).WithType(typeof(Type).GetTypeSyntax())) .AddBodyStatements(body.ToArray()) .AddAttributeLists( SF.AttributeList() .AddAttributes(SF.Attribute(typeof(SerializerMethodAttribute).GetNameSyntax()))); } /// <summary> /// Returns syntax for the deep copier method. /// </summary> /// <param name="type">The type.</param> /// <param name="fields">The fields.</param> /// <returns>Syntax for the deep copier method.</returns> private static MemberDeclarationSyntax GenerateDeepCopierMethod(Type type, List<FieldInfoMember> fields) { var originalVariable = SF.IdentifierName("original"); var inputVariable = SF.IdentifierName("input"); var resultVariable = SF.IdentifierName("result"); var body = new List<StatementSyntax>(); if (type.GetCustomAttribute<ImmutableAttribute>() != null) { // Immutable types do not require copying. body.Add(SF.ReturnStatement(originalVariable)); } else { body.Add( SF.LocalDeclarationStatement( SF.VariableDeclaration(type.GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("input") .WithInitializer( SF.EqualsValueClause( SF.ParenthesizedExpression( SF.CastExpression(type.GetTypeSyntax(), originalVariable))))))); body.Add( SF.LocalDeclarationStatement( SF.VariableDeclaration(type.GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("result") .WithInitializer(SF.EqualsValueClause(GetObjectCreationExpressionSyntax(type)))))); // Record this serialization. Expression<Action> recordObject = () => SerializationContext.Current.RecordObject(default(object), default(object)); var currentSerializationContext = SyntaxFactory.AliasQualifiedName( SF.IdentifierName(SF.Token(SyntaxKind.GlobalKeyword)), SF.IdentifierName("Orleans")) .Qualify("Serialization") .Qualify("SerializationContext") .Qualify("Current"); body.Add( SF.ExpressionStatement( recordObject.Invoke(currentSerializationContext) .AddArgumentListArguments(SF.Argument(originalVariable), SF.Argument(resultVariable)))); // Copy all members from the input to the result. foreach (var field in fields) { body.Add(SF.ExpressionStatement(field.GetSetter(resultVariable, field.GetGetter(inputVariable)))); } body.Add(SF.ReturnStatement(resultVariable)); } return SF.MethodDeclaration(typeof(object).GetTypeSyntax(), "DeepCopier") .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword)) .AddParameterListParameters( SF.Parameter(SF.Identifier("original")).WithType(typeof(object).GetTypeSyntax())) .AddBodyStatements(body.ToArray()) .AddAttributeLists( SF.AttributeList().AddAttributes(SF.Attribute(typeof(CopierMethodAttribute).GetNameSyntax()))); } /// <summary> /// Returns syntax for the static fields of the serializer class. /// </summary> /// <param name="fields">The fields.</param> /// <returns>Syntax for the static fields of the serializer class.</returns> private static MemberDeclarationSyntax[] GenerateStaticFields(List<FieldInfoMember> fields) { var result = new List<MemberDeclarationSyntax>(); // ReSharper disable once ReturnValueOfPureMethodIsNotUsed Expression<Action<TypeInfo>> getField = _ => _.GetField(string.Empty, BindingFlags.Default); Expression<Action<Type>> getTypeInfo = _ => _.GetTypeInfo(); Expression<Action> getGetter = () => SerializationManager.GetGetter(default(FieldInfo)); Expression<Action> getReferenceSetter = () => SerializationManager.GetReferenceSetter(default(FieldInfo)); Expression<Action> getValueSetter = () => SerializationManager.GetValueSetter(default(FieldInfo)); // Expressions for specifying binding flags. var bindingFlags = SyntaxFactoryExtensions.GetBindingFlagsParenthesizedExpressionSyntax( SyntaxKind.BitwiseOrExpression, BindingFlags.Instance, BindingFlags.NonPublic, BindingFlags.Public); // Add each field and initialize it. foreach (var field in fields) { var fieldInfo = getField.Invoke(getTypeInfo.Invoke(SF.TypeOfExpression(field.FieldInfo.DeclaringType.GetTypeSyntax()))) .AddArgumentListArguments( SF.Argument(field.FieldInfo.Name.GetLiteralExpression()), SF.Argument(bindingFlags)); var fieldInfoVariable = SF.VariableDeclarator(field.InfoFieldName).WithInitializer(SF.EqualsValueClause(fieldInfo)); var fieldInfoField = SF.IdentifierName(field.InfoFieldName); if (!field.IsGettableProperty || !field.IsSettableProperty) { result.Add( SF.FieldDeclaration( SF.VariableDeclaration(typeof(FieldInfo).GetTypeSyntax()).AddVariables(fieldInfoVariable)) .AddModifiers( SF.Token(SyntaxKind.PrivateKeyword), SF.Token(SyntaxKind.StaticKeyword), SF.Token(SyntaxKind.ReadOnlyKeyword))); } // Declare the getter for this field. if (!field.IsGettableProperty) { var getterType = typeof(Func<,>).MakeGenericType(field.FieldInfo.DeclaringType, field.FieldInfo.FieldType) .GetTypeSyntax(); var fieldGetterVariable = SF.VariableDeclarator(field.GetterFieldName) .WithInitializer( SF.EqualsValueClause( SF.CastExpression( getterType, getGetter.Invoke().AddArgumentListArguments(SF.Argument(fieldInfoField))))); result.Add( SF.FieldDeclaration(SF.VariableDeclaration(getterType).AddVariables(fieldGetterVariable)) .AddModifiers( SF.Token(SyntaxKind.PrivateKeyword), SF.Token(SyntaxKind.StaticKeyword), SF.Token(SyntaxKind.ReadOnlyKeyword))); } if (!field.IsSettableProperty) { if (field.FieldInfo.DeclaringType != null && field.FieldInfo.DeclaringType.IsValueType) { var setterType = typeof(SerializationManager.ValueTypeSetter<,>).MakeGenericType( field.FieldInfo.DeclaringType, field.FieldInfo.FieldType).GetTypeSyntax(); var fieldSetterVariable = SF.VariableDeclarator(field.SetterFieldName) .WithInitializer( SF.EqualsValueClause( SF.CastExpression( setterType, getValueSetter.Invoke() .AddArgumentListArguments(SF.Argument(fieldInfoField))))); result.Add( SF.FieldDeclaration(SF.VariableDeclaration(setterType).AddVariables(fieldSetterVariable)) .AddModifiers( SF.Token(SyntaxKind.PrivateKeyword), SF.Token(SyntaxKind.StaticKeyword), SF.Token(SyntaxKind.ReadOnlyKeyword))); } else { var setterType = typeof(Action<,>).MakeGenericType(field.FieldInfo.DeclaringType, field.FieldInfo.FieldType) .GetTypeSyntax(); var fieldSetterVariable = SF.VariableDeclarator(field.SetterFieldName) .WithInitializer( SF.EqualsValueClause( SF.CastExpression( setterType, getReferenceSetter.Invoke() .AddArgumentListArguments(SF.Argument(fieldInfoField))))); result.Add( SF.FieldDeclaration(SF.VariableDeclaration(setterType).AddVariables(fieldSetterVariable)) .AddModifiers( SF.Token(SyntaxKind.PrivateKeyword), SF.Token(SyntaxKind.StaticKeyword), SF.Token(SyntaxKind.ReadOnlyKeyword))); } } } return result.ToArray(); } /// <summary> /// Returns syntax for initializing a new instance of the provided type. /// </summary> /// <param name="type">The type.</param> /// <returns>Syntax for initializing a new instance of the provided type.</returns> private static ExpressionSyntax GetObjectCreationExpressionSyntax(Type type) { ExpressionSyntax result; var typeInfo = type.GetTypeInfo(); if (typeInfo.IsValueType) { // Use the default value. result = SF.DefaultExpression(typeInfo.GetTypeSyntax()); } else if (type.GetConstructor(Type.EmptyTypes) != null) { // Use the default constructor. result = SF.ObjectCreationExpression(typeInfo.GetTypeSyntax()).AddArgumentListArguments(); } else { // Create an unformatted object. Expression<Func<object>> getUninitializedObject = #if NETSTANDARD () => SerializationManager.GetUninitializedObjectWithFormatterServices(default(Type)); #else () => FormatterServices.GetUninitializedObject(default(Type)); #endif result = SF.CastExpression( type.GetTypeSyntax(), getUninitializedObject.Invoke() .AddArgumentListArguments( SF.Argument(SF.TypeOfExpression(typeInfo.GetTypeSyntax())))); } return result; } /// <summary> /// Returns syntax for the serializer registration method. /// </summary> /// <param name="type">The type.</param> /// <returns>Syntax for the serializer registration method.</returns> private static MemberDeclarationSyntax GenerateRegisterMethod(Type type) { Expression<Action> register = () => SerializationManager.Register( default(Type), default(SerializationManager.DeepCopier), default(SerializationManager.Serializer), default(SerializationManager.Deserializer)); return SF.MethodDeclaration(typeof(void).GetTypeSyntax(), "Register") .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword)) .AddParameterListParameters() .AddBodyStatements( SF.ExpressionStatement( register.Invoke() .AddArgumentListArguments( SF.Argument(SF.TypeOfExpression(type.GetTypeSyntax())), SF.Argument(SF.IdentifierName("DeepCopier")), SF.Argument(SF.IdentifierName("Serializer")), SF.Argument(SF.IdentifierName("Deserializer"))))); } /// <summary> /// Returns syntax for the constructor. /// </summary> /// <param name="className">The name of the class.</param> /// <returns>Syntax for the constructor.</returns> private static ConstructorDeclarationSyntax GenerateConstructor(string className) { return SF.ConstructorDeclaration(className) .AddModifiers(SF.Token(SyntaxKind.StaticKeyword)) .AddParameterListParameters() .AddBodyStatements( SF.ExpressionStatement( SF.InvocationExpression(SF.IdentifierName("Register")).AddArgumentListArguments())); } /// <summary> /// Returns syntax for the generic serializer registration method for the provided type.. /// </summary> /// <param name="type">The type which is supported by this serializer.</param> /// <param name="serializerType">The type of the serializer.</param> /// <returns>Syntax for the generic serializer registration method for the provided type..</returns> private static MemberDeclarationSyntax GenerateMasterRegisterMethod(Type type, TypeSyntax serializerType) { Expression<Action> register = () => SerializationManager.Register(default(Type), default(Type)); return SF.MethodDeclaration(typeof(void).GetTypeSyntax(), "Register") .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword)) .AddParameterListParameters() .AddBodyStatements( SF.ExpressionStatement( register.Invoke() .AddArgumentListArguments( SF.Argument( SF.TypeOfExpression(type.GetTypeSyntax(includeGenericParameters: false))), SF.Argument(SF.TypeOfExpression(serializerType))))); } /// <summary> /// Returns a sorted list of the fields of the provided type. /// </summary> /// <param name="type">The type.</param> /// <returns>A sorted list of the fields of the provided type.</returns> private static List<FieldInfoMember> GetFields(Type type) { var result = type.GetAllFields() .Where(field => field.GetCustomAttribute<NonSerializedAttribute>() == null) .Select((info, i) => new FieldInfoMember { FieldInfo = info, FieldNumber = i }) .ToList(); result.Sort(FieldInfoMember.Comparer.Instance); return result; } /// <summary> /// Represents a field. /// </summary> private class FieldInfoMember { private PropertyInfo property; /// <summary> /// Gets or sets the underlying <see cref="FieldInfo"/> instance. /// </summary> public FieldInfo FieldInfo { get; set; } /// <summary> /// Sets the ordinal assigned to this field. /// </summary> public int FieldNumber { private get; set; } /// <summary> /// Gets the name of the field info field. /// </summary> public string InfoFieldName { get { return "field" + this.FieldNumber; } } /// <summary> /// Gets the name of the getter field. /// </summary> public string GetterFieldName { get { return "getField" + this.FieldNumber; } } /// <summary> /// Gets the name of the setter field. /// </summary> public string SetterFieldName { get { return "setField" + this.FieldNumber; } } /// <summary> /// Gets a value indicating whether or not this field represents a property with an accessible, non-obsolete getter. /// </summary> public bool IsGettableProperty { get { return this.PropertyInfo != null && this.PropertyInfo.GetGetMethod() != null && !this.IsObsolete; } } /// <summary> /// Gets a value indicating whether or not this field represents a property with an accessible, non-obsolete setter. /// </summary> public bool IsSettableProperty { get { return this.PropertyInfo != null && this.PropertyInfo.GetSetMethod() != null && !this.IsObsolete; } } /// <summary> /// Gets syntax representing the type of this field. /// </summary> public TypeSyntax Type { get { return this.FieldInfo.FieldType.GetTypeSyntax(); } } /// <summary> /// Gets the <see cref="PropertyInfo"/> which this field is the backing property for, or /// <see langword="null" /> if this is not the backing field of an auto-property. /// </summary> private PropertyInfo PropertyInfo { get { if (this.property != null) { return this.property; } var propertyName = Regex.Match(this.FieldInfo.Name, "^<([^>]+)>.*$"); if (propertyName.Success && this.FieldInfo.DeclaringType != null) { var name = propertyName.Groups[1].Value; this.property = this.FieldInfo.DeclaringType.GetProperty(name, BindingFlags.Instance | BindingFlags.Public); } return this.property; } } /// <summary> /// Gets a value indicating whether or not this field is obsolete. /// </summary> private bool IsObsolete { get { var obsoleteAttr = this.FieldInfo.GetCustomAttribute<ObsoleteAttribute>(); // Get the attribute from the property, if present. if (this.property != null && obsoleteAttr == null) { obsoleteAttr = this.property.GetCustomAttribute<ObsoleteAttribute>(); } return obsoleteAttr != null; } } /// <summary> /// Returns syntax for retrieving the value of this field, deep copying it if neccessary. /// </summary> /// <param name="instance">The instance of the containing type.</param> /// <param name="forceAvoidCopy">Whether or not to ensure that no copy of the field is made.</param> /// <returns>Syntax for retrieving the value of this field.</returns> public ExpressionSyntax GetGetter(ExpressionSyntax instance, bool forceAvoidCopy = false) { // Retrieve the value of the field. var getValueExpression = this.GetValueExpression(instance); // Avoid deep-copying the field if possible. if (forceAvoidCopy || this.FieldInfo.FieldType.IsOrleansShallowCopyable()) { // Return the value without deep-copying it. return getValueExpression; } // Addressable arguments must be converted to references before passing. // IGrainObserver instances cannot be directly converted to references, therefore they are not included. ExpressionSyntax deepCopyValueExpression; if (typeof(IAddressable).IsAssignableFrom(this.FieldInfo.FieldType) && this.FieldInfo.FieldType.GetTypeInfo().IsInterface && !typeof(IGrainObserver).IsAssignableFrom(this.FieldInfo.FieldType)) { var getAsReference = getValueExpression.Member( (IAddressable grain) => grain.AsReference<IGrain>(), this.FieldInfo.FieldType); // If the value is not a GrainReference, convert it to a strongly-typed GrainReference. // C#: !(value is GrainReference) ? value.AsReference<TInterface>() : value; deepCopyValueExpression = SF.ConditionalExpression( SF.PrefixUnaryExpression( SyntaxKind.LogicalNotExpression, SF.ParenthesizedExpression( SF.BinaryExpression( SyntaxKind.IsExpression, getValueExpression, typeof(GrainReference).GetTypeSyntax()))), SF.InvocationExpression(getAsReference), getValueExpression); } else { deepCopyValueExpression = getValueExpression; } // Deep-copy the value. Expression<Action> deepCopyInner = () => SerializationManager.DeepCopyInner(default(object)); var typeSyntax = this.FieldInfo.FieldType.GetTypeSyntax(); return SF.CastExpression( typeSyntax, deepCopyInner.Invoke().AddArgumentListArguments(SF.Argument(deepCopyValueExpression))); } /// <summary> /// Returns syntax for setting the value of this field. /// </summary> /// <param name="instance">The instance of the containing type.</param> /// <param name="value">Syntax for the new value.</param> /// <returns>Syntax for setting the value of this field.</returns> public ExpressionSyntax GetSetter(ExpressionSyntax instance, ExpressionSyntax value) { // If the field is the backing field for an accessible auto-property use the property directly. if (this.PropertyInfo != null && this.PropertyInfo.GetSetMethod() != null && !this.IsObsolete) { return SF.AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, instance.Member(this.PropertyInfo.Name), value); } var instanceArg = SF.Argument(instance); if (this.FieldInfo.DeclaringType != null && this.FieldInfo.DeclaringType.IsValueType) { instanceArg = instanceArg.WithRefOrOutKeyword(SF.Token(SyntaxKind.RefKeyword)); } return SF.InvocationExpression(SF.IdentifierName(this.SetterFieldName)) .AddArgumentListArguments(instanceArg, SF.Argument(value)); } /// <summary> /// Returns syntax for retrieving the value of this field. /// </summary> /// <param name="instance">The instance of the containing type.</param> /// <returns>Syntax for retrieving the value of this field.</returns> private ExpressionSyntax GetValueExpression(ExpressionSyntax instance) { // If the field is the backing field for an accessible auto-property use the property directly. ExpressionSyntax result; if (this.PropertyInfo != null && this.PropertyInfo.GetGetMethod() != null && !this.IsObsolete) { result = instance.Member(this.PropertyInfo.Name); } else { // Retrieve the field using the generated getter. result = SF.InvocationExpression(SF.IdentifierName(this.GetterFieldName)) .AddArgumentListArguments(SF.Argument(instance)); } return result; } /// <summary> /// A comparer for <see cref="FieldInfoMember"/> which compares by name. /// </summary> public class Comparer : IComparer<FieldInfoMember> { /// <summary> /// The singleton instance. /// </summary> private static readonly Comparer Singleton = new Comparer(); /// <summary> /// Gets the singleton instance of this class. /// </summary> public static Comparer Instance { get { return Singleton; } } public int Compare(FieldInfoMember x, FieldInfoMember y) { return string.Compare(x.FieldInfo.Name, y.FieldInfo.Name, StringComparison.Ordinal); } } } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using IDE.Common; using IDE.Controls; using IDE.Collections; namespace IDE.Forms { /// <summary> /// Summary description for WizardDialog. /// </summary> internal class WizardDialog : System.Windows.Forms.Form { internal enum TitleModes { None, WizardPageTitle, WizardPageSubTitle, WizardPageCaptionTitle, Steps } protected string _cachedTitle; protected TitleModes _titleMode; protected WizardControl wizardControl; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public WizardDialog() { // // Required for Windows Form Designer support // InitializeComponent(); // Initialize properties ResetTitleMode(); // Hook into wizard page collection changes wizardControl.WizardPages.Cleared += new Collections.CollectionClear(OnPagesCleared); wizardControl.WizardPages.Inserted += new Collections.CollectionChange(OnPagesChanged); wizardControl.WizardPages.Removed += new Collections.CollectionChange(OnPagesChanged); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.wizardControl = new IDE.Controls.WizardControl(); this.SuspendLayout(); // // wizardControl // this.wizardControl.Dock = System.Windows.Forms.DockStyle.Fill; this.wizardControl.Location = new System.Drawing.Point(0, 0); this.wizardControl.Name = "wizardControl"; this.wizardControl.SelectedIndex = -1; this.wizardControl.Size = new System.Drawing.Size(416, 289); this.wizardControl.TabIndex = 0; this.wizardControl.WizardCaptionTitleChanged += new System.EventHandler(this.OnWizardCaptionTitleChanged); this.wizardControl.BackClick += new System.ComponentModel.CancelEventHandler(this.OnBackClick); this.wizardControl.SelectionChanged += new System.EventHandler(this.OnSelectionChanged); this.wizardControl.CancelClick += new System.EventHandler(this.OnCancelClick); this.wizardControl.NextClick += new System.ComponentModel.CancelEventHandler(this.OnNextClick); this.wizardControl.HelpClick += new System.EventHandler(this.OnHelpClick); this.wizardControl.CloseClick += new System.EventHandler(this.OnCloseClick); this.wizardControl.UpdateClick += new System.EventHandler(this.OnUpdateClick); this.wizardControl.WizardPageEnter += new IDE.Controls.WizardControl.WizardPageHandler(this.OnWizardPageEnter); this.wizardControl.WizardPageLeave += new IDE.Controls.WizardControl.WizardPageHandler(this.OnWizardPageLeave); this.wizardControl.FinishClick += new System.EventHandler(this.OnFinishClick); // // WizardDialog // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(416, 289); this.Controls.Add(this.wizardControl); this.Name = "WizardDialog"; this.Text = "Wizard Dialog"; this.ResumeLayout(false); } #endregion public new string Text { get { return _cachedTitle; } set { // Store the provided value _cachedTitle = value; // Apply the title mode extra to the end ApplyTitleMode(); } } [Category("Wizard")] [Description("Determine how the title is automatically defined")] [DefaultValue(typeof(TitleModes), "WizardPageCaptionTitle")] public TitleModes TitleMode { get { return _titleMode; } set { if (_titleMode != value) { _titleMode = value; ApplyTitleMode(); } } } public void ResetTitleMode() { TitleMode = TitleModes.WizardPageCaptionTitle; } protected virtual void ApplyTitleMode() { string newTitle = _cachedTitle; // Calculate new title text switch(_titleMode) { case TitleModes.None: // Do nothing! break; case TitleModes.Steps: // Get the current page int selectedPage = wizardControl.SelectedIndex; int totalPages = wizardControl.WizardPages.Count; // Only need separator if some text is already present if (newTitle.Length > 0) newTitle += " - "; // Append the required text newTitle += "Step " + (selectedPage + 1).ToString() + " of " + totalPages.ToString(); break; case TitleModes.WizardPageTitle: // Do we have a valid page currently selected? if (wizardControl.SelectedIndex != -1) { // Get the page WizardPage wp = wizardControl.WizardPages[wizardControl.SelectedIndex]; // Only need separator if some text is already present if (newTitle.Length > 0) newTitle += " - "; // Append page title to the title newTitle += wp.Title; } break; case TitleModes.WizardPageSubTitle: // Do we have a valid page currently selected? if (wizardControl.SelectedIndex != -1) { // Get the page WizardPage wp = wizardControl.WizardPages[wizardControl.SelectedIndex]; // Only need separator if some text is already present if (newTitle.Length > 0) newTitle += " - "; // Append page sub-title to the title newTitle += wp.SubTitle; } break; case TitleModes.WizardPageCaptionTitle: // Do we have a valid page currently selected? if (wizardControl.SelectedIndex != -1) { // Get the page WizardPage wp = wizardControl.WizardPages[wizardControl.SelectedIndex]; // Only need separator if some text is already present if (newTitle.Length > 0) newTitle += " - "; // Append page sub-title to the title newTitle += wp.CaptionTitle; } break; } // Use base class to update actual caption bar base.Text = newTitle; } protected virtual void OnPagesCleared() { // Update the caption bar to reflect change in selection ApplyTitleMode(); } protected virtual void OnPagesChanged(int index, object value) { // Update the caption bar to reflect change in selection ApplyTitleMode(); } protected virtual void OnCloseClick(object sender, EventArgs e) { // By default we close the Form this.DialogResult = DialogResult.OK; this.Close(); } protected virtual void OnFinishClick(object sender, EventArgs e) { // By default we close the Form this.DialogResult = DialogResult.OK; this.Close(); } protected virtual void OnCancelClick(object sender, EventArgs e) { // By default we close the Form this.DialogResult = DialogResult.Cancel; this.Close(); } protected virtual void OnNextClick(object sender, CancelEventArgs e) { // By default we do nothing, let derived class override } protected virtual void OnBackClick(object sender, CancelEventArgs e) { // By default we do nothing, let derived class override } protected virtual void OnUpdateClick(object sender, EventArgs e) { // By default we do nothing, let derived class override } protected virtual void OnHelpClick(object sender, EventArgs e) { // By default we do nothing, let derived class override } protected virtual void OnSelectionChanged(object sender, EventArgs e) { // Update the caption bar to reflect change in selection ApplyTitleMode(); } protected virtual void OnWizardPageEnter(Controls.WizardPage wp, Controls.WizardControl wc) { // By default we do nothing, let derived class override } protected virtual void OnWizardPageLeave(Controls.WizardPage wp, Controls.WizardControl wc) { // By default we do nothing, let derived class override } protected virtual void OnWizardCaptionTitleChanged(object sender, EventArgs e) { // Update the caption bar to reflect change in selection ApplyTitleMode(); } } }
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Storage; using Microsoft.Xna.Framework.Content; using IRTaktiks.Components.Manager; using IRTaktiks.Input; using IRTaktiks.Input.EventArgs; namespace IRTaktiks.Components.Config { /// <summary> /// Representation of the config keyboard. /// </summary> public class Keyboard : Configurable { #region Event /// <summary> /// The delegate of methods that will handle the typed event. /// </summary> /// <param name="letter">The letter pressed on the keyboard.</param> public delegate void TypedEventHandler(string letter); /// <summary> /// Event fired when a letter on the keyboard is typed. /// </summary> public event TypedEventHandler Typed; #endregion #region Properties /// <summary> /// Indicate that the item is configurated. /// </summary> public override bool Configurated { get { return true; } } #endregion #region Constructor /// <summary> /// Constructor of class. /// </summary> /// <param name="game">The instance of game that is running.</param> /// <param name="playerIndex">The index of the player owner of the keyboard.</param> public Keyboard(Game game, PlayerIndex playerIndex) : base(game, playerIndex) { switch (playerIndex) { case PlayerIndex.One: this.PositionField = new Vector2(0, 0); this.TextureField = TextureManager.Instance.Sprites.Config.KeyboardPlayerOne; break; case PlayerIndex.Two: this.PositionField = new Vector2(640, 0); this.TextureField = TextureManager.Instance.Sprites.Config.KeyboardPlayerTwo; break; } InputManager.Instance.CursorDown += new EventHandler<CursorDownArgs>(CursorDown); } #endregion #region Component Methods /// <summary> /// Allows the game component to perform any initialization it needs to before starting /// to run. This is where it can query for any required services and load content. /// </summary> public override void Initialize() { base.Initialize(); } /// <summary> /// Allows the game component to update itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public override void Update(GameTime gameTime) { base.Update(gameTime); } /// <summary> /// Called when the DrawableGameComponent needs to be drawn. Override this method /// with component-specific drawing code. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public override void Draw(GameTime gameTime) { IRTGame game = this.Game as IRTGame; game.SpriteManager.Draw(this.Texture, this.Position, Color.White, 20); base.Draw(gameTime); } #endregion #region Methods /// <summary> /// Unregister all touch events in the keyboard. /// </summary> public override void Unregister() { InputManager.Instance.CursorDown -= CursorDown; } #endregion #region Input Handling /// <summary> /// Input Handling for Cursor Down event. /// </summary> private void CursorDown(object sender, CursorDownArgs e) { // 1st Line if (e.Position.Y > (this.Position.Y + 783) && e.Position.Y < (this.Position.Y + 822)) { if (e.Position.X > (this.Position.X + 27) && e.Position.X < (this.Position.X + 66)) this.Typed("1"); else if (e.Position.X > (this.Position.X + 71) && e.Position.X < (this.Position.X + 110)) this.Typed("2"); else if (e.Position.X > (this.Position.X + 115) && e.Position.X < (this.Position.X + 154)) this.Typed("3"); else if (e.Position.X > (this.Position.X + 159) && e.Position.X < (this.Position.X + 198)) this.Typed("4"); else if (e.Position.X > (this.Position.X + 203) && e.Position.X < (this.Position.X + 242)) this.Typed("5"); else if (e.Position.X > (this.Position.X + 247) && e.Position.X < (this.Position.X + 283)) this.Typed("6"); else if (e.Position.X > (this.Position.X + 291) && e.Position.X < (this.Position.X + 330)) this.Typed("7"); else if (e.Position.X > (this.Position.X + 335) && e.Position.X < (this.Position.X + 374)) this.Typed("8"); else if (e.Position.X > (this.Position.X + 379) && e.Position.X < (this.Position.X + 418)) this.Typed("9"); else if (e.Position.X > (this.Position.X + 423) && e.Position.X < (this.Position.X + 462)) this.Typed("0"); else if (e.Position.X > (this.Position.X + 467) && e.Position.X < (this.Position.X + 594)) this.Typed(null); } // 2nd Line else if (e.Position.Y > (this.Position.Y + 827) && e.Position.Y < (this.Position.Y + 866)) { if (e.Position.X > (this.Position.X + 35) && e.Position.X < (this.Position.X + 74)) this.Typed("Q"); else if (e.Position.X > (this.Position.X + 79) && e.Position.X < (this.Position.X + 118)) this.Typed("W"); else if (e.Position.X > (this.Position.X + 123) && e.Position.X < (this.Position.X + 162)) this.Typed("E"); else if (e.Position.X > (this.Position.X + 167) && e.Position.X < (this.Position.X + 206)) this.Typed("R"); else if (e.Position.X > (this.Position.X + 211) && e.Position.X < (this.Position.X + 250)) this.Typed("T"); else if (e.Position.X > (this.Position.X + 255) && e.Position.X < (this.Position.X + 294)) this.Typed("Y"); else if (e.Position.X > (this.Position.X + 299) && e.Position.X < (this.Position.X + 338)) this.Typed("U"); else if (e.Position.X > (this.Position.X + 343) && e.Position.X < (this.Position.X + 382)) this.Typed("I"); else if (e.Position.X > (this.Position.X + 387) && e.Position.X < (this.Position.X + 426)) this.Typed("O"); else if (e.Position.X > (this.Position.X + 431) && e.Position.X < (this.Position.X + 470)) this.Typed("P"); else if (e.Position.X > (this.Position.X + 475) && e.Position.X < (this.Position.X + 514)) this.Typed("("); else if (e.Position.X > (this.Position.X + 519) && e.Position.X < (this.Position.X + 558)) this.Typed("["); else if (e.Position.X > (this.Position.X + 563) && e.Position.X < (this.Position.X + 602)) this.Typed("{"); } // 3rd Line else if (e.Position.Y > (this.Position.Y + 871) && e.Position.Y < (this.Position.Y + 910)) { if (e.Position.X > (this.Position.X + 46) && e.Position.X < (this.Position.X + 85)) this.Typed("A"); else if (e.Position.X > (this.Position.X + 90) && e.Position.X < (this.Position.X + 129)) this.Typed("S"); else if (e.Position.X > (this.Position.X + 134) && e.Position.X < (this.Position.X + 173)) this.Typed("D"); else if (e.Position.X > (this.Position.X + 178) && e.Position.X < (this.Position.X + 217)) this.Typed("F"); else if (e.Position.X > (this.Position.X + 222) && e.Position.X < (this.Position.X + 261)) this.Typed("G"); else if (e.Position.X > (this.Position.X + 266) && e.Position.X < (this.Position.X + 305)) this.Typed("H"); else if (e.Position.X > (this.Position.X + 310) && e.Position.X < (this.Position.X + 349)) this.Typed("J"); else if (e.Position.X > (this.Position.X + 354) && e.Position.X < (this.Position.X + 393)) this.Typed("K"); else if (e.Position.X > (this.Position.X + 398) && e.Position.X < (this.Position.X + 437)) this.Typed("L"); else if (e.Position.X > (this.Position.X + 442) && e.Position.X < (this.Position.X + 481)) this.Typed("C"); else if (e.Position.X > (this.Position.X + 486) && e.Position.X < (this.Position.X + 525)) this.Typed(")"); else if (e.Position.X > (this.Position.X + 530) && e.Position.X < (this.Position.X + 569)) this.Typed("]"); else if (e.Position.X > (this.Position.X + 574) && e.Position.X < (this.Position.X + 613)) this.Typed("}"); } // 4th Line else if (e.Position.Y > (this.Position.Y + 915) && e.Position.Y < (this.Position.Y + 954)) { if (e.Position.X > (this.Position.X + 27) && e.Position.X < (this.Position.X + 66)) this.Typed("\\"); else if (e.Position.X > (this.Position.X + 71) && e.Position.X < (this.Position.X + 110)) this.Typed("Z"); else if (e.Position.X > (this.Position.X + 115) && e.Position.X < (this.Position.X + 154)) this.Typed("X"); else if (e.Position.X > (this.Position.X + 159) && e.Position.X < (this.Position.X + 198)) this.Typed("C"); else if (e.Position.X > (this.Position.X + 203) && e.Position.X < (this.Position.X + 242)) this.Typed("V"); else if (e.Position.X > (this.Position.X + 247) && e.Position.X < (this.Position.X + 283)) this.Typed("B"); else if (e.Position.X > (this.Position.X + 291) && e.Position.X < (this.Position.X + 330)) this.Typed("N"); else if (e.Position.X > (this.Position.X + 335) && e.Position.X < (this.Position.X + 374)) this.Typed("M"); else if (e.Position.X > (this.Position.X + 379) && e.Position.X < (this.Position.X + 418)) this.Typed("<"); else if (e.Position.X > (this.Position.X + 423) && e.Position.X < (this.Position.X + 462)) this.Typed(">"); else if (e.Position.X > (this.Position.X + 467) && e.Position.X < (this.Position.X + 506)) this.Typed(","); else if (e.Position.X > (this.Position.X + 511) && e.Position.X < (this.Position.X + 550)) this.Typed("."); else if (e.Position.X > (this.Position.X + 555) && e.Position.X < (this.Position.X + 594)) this.Typed("/"); } // 5th Line else if (e.Position.Y > (this.Position.Y + 959) && e.Position.Y < (this.Position.Y + 997)) { if (e.Position.X > (this.Position.X + 115) && e.Position.X < (this.Position.X + 506)) this.Typed(" "); } } #endregion } }
/** * \file NETGeographicLib\ProjectionsPanel.cs * \brief NETGeographicLib projection example * * NETGeographicLib.AzimuthalEquidistant, * NETGeographicLib.CassiniSoldner, and * NETGeographicLib.Gnomonic example. * * NETGeographicLib is copyright (c) Scott Heiman (2013) * GeographicLib is Copyright (c) Charles Karney (2010-2012) * <[email protected]> and licensed under the MIT/X11 License. * For more information, see * https://geographiclib.sourceforge.io/ **********************************************************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using NETGeographicLib; namespace Projections { public partial class ProjectionsPanel : UserControl { enum ProjectionTypes { AzimuthalEquidistant = 0, CassiniSoldner = 1, Gnomonic = 2 } ProjectionTypes m_type; AzimuthalEquidistant m_azimuthal = null; CassiniSoldner m_cassini = null; Gnomonic m_gnomonic = null; Geodesic m_geodesic = null; public ProjectionsPanel() { InitializeComponent(); try { m_geodesic = new Geodesic(); } catch (Exception xcpt) { MessageBox.Show(xcpt.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } m_majorRadiusTextBox.Text = m_geodesic.EquatorialRadius.ToString(); m_flatteningTextBox.Text = m_geodesic.Flattening.ToString(); m_lat0TextBox.Text = m_lon0TextBox.Text = "0"; m_projectionComboBox.SelectedIndex = 0; m_functionComboBox.SelectedIndex = 0; } private void OnProjectectionType(object sender, EventArgs e) { m_type = (ProjectionTypes)m_projectionComboBox.SelectedIndex; switch (m_type) { case ProjectionTypes.AzimuthalEquidistant: m_azimuthal = new AzimuthalEquidistant(m_geodesic); break; case ProjectionTypes.CassiniSoldner: double lat0 = Double.Parse( m_lat0TextBox.Text ); double lon0 = Double.Parse( m_lon0TextBox.Text ); m_cassini = new CassiniSoldner(lat0, lon0, m_geodesic); break; case ProjectionTypes.Gnomonic: m_gnomonic = new Gnomonic(m_geodesic); break; } } private void OnSet(object sender, EventArgs e) { try { double a = Double.Parse(m_majorRadiusTextBox.Text); double f = Double.Parse(m_flatteningTextBox.Text); m_geodesic = new Geodesic(a, f); } catch ( Exception xcpt) { MessageBox.Show(xcpt.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void OnFunction(object sender, EventArgs e) { switch (m_functionComboBox.SelectedIndex) { case 0: m_latitudeTextBox.ReadOnly = m_longitudeTextBox.ReadOnly = false; m_xTextBox.ReadOnly = m_yTextBox.ReadOnly = true; break; case 1: m_latitudeTextBox.ReadOnly = m_longitudeTextBox.ReadOnly = true; m_xTextBox.ReadOnly = m_yTextBox.ReadOnly = false; break; } } private void OnConvert(object sender, EventArgs e) { try { switch (m_type) { case ProjectionTypes.AzimuthalEquidistant: ConvertAzimuthalEquidistant(); break; case ProjectionTypes.CassiniSoldner: ConvertCassiniSoldner(); break; case ProjectionTypes.Gnomonic: ConvertGnomonic(); break; } } catch (Exception xcpt) { MessageBox.Show(xcpt.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void ConvertAzimuthalEquidistant() { double lat0 = Double.Parse(m_lat0TextBox.Text); double lon0 = Double.Parse(m_lon0TextBox.Text); double lat = 0.0, lon = 0.0, x = 0.0, y = 0.0, azi = 0.0, rk = 0.0; switch (m_functionComboBox.SelectedIndex) { case 0: lat = Double.Parse(m_latitudeTextBox.Text); lon = Double.Parse(m_longitudeTextBox.Text); m_azimuthal.Forward(lat0, lon0, lat, lon, out x, out y, out azi, out rk); m_xTextBox.Text = x.ToString(); m_yTextBox.Text = y.ToString(); break; case 1: x = Double.Parse(m_xTextBox.Text); y = Double.Parse(m_yTextBox.Text); m_azimuthal.Reverse(lat0, lon0, x, y, out lat, out lon, out azi, out rk); m_latitudeTextBox.Text = lat.ToString(); m_longitudeTextBox.Text = lon.ToString(); break; } m_azimuthTextBox.Text = azi.ToString(); m_scaleTextBox.Text = rk.ToString(); } private void ConvertCassiniSoldner() { double lat = 0.0, lon = 0.0, x = 0.0, y = 0.0, azi = 0.0, rk = 0.0; switch (m_functionComboBox.SelectedIndex) { case 0: lat = Double.Parse(m_latitudeTextBox.Text); lon = Double.Parse(m_longitudeTextBox.Text); m_cassini.Forward(lat, lon, out x, out y, out azi, out rk); m_xTextBox.Text = x.ToString(); m_yTextBox.Text = y.ToString(); break; case 1: x = Double.Parse(m_xTextBox.Text); y = Double.Parse(m_yTextBox.Text); m_cassini.Reverse(x, y, out lat, out lon, out azi, out rk); m_latitudeTextBox.Text = lat.ToString(); m_longitudeTextBox.Text = lon.ToString(); break; } m_azimuthTextBox.Text = azi.ToString(); m_scaleTextBox.Text = rk.ToString(); } private void ConvertGnomonic() { double lat0 = Double.Parse(m_lat0TextBox.Text); double lon0 = Double.Parse(m_lon0TextBox.Text); double lat = 0.0, lon = 0.0, x = 0.0, y = 0.0, azi = 0.0, rk = 0.0; switch (m_functionComboBox.SelectedIndex) { case 0: lat = Double.Parse(m_latitudeTextBox.Text); lon = Double.Parse(m_longitudeTextBox.Text); m_gnomonic.Forward(lat0, lon0, lat, lon, out x, out y, out azi, out rk); m_xTextBox.Text = x.ToString(); m_yTextBox.Text = y.ToString(); break; case 1: x = Double.Parse(m_xTextBox.Text); y = Double.Parse(m_yTextBox.Text); m_gnomonic.Reverse(lat0, lon0, x, y, out lat, out lon, out azi, out rk); m_latitudeTextBox.Text = lat.ToString(); m_longitudeTextBox.Text = lon.ToString(); break; } m_azimuthTextBox.Text = azi.ToString(); m_scaleTextBox.Text = rk.ToString(); } private void OnValidate(object sender, EventArgs e) { try { double lat = 0.0, lon = 0.0, x = 0.0, y = 0.0, x1 = 0.0, y1 = 0.0, azi = 0.0, rk = 0.0; AzimuthalEquidistant azimuthal = new AzimuthalEquidistant(m_geodesic); azimuthal = new AzimuthalEquidistant(); azimuthal.Forward(32.0, -86.0, 33.0, -87.0, out x, out y, out azi, out rk); azimuthal.Forward(32.0, -86.0, 33.0, -87.0, out x1, out y1); if (x != x1 || y != y1) throw new Exception("Error in AzimuthalEquidistant.Forward"); azimuthal.Reverse(32.0, -86.0, x, y, out lat, out lon, out azi, out rk); azimuthal.Reverse(32.0, -86.0, x, y, out x1, out y1); if ( x1 != lat || y1 != lon ) throw new Exception("Error in AzimuthalEquidistant.Reverse"); CassiniSoldner cassini = new CassiniSoldner(32.0, -86.0, m_geodesic); cassini = new CassiniSoldner(32.0, -86.0); cassini.Reset(31.0, -87.0); cassini.Forward(32.0, -86.0, out x, out y, out azi, out rk); cassini.Forward(32.0, -86.0, out x1, out y1); if (x != x1 || y != y1) throw new Exception("Error in CassiniSoldner.Forward"); cassini.Reverse(x, y, out lat, out lon, out azi, out rk); cassini.Reverse(x, y, out x1, out y1); if (x1 != lat || y1 != lon) throw new Exception("Error in CassiniSoldner.Reverse"); Gnomonic gnomonic = new Gnomonic(m_geodesic); gnomonic = new Gnomonic(); gnomonic.Forward(32.0, -86.0, 31.0, -87.0, out x, out y, out azi, out rk); gnomonic.Forward(32.0, -86.0, 31.0, -87.0, out x1, out y1); if (x != x1 || y != y1) throw new Exception("Error in Gnomonic.Forward"); gnomonic.Reverse(32.0, -86.0, x, y, out lat, out lon, out azi, out rk); gnomonic.Reverse(32.0, -86.0, x, y, out x1, out y1); if (x1 != lat || y1 != lon) throw new Exception("Error in Gnomonic.Reverse"); } catch (Exception xcpt) { MessageBox.Show(xcpt.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } MessageBox.Show("No errors detected", "OK", MessageBoxButtons.OK, MessageBoxIcon.Information); } } }
namespace Cql.Core.Owin.SwaggerDocs { using System; using System.Collections.Generic; using System.Web.Http.Description; using Swashbuckle.Swagger; public class AuthTokenOperation : IDocumentFilter { public bool SupportsClientId { get; set; } = true; public bool SupportsPasswordGrant { get; set; } = true; public bool SupportsRefreshTokenGrant { get; set; } = true; public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { if (this.SupportsPasswordGrant) { this.AddTokenPasswordGrantEndPoint(swaggerDoc, schemaRegistry, apiExplorer); } if (this.SupportsRefreshTokenGrant) { this.AddRefreshTokenEndpoint(swaggerDoc, schemaRegistry, apiExplorer); } this.AddAdditionalAuthTokenEndPoints(swaggerDoc, schemaRegistry, apiExplorer); } protected virtual void AddAdditionalAuthTokenEndPoints(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { } protected virtual void AddClientIdParams(ICollection<Parameter> list) { list.Add( new Parameter { type = "string", name = "client_id", @in = "formData", required = false, @default = "swagger", description = "(Optional) pass client id in form data instead of using basic auth" }); list.Add( new Parameter { type = "password", name = "client_secret", @in = "formData", required = false, description = "(Optional) pass client secret in form data instead of using basic auth" }); } protected virtual void AddRefreshTokenEndpoint(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { swaggerDoc.paths.Add( "/api/token#refresh", new PathItem { post = new Operation { operationId = "RefreshTokenGrant", tags = new List<string> { "Token" }, summary = "Used to retrieve an authorization token using a refresh token grant.", description = "The path should be /api/token -- it's a limitation of swagger that you cannot overload the same path and verb with different parameters.", consumes = FormEncodedContent(), responses = this.GetTokenReponse(), parameters = this.GetRefreshTokenGrantParameters() } }); } protected virtual void AddTokenPasswordGrantEndPoint(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { swaggerDoc.paths.Add( "/api/token", new PathItem { post = new Operation { operationId = "PasswordGrant", tags = new List<string> { "Token" }, summary = "Used to retrieve an authorization token using a username and password grant.", consumes = FormEncodedContent(), responses = this.GetTokenReponse(), parameters = this.GetPasswordGrantParameters() } }); } protected virtual IDictionary<string, Schema> GetDefaultTokenResponseProperties() { var props = new Dictionary<string, Schema>(); this.SetTokenProps(props); this.SetUserProps(props); this.SetAdditionalProps(props); return props; } protected virtual List<Parameter> GetPasswordGrantParameters() { var list = new List<Parameter> { new Parameter { type = "string", name = "grant_type", required = true, @in = "formData", @default = "password", description = "Always \"password\"" }, new Parameter { type = "string", name = "username", required = true, @in = "formData", description = "The UserName (which is also their email)." }, new Parameter { type = "string", name = "password", required = true, @in = "formData", description = "The user's secret password.", format = "password" } }; if (this.SupportsClientId) { this.AddClientIdParams(list); } return list; } protected virtual List<Parameter> GetRefreshTokenGrantParameters() { var list = new List<Parameter> { new Parameter { type = "string", name = "grant_type", required = true, @in = "formData", @default = "refresh_token", description = "Always \"refresh_token\"" }, new Parameter { type = "string", name = "refresh_token", required = true, @in = "formData", description = "The refresh token issued by the password grant step." } }; if (this.SupportsClientId) { this.AddClientIdParams(list); } return list; } protected virtual IDictionary<string, Response> GetTokenReponse() { return new Dictionary<string, Response> { ["200"] = new Response { description = "Login token response", schema = new Schema { properties = this.GetDefaultTokenResponseProperties() } } }; } protected virtual void SetAdditionalProps(IDictionary<string, Schema> props) { } protected virtual void SetTokenProps(IDictionary<string, Schema> props) { props["access_token"] = new Schema { example = "6coMuP3pLcjfQb1UOGIoMYBQ9wZ8_orMWYGwpPNQPzNH1ET8NyOLmzB2PpTI7SEI9fV7DWjOwQbOhvQDVAIfNgMMbrv8CrIOdWePd9Wkzuqhfqq8NIx=", type = "string", description = "The access token to be used in the Authentication header with a value of \"bearer {access_token}\" " + "or access_token query parameter, \"?access_token={access_token}\" for authenticated links." }; props["token_type"] = new Schema { example = "bearer", type = "string", description = "Always \"bearer\"." }; props["expires_in"] = new Schema { example = 1799, type = "number", description = "The number of seconds before the issued access_token expires (about 30 minutes)." }; props["refresh_token"] = new Schema { example = $"{Guid.NewGuid():n}{Guid.NewGuid():n}", type = "string", description = "The refresh token used for renewing the authenticated session when the current token expires." }; } protected virtual void SetUserProps(IDictionary<string, Schema> props) { props["userName"] = new Schema { example = "[email protected]", type = "string", description = "The username." }; props["displayName"] = new Schema { example = "Ima User", type = "string", description = "The preferred display name." }; props["roles"] = new Schema { example = "Admin", type = "string", description = "The list of roles for the user." }; } private static List<string> FormEncodedContent() { return new List<string> { "application/x-www-form-urlencoded" }; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Net.Mail.SmtpClient.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Net.Mail { public partial class SmtpClient : IDisposable { #region Methods and constructors public void Dispose() { } protected virtual new void Dispose(bool disposing) { } protected void OnSendCompleted(System.ComponentModel.AsyncCompletedEventArgs e) { } public void Send(string from, string recipients, string subject, string body) { Contract.Ensures(0 <= body.Length); Contract.Ensures(0 <= subject.Length); } public void Send(MailMessage message) { } public void SendAsync(MailMessage message, Object userToken) { Contract.Ensures(System.ComponentModel.AsyncOperationManager.SynchronizationContext == System.Threading.SynchronizationContext.Current); } public void SendAsync(string from, string recipients, string subject, string body, Object userToken) { Contract.Ensures(0 <= body.Length); Contract.Ensures(0 <= subject.Length); Contract.Ensures(System.ComponentModel.AsyncOperationManager.SynchronizationContext == System.Threading.SynchronizationContext.Current); } public void SendAsyncCancel() { } public SmtpClient(string host, int port) { } public SmtpClient(string host) { } public SmtpClient() { } #endregion #region Properties and indexers public System.Security.Cryptography.X509Certificates.X509CertificateCollection ClientCertificates { get { return default(System.Security.Cryptography.X509Certificates.X509CertificateCollection); } } public System.Net.ICredentialsByHost Credentials { get { return default(System.Net.ICredentialsByHost); } set { } } public SmtpDeliveryMethod DeliveryMethod { get { return default(SmtpDeliveryMethod); } set { } } public bool EnableSsl { get { return default(bool); } set { } } public string Host { get { return default(string); } set { } } public string PickupDirectoryLocation { get { return default(string); } set { } } public int Port { get { return default(int); } set { } } public System.Net.ServicePoint ServicePoint { get { Contract.Ensures(Contract.Result<System.Net.ServicePoint>() != null); return default(System.Net.ServicePoint); } } public string TargetName { get { return default(string); } set { } } public int Timeout { get { return default(int); } set { } } public bool UseDefaultCredentials { get { return default(bool); } set { } } #endregion #region Events public event SendCompletedEventHandler SendCompleted { add { } remove { } } #endregion } }
/**************************************************************************** Copyright (c) 2010 cocos2d-x.org Copyright (c) 2011-2012 openxlive.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ using System.Collections.Generic; using Microsoft.Xna.Framework.Graphics; using System.Globalization; using System; #if !WINDOWS_PHONE && !WINDOWS &&!NETFX_CORE #if MACOS using MonoMac.OpenGL; #elif WINDOWSGL || LINUX using OpenTK.Graphics.OpenGL; #else using OpenTK.Graphics.ES20; using BeginMode = OpenTK.Graphics.ES20.All; using EnableCap = OpenTK.Graphics.ES20.All; using TextureTarget = OpenTK.Graphics.ES20.All; using BufferTarget = OpenTK.Graphics.ES20.All; using BufferUsageHint = OpenTK.Graphics.ES20.All; using DrawElementsType = OpenTK.Graphics.ES20.All; using GetPName = OpenTK.Graphics.ES20.All; using FramebufferErrorCode = OpenTK.Graphics.ES20.All; using FramebufferTarget = OpenTK.Graphics.ES20.All; using FramebufferAttachment = OpenTK.Graphics.ES20.All; using RenderbufferTarget = OpenTK.Graphics.ES20.All; using RenderbufferStorage = OpenTK.Graphics.ES20.All; #endif #endif namespace CocosSharp { internal class CCUtils { #if !WINDOWS_PHONE #if OPENGL static List<string> GLExtensions = null; public static List<string> GetGLExtensions() { // Setup extensions. if(GLExtensions == null) { List<string> extensions = new List<string>(); #if GLES var extstring = GL.GetString(RenderbufferStorage.Extensions); CheckGLError(); #elif MACOS // for right now there are errors with GL before we even get here so the // CheckGLError for MACOS is throwing errors even though the extensions are read // correctly. Placed this here for now so that we can continue the processing // until we find the real error. var extstring = GL.GetString(StringName.Extensions); #else var extstring = GL.GetString(StringName.Extensions); CheckGLError(); #endif if (!string.IsNullOrEmpty(extstring)) { extensions.AddRange(extstring.Split(' ')); CCLog.Log("Supported GL extensions:"); foreach (string extension in extensions) CCLog.Log(extension); } GLExtensions = extensions; } return GLExtensions; } public static void CheckGLError() { #if GLES && !ANGLE All error = GL.GetError(); if (error != All.False) throw new Exception("GL.GetError() returned " + error.ToString()); #elif OPENGL ErrorCode error = GL.GetError(); if (error != ErrorCode.NoError) throw new Exception("GL.GetError() returned " + error.ToString()); #endif } #endif #endif /// <summary> /// Returns the Cardinal Spline position for a given set of control points, tension and time /// </summary> /// <param name="p0"></param> /// <param name="p1"></param> /// <param name="p2"></param> /// <param name="p3"></param> /// <param name="tension"></param> /// <param name="t"></param> /// <returns></returns> public static CCPoint CCCardinalSplineAt(CCPoint p0, CCPoint p1, CCPoint p2, CCPoint p3, float tension, float t) { float t2 = t * t; float t3 = t2 * t; /* * Formula: s(-ttt + 2tt - t)P1 + s(-ttt + tt)P2 + (2ttt - 3tt + 1)P2 + s(ttt - 2tt + t)P3 + (-2ttt + 3tt)P3 + s(ttt - tt)P4 */ float s = (1 - tension) / 2; float b1 = s * ((-t3 + (2 * t2)) - t); // s(-t3 + 2 t2 - t)P1 float b2 = s * (-t3 + t2) + (2 * t3 - 3 * t2 + 1); // s(-t3 + t2)P2 + (2 t3 - 3 t2 + 1)P2 float b3 = s * (t3 - 2 * t2 + t) + (-2 * t3 + 3 * t2); // s(t3 - 2 t2 + t)P3 + (-2 t3 + 3 t2)P3 float b4 = s * (t3 - t2); // s(t3 - t2)P4 float x = (p0.X * b1 + p1.X * b2 + p2.X * b3 + p3.X * b4); float y = (p0.Y * b1 + p1.Y * b2 + p2.Y * b3 + p3.Y * b4); return new CCPoint(x, y); } /// <summary> /// Parses an int value using the default number style and the invariant culture parser. /// </summary> /// <param name="toParse">The value to parse</param> /// <returns>The int value of the string</returns> public static int CCParseInt(string toParse) { // http://www.cocos2d-x.org/boards/17/topics/11690 // Issue #17 // https://github.com/cocos2d/cocos2d-x-for-xna/issues/17 return int.Parse(toParse, CultureInfo.InvariantCulture); } /// <summary> /// Parses aint value for the given string using the given number style and using /// the invariant culture parser. /// </summary> /// <param name="toParse">The value to parse.</param> /// <param name="ns">The number style used to parse the int value.</param> /// <returns>The int value of the string.</returns> public static int CCParseInt(string toParse, NumberStyles ns) { // http://www.cocos2d-x.org/boards/17/topics/11690 // Issue #17 // https://github.com/cocos2d/cocos2d-x-for-xna/issues/17 return int.Parse(toParse, ns, CultureInfo.InvariantCulture); } /// <summary> /// Parses a float value using the default number style and the invariant culture parser. /// </summary> /// <param name="toParse">The value to parse</param> /// <returns>The float value of the string.</returns> public static float CCParseFloat(string toParse) { // http://www.cocos2d-x.org/boards/17/topics/11690 // Issue #17 // https://github.com/cocos2d/cocos2d-x-for-xna/issues/17 return float.Parse(toParse, CultureInfo.InvariantCulture); } /// <summary> /// Parses a float value for the given string using the given number style and using /// the invariant culture parser. /// </summary> /// <param name="toParse">The value to parse.</param> /// <param name="ns">The number style used to parse the float value.</param> /// <returns>The float value of the string.</returns> public static float CCParseFloat(string toParse, NumberStyles ns) { // http://www.cocos2d-x.org/boards/17/topics/11690 // https://github.com/cocos2d/cocos2d-x-for-xna/issues/17 return float.Parse(toParse, ns, CultureInfo.InvariantCulture); } /// <summary> /// Returns the next Power of Two for the given value. If x = 3, then this returns 4. /// If x = 4 then 4 is returned. If the value is a power of two, then the same value /// is returned. /// </summary> /// <param name="x">The base of the POT test</param> /// <returns>The next power of 2 (1, 2, 4, 8, 16, 32, 64, 128, etc)</returns> public static long CCNextPOT(long x) { x = x - 1; x = x | (x >> 1); x = x | (x >> 2); x = x | (x >> 4); x = x | (x >> 8); x = x | (x >> 16); return x + 1; } /// <summary> /// Returns the next Power of Two for the given value. If x = 3, then this returns 4. /// If x = 4 then 4 is returned. If the value is a power of two, then the same value /// is returned. /// </summary> /// <param name="x">The base of the POT test</param> /// <returns>The next power of 2 (1, 2, 4, 8, 16, 32, 64, 128, etc)</returns> public static int CCNextPOT(int x) { x = x - 1; x = x | (x >> 1); x = x | (x >> 2); x = x | (x >> 4); x = x | (x >> 8); x = x | (x >> 16); return x + 1; } public static void Split(string src, string token, List<string> vect) { int nend = 0; int nbegin = 0; while (nend != -1) { nend = src.IndexOf(token, nbegin); if (nend == -1) vect.Add(src.Substring(nbegin, src.Length - nbegin)); else vect.Add(src.Substring(nbegin, nend - nbegin)); nbegin = nend + token.Length; } } // first, judge whether the form of the string like this: {x,y} // if the form is right,the string will be splited into the parameter strs; // or the parameter strs will be empty. // if the form is right return true,else return false. public static bool SplitWithForm(string pStr, List<string> strs) { bool bRet = false; do { if (pStr == null) { break; } // string is empty string content = pStr; if (content.Length == 0) { break; } int nPosLeft = content.IndexOf('{'); int nPosRight = content.IndexOf('}'); // don't have '{' and '}' if (nPosLeft == -1 || nPosRight == -1) { break; } // '}' is before '{' if (nPosLeft > nPosRight) { break; } string pointStr = content.Substring(nPosLeft + 1, nPosRight - nPosLeft - 1); // nothing between '{' and '}' if (pointStr.Length == 0) { break; } int nPos1 = pointStr.IndexOf('{'); int nPos2 = pointStr.IndexOf('}'); // contain '{' or '}' if (nPos1 != -1 || nPos2 != -1) break; Split(pointStr, ",", strs); if (strs.Count != 2 || strs[0].Length == 0 || strs[1].Length == 0) { strs.Clear(); break; } bRet = true; } while (false); return bRet; } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Novell.Directory.Ldap.MessageAgent.cs // // Author: // Sunil Kumar ([email protected]) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using System.Diagnostics; using System.Threading; using Novell.Directory.LDAP.VQ.Utilclass; namespace Novell.Directory.LDAP.VQ { /* package */ class MessageAgent { private void InitBlock() { messages = new MessageVector(5, 5); } /// <summary> empty and return all messages owned by this agent /// /// /// </summary> virtual internal object[] MessageArray { /* package */ get { return messages.ObjectArray; } } /// <summary> Get a list of message ids controlled by this agent /// /// </summary> /// <returns> an array of integers representing the message ids /// </returns> virtual internal int[] MessageIDs { /* package */ get { int size = messages.Count; int[] ids = new int[size]; Message info; for (int i = 0; i < size; i++) { info = (Message)messages[i]; ids[i] = info.MessageID; } return ids; } } /// <summary> Get the maessage agent number for debugging /// /// </summary> /// <returns> the agent number /// </returns> virtual internal string AgentName { /*packge*/ get { return name; } } /// <summary> Get a count of all messages queued</summary> virtual internal int Count { /* package */ get { int count = 0; object[] msgs = messages.ToArray(); for (int i = 0; i < msgs.Length; i++) { Message m = (Message)msgs[i]; count += m.Count; } return count; } } private MessageVector messages; private int indexLastRead = 0; private static object nameLock; // protect agentNum private static int agentNum = 0; // Debug, agent number private string name; // string name for debug /* package */ internal MessageAgent() { InitBlock(); // Get a unique agent id for debug } /// <summary> merges two message agents /// /// </summary> /// <param name="fromAgent">the agent to be merged into this one /// </param> /* package */ internal void merge(MessageAgent fromAgent) { object[] msgs = fromAgent.MessageArray; for (int i = 0; i < msgs.Length; i++) { messages.Add(msgs[i]); ((Message)(msgs[i])).Agent = this; } lock (messages) { if (msgs.Length > 1) { Monitor.PulseAll(messages); // wake all threads waiting for messages } else if (msgs.Length == 1) { Monitor.Pulse(messages); // only wake one thread } } } /// <summary> Wakes up any threads waiting for messages in the message agent /// /// </summary> /* package */ internal void sleepersAwake(bool all) { lock (messages) { if (all) Monitor.PulseAll(messages); else Monitor.Pulse(messages); } } /// <summary> Returns true if any responses are queued for any of the agent's messages /// /// return false if no responses are queued, otherwise true /// </summary> /* package */ internal bool isResponseReceived() { int size = messages.Count; int next = indexLastRead + 1; Message info; for (int i = 0; i < size; i++) { if (next == size) { next = 0; } info = (Message)messages[next]; if (info.hasReplies()) { return true; } } return false; } /// <summary> Returns true if any responses are queued for the specified msgId /// /// return false if no responses are queued, otherwise true /// </summary> /* package */ internal bool isResponseReceived(int msgId) { try { Message info = messages.findMessageById(msgId); return info.hasReplies(); } catch (FieldAccessException ex) { return false; } } /// <summary> Abandon the request associated with MsgId /// /// </summary> /// <param name="msgId">the message id to abandon /// /// </param> /// <param name="cons">constraints associated with this request /// </param> /* package */ internal void Abandon(int msgId, LdapConstraints cons) //, boolean informUser) { Message info = null; try { // Send abandon request and remove from connection list info = messages.findMessageById(msgId); SupportClass.VectorRemoveElement(messages, info); // This message is now dead info.Abandon(cons, null); } catch (FieldAccessException ex) { } } /// <summary> Abandon all requests on this MessageAgent</summary> /* package */ internal void AbandonAll() { int size = messages.Count; Message info; for (int i = 0; i < size; i++) { info = (Message)messages[i]; // Message complete and no more replies, remove from id list SupportClass.VectorRemoveElement(messages, info); info.Abandon(null, null); } } /// <summary> Indicates whether a specific operation is complete /// /// </summary> /// <returns> true if a specific operation is complete /// </returns> /* package */ internal bool isComplete(int msgid) { try { Message info = messages.findMessageById(msgid); if (!info.Complete) { return false; } } catch (FieldAccessException ex) { // return true, if no message, it must be complete } return true; } /// <summary> Returns the Message object for a given messageID /// /// </summary> /// <param name="msgid">the message ID. /// </param> /* package */ internal Message getMessage(int msgid) { return messages.findMessageById(msgid); } /// <summary> Send a request to the server. A Message class is created /// for the specified request which causes the message to be sent. /// The request is added to the list of messages being managed by /// this agent. /// /// </summary> /// <param name="conn">the connection that identifies the server. /// /// </param> /// <param name="msg">the LdapMessage to send /// /// </param> /// <param name="timeOut">the interval to wait for the message to complete or /// <code>null</code> if infinite. /// </param> /// <param name="queue">the LdapMessageQueue associated with this request. /// </param> /* package */ internal void sendMessage(Connection conn, LdapMessage msg, int timeOut, LdapMessageQueue queue, BindProperties bindProps) { // creating a messageInfo causes the message to be sent // and a timer to be started if needed. Message message = new Message(msg, timeOut, conn, this, queue, bindProps); messages.Add(message); message.sendMessage(); // Now send message to server } /// <summary> Returns a response queued, or waits if none queued /// /// </summary> /* package */ // internal object getLdapMessage(System.Int32 msgId) internal object getLdapMessage(int msgId) { return (getLdapMessage(new Integer32(msgId))); } internal object getLdapMessage(Integer32 msgId) { object rfcMsg; // If no messages for this agent, just return null if (messages.Count == 0) { return null; } if (msgId != null) { // Request messages for a specific ID try { // Get message for this ID // Message info = messages.findMessageById(msgId); Message info = messages.findMessageById(msgId.intValue); rfcMsg = info.waitForReply(); // blocks for a response if (!info.acceptsReplies() && !info.hasReplies()) { // Message complete and no more replies, remove from id list SupportClass.VectorRemoveElement(messages, info); info.Abandon(null, null); // Get rid of resources } return rfcMsg; } catch (FieldAccessException ex) { // no such message id return null; } } // A msgId was NOT specified, any message will do lock (messages) { while (true) { int next = indexLastRead + 1; Message info; for (int i = 0; i < messages.Count; i++) { if (next >= messages.Count) { next = 0; } info = (Message)messages[next]; indexLastRead = next++; rfcMsg = info.Reply; // Check this request is complete if (!info.acceptsReplies() && !info.hasReplies()) { // Message complete & no more replies, remove from id list SupportClass.VectorRemoveElement(messages, info); // remove from list info.Abandon(null, null); // Get rid of resources // Start loop at next message that is now moved // to the current position in the Vector. i -= 1; } if (rfcMsg != null) { // We got a reply return rfcMsg; } } // end for loop */ // Messages can be removed in this loop, we we must // check if any messages left for this agent if (messages.Count == 0) { return null; } // No data, wait for something to come in. try { Monitor.Wait(messages); } catch (Exception ex) { Debug.WriteLine(ex.Message); } } /* end while */ } /* end synchronized */ } /// <summary> Debug code to print messages in message vector</summary> private void debugDisplayMessages() { } static MessageAgent() { nameLock = new object(); } } }
using System; using OTFontFile; using OTFontFile.OTL; namespace OTFontFileVal { /// <summary> /// Summary description for val_BASE. /// </summary> public class val_BASE : Table_BASE, ITableValidate { /************************ * constructors */ public val_BASE(OTTag tag, MBOBuffer buf) : base(tag, buf) { m_DataOverlapDetector = new DataOverlapDetector(); } /************************ * public methods */ public bool Validate(Validator v, OTFontVal fontOwner) { bool bRet = true; if (v.PerformTest(T.BASE_Version)) { if (Version.GetUint() == 0x00010000) { v.Pass(T.BASE_Version, P.BASE_P_Version, m_tag); } else { v.Error(T.BASE_Version, E.BASE_E_Version, m_tag, "0x"+Version.GetUint().ToString("x8")); bRet = false; } } if (v.PerformTest(T.BASE_HeaderOffsets)) { if (HorizAxisOffset == 0) { v.Pass(T.BASE_HeaderOffsets, P.BASE_P_HorizAxisOffset_null, m_tag); } else if (HorizAxisOffset < GetLength()) { v.Pass(T.BASE_HeaderOffsets, P.BASE_P_HorizAxisOffset_valid, m_tag); } else { v.Error(T.BASE_HeaderOffsets, E.BASE_E_HorizAxisOffset_OutsideTable, m_tag); bRet = false; } if (VertAxisOffset == 0) { v.Pass(T.BASE_HeaderOffsets, P.BASE_P_VertAxisOffset_null, m_tag); } else if (VertAxisOffset < GetLength()) { v.Pass(T.BASE_HeaderOffsets, P.BASE_P_VertAxisOffset_valid, m_tag); } else { v.Error(T.BASE_HeaderOffsets, E.BASE_E_VertAxisOffset_OutsideTable, m_tag); bRet = false; } } if (v.PerformTest(T.BASE_HorizAxisTable)) { AxisTable_val at = GetHorizAxisTable_val(); if (at != null) { at.Validate(v, "H Axis", this); } } if (v.PerformTest(T.BASE_VertAxisTable)) { AxisTable_val at = GetVertAxisTable_val(); if (at != null) { at.Validate(v, "V Axis", this); } } return bRet; } /************************ * classes */ public class AxisTable_val : AxisTable, I_OTLValidate { public AxisTable_val(ushort offset, MBOBuffer bufTable) : base(offset, bufTable) { } public bool Validate(Validator v, string sIdentity, OTTable table) { bool bRet = true; bRet &= ((val_BASE)table).ValidateNoOverlap(m_offsetAxisTable, CalcLength(), v, sIdentity, table.GetTag()); if (BaseTagListOffset == 0) { v.Pass(T.T_NULL, P.BASE_P_AxisTable_BaseTagListOffset_null, table.m_tag, sIdentity); } else if (BaseTagListOffset + m_offsetAxisTable > m_bufTable.GetLength()) { v.Error(T.T_NULL, E.BASE_E_AxisTable_BaseTagListOffset, table.m_tag, sIdentity); bRet = false; } else { v.Pass(T.T_NULL, P.BASE_P_AxisTable_BaseTagListOffset_valid, table.m_tag, sIdentity); BaseTagListTable_val btlt = GetBaseTagListTable_val(); btlt.Validate(v, sIdentity, table); } if (BaseScriptListOffset == 0) { v.Error(T.T_NULL, E.BASE_E_AxisTable_BaseScriptListOffset_null, table.m_tag, sIdentity); bRet = false; } else if (BaseScriptListOffset + m_offsetAxisTable > m_bufTable.GetLength()) { v.Error(T.T_NULL, E.BASE_E_AxisTable_BaseScriptListOffset, table.m_tag, sIdentity); bRet = false; } else { v.Pass(T.T_NULL, P.BASE_P_AxisTable_BaseScriptListOffset_valid, table.m_tag, sIdentity); BaseScriptListTable_val bslt = GetBaseScriptListTable_val(); bslt.Validate(v, sIdentity, table); } return bRet; } public BaseTagListTable_val GetBaseTagListTable_val() { BaseTagListTable_val btlt = null; if (BaseTagListOffset != 0) { ushort offset = (ushort)(m_offsetAxisTable + BaseTagListOffset); btlt = new BaseTagListTable_val(offset, m_bufTable); } return btlt; } public BaseScriptListTable_val GetBaseScriptListTable_val() { BaseScriptListTable_val bslt = null; if (BaseScriptListOffset != 0) { ushort offset = (ushort)(m_offsetAxisTable + BaseScriptListOffset); bslt = new BaseScriptListTable_val(offset, m_bufTable); } return bslt; } } public class BaseTagListTable_val : BaseTagListTable, I_OTLValidate { public BaseTagListTable_val(ushort offset, MBOBuffer bufTable) : base(offset, bufTable) { } public bool Validate(Validator v, string sIdentity, OTTable table) { bool bRet = true; bRet &= ((val_BASE)table).ValidateNoOverlap(m_offsetBaseTagListTable, CalcLength(), v, sIdentity, table.GetTag()); bool bTagsValid = true; for (uint i=0; i<BaseTagCount; i++) { OTTag BaselineTag = GetBaselineTag(i); if (!BaselineTag.IsValid()) { v.Error(T.T_NULL, E.BASE_E_BaseTagList_TagValid, table.m_tag, sIdentity + ", tag = 0x" + ((uint)BaselineTag).ToString("x8")); bTagsValid = false; bRet = false; } } if (bTagsValid) { v.Pass(T.T_NULL, P.BASE_P_BaseTagList_TagValid, table.m_tag, sIdentity); } bool bOrderOk = true; if (BaseTagCount > 1) { for (uint i=0; i<BaseTagCount-1; i++) { OTTag ThisTag = GetBaselineTag(i); OTTag NextTag = GetBaselineTag(i+1); if (ThisTag >= NextTag) { v.Error(T.T_NULL, E.BASE_E_BaseTagList_TagOrder, table.m_tag, sIdentity); bOrderOk = false; bRet = false; break; } } } if (bOrderOk) { v.Pass(T.T_NULL, P.BASE_P_BaseTagList_TagOrder, table.m_tag, sIdentity); } return bRet; } } public class BaseScriptListTable_val : BaseScriptListTable, I_OTLValidate { public BaseScriptListTable_val(ushort offset, MBOBuffer bufTable) : base(offset, bufTable) { } public bool Validate(Validator v, string sIdentity, OTTable table) { bool bRet = true; bRet &= ((val_BASE)table).ValidateNoOverlap(m_offsetBaseScriptListTable, CalcLength(), v, sIdentity, table.GetTag()); bool bOrderOk = true; if (BaseScriptCount > 1) { for (uint i=0; i<BaseScriptCount-1; i++) { BaseScriptRecord ThisBsr = GetBaseScriptRecord(i); BaseScriptRecord NextBsr = GetBaseScriptRecord(i+1); if (ThisBsr.BaseScriptTag >= NextBsr.BaseScriptTag) { v.Error(T.T_NULL, E.BASE_E_BaseScriptList_Order, table.m_tag, sIdentity); bOrderOk = false; bRet = false; break; } } } if (bOrderOk) { v.Pass(T.T_NULL, P.BASE_P_BaseScriptList_Order, table.m_tag, sIdentity); } bool bOffsetsOk = true; for (uint i=0; i<BaseScriptCount; i++) { BaseScriptRecord bsr = GetBaseScriptRecord(i); if (bsr.BaseScriptOffset + m_offsetBaseScriptListTable > m_bufTable.GetLength()) { v.Error(T.T_NULL, E.BASE_E_BaseScriptList_Offset, table.m_tag, sIdentity + ", index = "+i); bOffsetsOk = false; bRet = false; } } if (bOffsetsOk) { v.Pass(T.T_NULL, P.BASE_P_BaseScriptList_Offset, table.m_tag, sIdentity); } for (uint i=0; i<BaseScriptCount; i++) { BaseScriptRecord bsr = GetBaseScriptRecord(i); BaseScriptTable_val bst = GetBaseScriptTable_val(bsr); bst.Validate(v, sIdentity + ", BaseScriptRecord[" + i + "](" + bsr.BaseScriptTag + ")", table); } return bRet; } public BaseScriptTable_val GetBaseScriptTable_val(BaseScriptRecord bsr) { BaseScriptTable_val bst = null; if (bsr != null) { ushort offset = (ushort)(m_offsetBaseScriptListTable + bsr.BaseScriptOffset); bst = new BaseScriptTable_val(offset, m_bufTable); } return bst; } } public class BaseScriptTable_val : BaseScriptTable, I_OTLValidate { public BaseScriptTable_val(ushort offset, MBOBuffer bufTable) : base(offset, bufTable) { } public bool Validate(Validator v, string sIdentity, OTTable table) { bool bRet = true; bRet &= ((val_BASE)table).ValidateNoOverlap(m_offsetBaseScriptTable, CalcLength(), v, sIdentity, table.GetTag()); // check the BaseValuesOffset if (BaseValuesOffset == 0) { v.Pass(T.T_NULL, P.BASE_P_BaseValuesOffset_null, table.m_tag, sIdentity); } else if (BaseValuesOffset + m_offsetBaseScriptTable > m_bufTable.GetLength()) { v.Error(T.T_NULL, E.BASE_E_BaseValuesOffset, table.m_tag, sIdentity); } else { v.Pass(T.T_NULL, P.BASE_P_BaseValuesOffset, table.m_tag, sIdentity); } // check the DefaultMinMaxOffset if (DefaultMinMaxOffset == 0) { v.Pass(T.T_NULL, P.BASE_P_DefaultMinMaxOffset_null, table.m_tag, sIdentity); } else if (DefaultMinMaxOffset + m_offsetBaseScriptTable > m_bufTable.GetLength()) { v.Error(T.T_NULL, E.BASE_E_DefaultMinMaxOffset, table.m_tag, sIdentity); } else { v.Pass(T.T_NULL, P.BASE_P_DefaultMinMaxOffset, table.m_tag, sIdentity); } // check the BaseLangSysRecord order bool bOrderOk = true; if (BaseLangSysCount > 1) { for (uint i=0; i<BaseLangSysCount-1; i++) { BaseLangSysRecord ThisBlsr = GetBaseLangSysRecord(i); BaseLangSysRecord NextBlsr = GetBaseLangSysRecord(i+1); if (ThisBlsr.BaseLangSysTag >= NextBlsr.BaseLangSysTag) { v.Error(T.T_NULL, E.BASE_E_BaseLangSysRecord_order, table.m_tag, sIdentity); bOrderOk = false; bRet = false; } } } if (bOrderOk) { v.Pass(T.T_NULL, P.BASE_P_BaseLangSysRecord_order, table.m_tag, sIdentity); } // check the BaseLangSysRecord MinMaxOffsets bool bOffsetsOk = true; for (uint i=0; i<BaseLangSysCount; i++) { BaseLangSysRecord bslr = GetBaseLangSysRecord(i); if (bslr.MinMaxOffset == 0) { v.Error(T.T_NULL, E.BASE_E_BaseLangSysRecord_offset0, table.m_tag, sIdentity + ", BaseLangSysRecord index = "+i); bOffsetsOk = false; bRet = false; } else if (bslr.MinMaxOffset + m_offsetBaseScriptTable > m_bufTable.GetLength()) { v.Error(T.T_NULL, E.BASE_E_BaseLangSysRecord_offset, table.m_tag, sIdentity + ", BaseLangSysRecord index = "+i); bOffsetsOk = false; bRet = false; } } if (bOffsetsOk) { v.Pass(T.T_NULL, P.BASE_P_BaseLangSysRecord_offsets, table.m_tag, sIdentity); } // check the BaseValuesTable if (BaseValuesOffset != 0) { BaseValuesTable_val bvt = GetBaseValuesTable_val(); bvt.Validate(v, sIdentity, table); } // check the Default MinMaxTable if (DefaultMinMaxOffset != 0) { MinMaxTable_val mmt = GetDefaultMinMaxTable_val(); mmt.Validate(v, sIdentity + ", default MinMax", table); } // check the BaseLangSysRecord MinMaxTables for (uint i=0; i<BaseLangSysCount; i++) { BaseLangSysRecord blsr = GetBaseLangSysRecord(i); MinMaxTable_val mmt = GetMinMaxTable_val(blsr); mmt.Validate(v, sIdentity + ", BaseLangSysRecord[" + i + "]", table); } return bRet; } public BaseValuesTable_val GetBaseValuesTable_val() { BaseValuesTable_val bvt = null; if (BaseValuesOffset != 0) { bvt = new BaseValuesTable_val((ushort)(m_offsetBaseScriptTable + BaseValuesOffset), m_bufTable); } return bvt; } public MinMaxTable_val GetDefaultMinMaxTable_val() { MinMaxTable_val mmt = null; if (DefaultMinMaxOffset != 0) { mmt = new MinMaxTable_val((ushort)(m_offsetBaseScriptTable + DefaultMinMaxOffset), m_bufTable); } return mmt; } public MinMaxTable_val GetMinMaxTable_val(BaseLangSysRecord blsr) { MinMaxTable_val mmt = null; if (blsr != null) { ushort offset = (ushort)(m_offsetBaseScriptTable + blsr.MinMaxOffset); mmt = new MinMaxTable_val(offset, m_bufTable); } return mmt; } } public class BaseValuesTable_val : BaseValuesTable, I_OTLValidate { public BaseValuesTable_val(ushort offset, MBOBuffer bufTable) : base(offset, bufTable) { } public bool Validate(Validator v, string sIdentity, OTTable table) { bool bRet = true; bRet &= ((val_BASE)table).ValidateNoOverlap(m_offsetBaseValuesTable, CalcLength(), v, sIdentity, table.GetTag()); // check BaseCoord offsets bool bOffsetsOk = true; for (uint i=0; i<BaseCoordCount; i++) { ushort bco = GetBaseCoordOffset(i); if (bco == 0) { v.Error(T.T_NULL, E.BASE_E_BaseValuesTable_BCO_0, table.m_tag, sIdentity + ", BaseCoordOffset index = " + i); bOffsetsOk = false; bRet = false; } else if (bco + m_offsetBaseValuesTable > m_bufTable.GetLength()) { v.Error(T.T_NULL, E.BASE_E_BaseValuesTable_BCO_invalid, table.m_tag, sIdentity + ", BaseCoordOffset index = " + i); bOffsetsOk = false; bRet = false; } } if (bOffsetsOk) { v.Pass(T.T_NULL, P.BASE_P_BaseValuesTable_BCO, table.m_tag, sIdentity); } // check the BaseCoord tables for (uint i=0; i<BaseCoordCount; i++) { BaseCoordTable_val bct = GetBaseCoordTable_val(i); bct.Validate(v, sIdentity, table); } return bRet; } public BaseCoordTable_val GetBaseCoordTable_val(uint i) { BaseCoordTable_val bct = null; if (i < BaseCoordCount) { ushort offset = (ushort)(m_offsetBaseValuesTable + GetBaseCoordOffset(i)); bct = new BaseCoordTable_val(offset, m_bufTable); } return bct; } } public class MinMaxTable_val : MinMaxTable, I_OTLValidate { public MinMaxTable_val(ushort offset, MBOBuffer bufTable) : base(offset, bufTable) { } public bool Validate(Validator v, string sIdentity, OTTable table) { bool bRet = true; bRet &= ((val_BASE)table).ValidateNoOverlap(m_offsetMinMaxTable, CalcLength(), v, sIdentity, table.GetTag()); // check the MinCoordOffset if (MinCoordOffset == 0) { v.Pass(T.T_NULL, P.BASE_P_MinMaxTable_MinCO_0, table.m_tag, sIdentity); } else if (MinCoordOffset + m_offsetMinMaxTable > m_bufTable.GetLength()) { v.Error(T.T_NULL, E.BASE_E_MinMaxTable_MinCO, table.m_tag, sIdentity); bRet = false; } else { v.Pass(T.T_NULL, P.BASE_P_MinMaxTable_MinCO, table.m_tag, sIdentity); } // check the MaxCoordOffset if (MaxCoordOffset == 0) { v.Pass(T.T_NULL, P.BASE_P_MinMaxTable_MaxCO_0, table.m_tag, sIdentity); } else if (MaxCoordOffset + m_offsetMinMaxTable > m_bufTable.GetLength()) { v.Error(T.T_NULL, E.BASE_E_MinMaxTable_MaxCO, table.m_tag, sIdentity); bRet = false; } else { v.Pass(T.T_NULL, P.BASE_P_MinMaxTable_MaxCO, table.m_tag, sIdentity); } // check the FeatMinMaxRecords bool bFeatMinMaxRecordsOk = true; for (uint i=0; i<FeatMinMaxCount; i++) { FeatMinMaxRecord fmmr = GetFeatMinMaxRecord(i); if (fmmr!=null) { if (fmmr.MinCoordOffset + m_offsetMinMaxTable > m_bufTable.GetLength()) { v.Error(T.T_NULL, E.BASE_E_FeatMinMaxRecords_MinCO_offset, table.m_tag, sIdentity + ", FeatMinMaxRecord[" + i + "]"); bFeatMinMaxRecordsOk = false; bRet = false; } if (fmmr.MaxCoordOffset + m_offsetMinMaxTable > m_bufTable.GetLength()) { v.Error(T.T_NULL, E.BASE_E_FeatMinMaxRecords_MaxCO_offset, table.m_tag, sIdentity + ", FeatMinMaxRecord[" + i + "]"); bFeatMinMaxRecordsOk = false; bRet = false; } } else { bFeatMinMaxRecordsOk = false; } } if (bFeatMinMaxRecordsOk) { v.Pass(T.T_NULL, P.BASE_P_FeatMinMaxRecords_offsets, table.m_tag, sIdentity); } // check the BaseCoord Tables BaseCoordTable_val bct = null; bct = GetMinCoordTable_val(); if (bct != null) { bct.Validate(v, sIdentity, table); } bct = GetMaxCoordTable_val(); if (bct != null) { bct.Validate(v, sIdentity, table); } for (uint i=0; i<FeatMinMaxCount; i++) { FeatMinMaxRecord fmmr = GetFeatMinMaxRecord(i); bct = GetFeatMinCoordTable_val(fmmr); if (bct != null) { bct.Validate(v, sIdentity, table); } bct = GetFeatMaxCoordTable_val(fmmr); if (bct != null) { bct.Validate(v, sIdentity, table); } } return bRet; } public BaseCoordTable_val GetMinCoordTable_val() { BaseCoordTable_val bct = null; if (MinCoordOffset != 0) { ushort offset = (ushort)(m_offsetMinMaxTable + MinCoordOffset); if (offset + 4 < m_bufTable.GetLength()) { bct = new BaseCoordTable_val(offset, m_bufTable); } } return bct; } public BaseCoordTable_val GetMaxCoordTable_val() { BaseCoordTable_val bct = null; if (MaxCoordOffset != 0) { ushort offset = (ushort)(m_offsetMinMaxTable + MaxCoordOffset); if (offset + 4 < m_bufTable.GetLength()) { bct = new BaseCoordTable_val(offset, m_bufTable); } } return bct; } public BaseCoordTable_val GetFeatMinCoordTable_val(FeatMinMaxRecord fmmr) { BaseCoordTable_val bct = null; if (fmmr != null) { if (fmmr.MinCoordOffset != 0) { ushort offset = (ushort)(m_offsetMinMaxTable + fmmr.MinCoordOffset); if (offset + 4 < m_bufTable.GetLength()) { bct = new BaseCoordTable_val(offset, m_bufTable); } } } return bct; } public BaseCoordTable_val GetFeatMaxCoordTable_val(FeatMinMaxRecord fmmr) { BaseCoordTable_val bct = null; if (fmmr != null) { if (fmmr.MaxCoordOffset != 0) { ushort offset = (ushort)(m_offsetMinMaxTable + fmmr.MaxCoordOffset); if (offset + 4 < m_bufTable.GetLength()) { bct = new BaseCoordTable_val(offset, m_bufTable); } } } return bct; } } public class BaseCoordTable_val : BaseCoordTable, I_OTLValidate { public BaseCoordTable_val(ushort offset, MBOBuffer bufTable) : base (offset, bufTable) { } public bool Validate(Validator v, string sIdentity, OTTable table) { bool bRet = true; bRet &= ((val_BASE)table).ValidateNoOverlap(m_offsetBaseCoordTable, CalcLength(), v, sIdentity, table.GetTag()); if (BaseCoordFormat == 1 || BaseCoordFormat == 2 || BaseCoordFormat == 3) { v.Pass(T.T_NULL, P.BASE_P_BaseCoordTable_format, table.m_tag, sIdentity); } else { v.Error(T.T_NULL, E.BASE_E_BaseCoordTable_format, table.m_tag, sIdentity + ", format = " + BaseCoordFormat); } return bRet; } public DeviceTable_val GetDeviceTable_val() { if (BaseCoordFormat != 3) { throw new System.InvalidOperationException(); } return new DeviceTable_val(DeviceTableOffset, m_bufTable); } } public AxisTable_val GetHorizAxisTable_val() { AxisTable_val at = null; if (HorizAxisOffset != 0) { at = new AxisTable_val(HorizAxisOffset, m_bufTable); } return at; } public AxisTable_val GetVertAxisTable_val() { AxisTable_val at = null; if (VertAxisOffset != 0) { at = new AxisTable_val(VertAxisOffset, m_bufTable); } return at; } public bool ValidateNoOverlap(uint offset, uint length, Validator v, string sIdentity, OTTag tag) { bool bValid = m_DataOverlapDetector.CheckForNoOverlap(offset, length); if (!bValid) { v.Error(T.T_NULL, E._Table_E_DataOverlap, tag, sIdentity + ", offset = " + offset + ", length = " + length); } return bValid; } protected DataOverlapDetector m_DataOverlapDetector; } }
using OpenKh.Common; using OpenKh.Kh2; using OpenKh.Ps2; using System.Collections.Generic; using System.IO; using System.Linq; using System.Numerics; namespace OpenKh.Engine.Parsers { public class Kkdf2MdlxParser { private class ImmutableMesh { public Mdlx.DmaChain DmaChain { get; } public List<VpuPacket> VpuPackets { get; } public int TextureIndex => DmaChain.TextureIndex; public bool IsOpaque => (DmaChain.RenderFlags & 1) == 0; public ImmutableMesh(Mdlx.DmaChain dmaChain) { DmaChain = dmaChain; VpuPackets = dmaChain.DmaVifs .Select(dmaVif => { var unpacker = new VifUnpacker(dmaVif.VifPacket); unpacker.Run(); using (var stream = new MemoryStream(unpacker.Memory)) return VpuPacket.Read(stream); }) .ToList(); } } private class VertexRef { public int vertexIndex, uvIndex; public VertexRef(int vertexIndex, int uvIndex) { this.vertexIndex = vertexIndex; this.uvIndex = uvIndex; } } private class TriangleRef { public TriangleRef(VertexRef one, VertexRef two, VertexRef three) { list = new VertexRef[] { one, two, three }; } public VertexRef[] list; public int textureIndex; public bool isOpaque; } private class ExportedMesh { public class Part { public int TextureIndex; public bool IsOpaque; public List<TriangleRef> triangleRefList = new List<TriangleRef>(); } public List<Part> partList = new List<Part>(); public List<Vector3> positionList = new List<Vector3>(); public List<Vector2> uvList = new List<Vector2>(); public List<Vector4[]> vertices; public List<VertexIndexWeighted[][]> vertexAssignments; } private readonly List<ImmutableMesh> immultableMeshList; private readonly ExportedMesh immutableExportedMesh; /// <summary> /// Build immutable parts from a submodel. /// </summary> /// <param name="submodel"></param> public Kkdf2MdlxParser(Mdlx.SubModel submodel) { immultableMeshList = submodel.DmaChains .Select(x => new ImmutableMesh(x)) .ToList(); immutableExportedMesh = PreProcessVerticesAndBuildModel(); } private ExportedMesh PreProcessVerticesAndBuildModel() { var exportedMesh = new ExportedMesh(); exportedMesh.vertexAssignments = new List<VertexIndexWeighted[][]>(); exportedMesh.vertices = new List<Vector4[]>(); int vertexBaseIndex = 0; int uvBaseIndex = 0; VertexRef[] ringBuffer = new VertexRef[4]; int ringIndex = 0; int[] triangleOrder = new int[] { 1, 3, 2 }; foreach (ImmutableMesh meshRoot in immultableMeshList) { for (int i = 0; i < meshRoot.VpuPackets.Count; i++) { VpuPacket mesh = meshRoot.VpuPackets[i]; var part = new ExportedMesh.Part { TextureIndex = meshRoot.TextureIndex, IsOpaque = meshRoot.IsOpaque, }; for (int x = 0; x < mesh.Indices.Length; x++) { var indexAssign = mesh.Indices[x]; VertexRef vertexRef = new VertexRef( vertexBaseIndex + indexAssign.Index, uvBaseIndex + x ); ringBuffer[ringIndex] = vertexRef; ringIndex = (ringIndex + 1) & 3; var flag = indexAssign.Function; if (flag == VpuPacket.VertexFunction.DrawTriangle || flag == VpuPacket.VertexFunction.DrawTriangleDoubleSided) { var triRef = new TriangleRef( ringBuffer[(ringIndex - triangleOrder[0]) & 3], ringBuffer[(ringIndex - triangleOrder[1]) & 3], ringBuffer[(ringIndex - triangleOrder[2]) & 3] ); part.triangleRefList.Add(triRef); } if (flag == VpuPacket.VertexFunction.DrawTriangleInverse || flag == VpuPacket.VertexFunction.DrawTriangleDoubleSided) { var triRef = new TriangleRef( ringBuffer[(ringIndex - triangleOrder[0]) & 3], ringBuffer[(ringIndex - triangleOrder[2]) & 3], ringBuffer[(ringIndex - triangleOrder[1]) & 3] ); part.triangleRefList.Add(triRef); } } var vertices = mesh.Vertices .Select(vertex => new Vector4(vertex.X, vertex.Y, vertex.Z, vertex.W)) .ToArray(); exportedMesh.vertices.Add(vertices); var matrixIndexList = meshRoot.DmaChain.DmaVifs[i].Alaxi; var vertexAssignmentsList = mesh.GetWeightedVertices(mesh.GetFromMatrixIndices(matrixIndexList)); exportedMesh.vertexAssignments.Add(vertexAssignmentsList); exportedMesh.uvList.AddRange( mesh.Indices.Select(x => new Vector2(x.U / 16 / 256.0f, x.V / 16 / 256.0f)) ); exportedMesh.partList.Add(part); vertexBaseIndex += vertexAssignmentsList.Length; uvBaseIndex += mesh.Indices.Length; } } return exportedMesh; } public List<MeshDescriptor> ProcessVerticesAndBuildModel(Matrix4x4[] matrices) { immutableExportedMesh.positionList.Clear(); for (var i = 0; i < immutableExportedMesh.vertexAssignments.Count; i++) { var vertexAssignments = immutableExportedMesh.vertexAssignments[i]; var vertices = immutableExportedMesh.vertices[i]; immutableExportedMesh.positionList.AddRange( vertexAssignments.Select( vertexAssigns => { Vector3 finalPos = Vector3.Zero; if (vertexAssigns.Length == 1) { // single joint finalPos = Vector3.Transform( ToVector3(vertices[vertexAssigns[0].VertexIndex]), matrices[vertexAssigns[0].MatrixIndex]); } else { // multiple joints, using rawPos.W as blend weights foreach (var vertexAssign in vertexAssigns) { finalPos += ToVector3( Vector4.Transform( vertices[vertexAssign.VertexIndex], matrices[vertexAssign.MatrixIndex] )); } } return finalPos; } ) ); } var newList = new List<MeshDescriptor>(); foreach (var part in immutableExportedMesh.partList) { var vertices = new List<PositionColoredTextured>(); var indices = new List<int>(); int triangleRefCount = part.triangleRefList.Count; for (int triIndex = 0; triIndex < triangleRefCount; triIndex++) { TriangleRef triRef = part.triangleRefList[triIndex]; for (int i = 0; i < triRef.list.Length; i++) { VertexRef vertRef = triRef.list[i]; indices.Add(vertices.Count); vertices.Add(new PositionColoredTextured( immutableExportedMesh.positionList[vertRef.vertexIndex], immutableExportedMesh.uvList[vertRef.uvIndex], 1.0f, 1.0f, 1.0f, 1.0f)); } } newList.Add( new MeshDescriptor { IsOpaque = part.IsOpaque, TextureIndex = part.TextureIndex, Vertices = vertices.ToArray(), Indices = indices.ToArray(), } ); } return newList; } private static Vector3 ToVector3(Vector4 pos) => new Vector3(pos.X, pos.Y, pos.Z); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CSharp.RuntimeBinder.Errors; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal sealed partial class ExpressionBinder { // ---------------------------------------------------------------------------- // BindImplicitConversion // ---------------------------------------------------------------------------- private sealed class ImplicitConversion { public ImplicitConversion(ExpressionBinder binder, EXPR exprSrc, CType typeSrc, EXPRTYPEORNAMESPACE typeDest, bool needsExprDest, CONVERTTYPE flags) { _binder = binder; _exprSrc = exprSrc; _typeSrc = typeSrc; _typeDest = typeDest.TypeOrNamespace.AsType(); _exprTypeDest = typeDest; _needsExprDest = needsExprDest; _flags = flags; _exprDest = null; } public EXPR ExprDest { get { return _exprDest; } } private EXPR _exprDest; private readonly ExpressionBinder _binder; private readonly EXPR _exprSrc; private readonly CType _typeSrc; private readonly CType _typeDest; private readonly EXPRTYPEORNAMESPACE _exprTypeDest; private readonly bool _needsExprDest; private CONVERTTYPE _flags; /* * BindImplicitConversion * * This is a complex routine with complex parameters. Generally, this should * be called through one of the helper methods that insulates you * from the complexity of the interface. This routine handles all the logic * associated with implicit conversions. * * exprSrc - the expression being converted. Can be null if only type conversion * info is being supplied. * typeSrc - type of the source * typeDest - type of the destination * exprDest - returns an expression of the src converted to the dest. If null, we * only care about whether the conversion can be attempted, not the * expression tree. * flags - flags possibly customizing the conversions allowed. E.g., can suppress * user-defined conversions. * * returns true if the conversion can be made, false if not. */ public bool Bind() { // 13.1 Implicit conversions // // The following conversions are classified as implicit conversions: // // * Identity conversions // * Implicit numeric conversions // * Implicit enumeration conversions // * Implicit reference conversions // * Boxing conversions // * Implicit type parameter conversions // * Implicit constant expression conversions // * User-defined implicit conversions // * Implicit conversions from an anonymous method expression to a compatible delegate type // * Implicit conversion from a method group to a compatible delegate type // * Conversions from the null type (11.2.7) to any nullable type // * Implicit nullable conversions // * Lifted user-defined implicit conversions // // Implicit conversions can occur in a variety of situations, including function member invocations // (14.4.3), cast expressions (14.6.6), and assignments (14.14). // Can't convert to or from the error type. if (_typeSrc == null || _typeDest == null || _typeDest.IsNeverSameType()) { return false; } Debug.Assert(_typeSrc != null && _typeDest != null); // types must be supplied. Debug.Assert(_exprSrc == null || _typeSrc == _exprSrc.type); // type of source should be correct if source supplied Debug.Assert(!_needsExprDest || _exprSrc != null); // need source expr to create dest expr switch (_typeDest.GetTypeKind()) { case TypeKind.TK_ErrorType: Debug.Assert(_typeDest.AsErrorType().HasTypeParent() || _typeDest.AsErrorType().HasNSParent()); if (_typeSrc != _typeDest) { return false; } if (_needsExprDest) { _exprDest = _exprSrc; } return true; case TypeKind.TK_NullType: // Can only convert to the null type if src is null. if (!_typeSrc.IsNullType()) { return false; } if (_needsExprDest) { _exprDest = _exprSrc; } return true; case TypeKind.TK_MethodGroupType: VSFAIL("Something is wrong with Type.IsNeverSameType()"); return false; case TypeKind.TK_NaturalIntegerType: case TypeKind.TK_ArgumentListType: return _typeSrc == _typeDest; case TypeKind.TK_VoidType: return false; default: break; } if (_typeSrc.IsErrorType()) { Debug.Assert(!_typeDest.IsErrorType()); return false; } // 13.1.1 Identity conversion // // An identity conversion converts from any type to the same type. This conversion exists only // such that an entity that already has a required type can be said to be convertible to that type. if (_typeSrc == _typeDest && ((_flags & CONVERTTYPE.ISEXPLICIT) == 0 || (!_typeSrc.isPredefType(PredefinedType.PT_FLOAT) && !_typeSrc.isPredefType(PredefinedType.PT_DOUBLE)))) { if (_needsExprDest) { _exprDest = _exprSrc; } return true; } if (_typeDest.IsNullableType()) { return BindNubConversion(_typeDest.AsNullableType()); } if (_typeSrc.IsNullableType()) { return bindImplicitConversionFromNullable(_typeSrc.AsNullableType()); } if ((_flags & CONVERTTYPE.ISEXPLICIT) != 0) { _flags |= CONVERTTYPE.NOUDC; } // Get the fundamental types of destination. FUNDTYPE ftDest = _typeDest.fundType(); Debug.Assert(ftDest != FUNDTYPE.FT_NONE || _typeDest.IsParameterModifierType()); switch (_typeSrc.GetTypeKind()) { default: VSFAIL("Bad type symbol kind"); break; case TypeKind.TK_MethodGroupType: if (_exprSrc.isMEMGRP()) { EXPRCALL outExpr; bool retVal = _binder.BindGrpConversion(_exprSrc.asMEMGRP(), _typeDest, _needsExprDest, out outExpr, false); _exprDest = outExpr; return retVal; } return false; case TypeKind.TK_VoidType: case TypeKind.TK_ErrorType: case TypeKind.TK_ParameterModifierType: case TypeKind.TK_ArgumentListType: return false; case TypeKind.TK_NullType: if (bindImplicitConversionFromNull()) { return true; } // If not, try user defined implicit conversions. break; case TypeKind.TK_ArrayType: if (bindImplicitConversionFromArray()) { return true; } // If not, try user defined implicit conversions. break; case TypeKind.TK_PointerType: if (bindImplicitConversionFromPointer()) { return true; } // If not, try user defined implicit conversions. break; case TypeKind.TK_TypeParameterType: if (bindImplicitConversionFromTypeVar(_typeSrc.AsTypeParameterType())) { return true; } // If not, try user defined implicit conversions. break; case TypeKind.TK_AggregateType: // TypeReference and ArgIterator can't be boxed (or converted to anything else) if (_typeSrc.isSpecialByRefType()) { return false; } if (bindImplicitConversionFromAgg(_typeSrc.AsAggregateType())) { return true; } // If not, try user defined implicit conversions. break; } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // RUNTIME BINDER ONLY CHANGE // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // // Every incoming dynamic operand should be implicitly convertible // to any type that it is an instance of. object srcRuntimeObject = _exprSrc?.RuntimeObject; if (srcRuntimeObject != null && _typeDest.AssociatedSystemType.IsInstanceOfType(srcRuntimeObject) && _binder.GetSemanticChecker().CheckTypeAccess(_typeDest, _binder.Context.ContextForMemberLookup())) { if (_needsExprDest) { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, _exprSrc.flags & EXPRFLAG.EXF_CANTBENULL); } return true; } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // END RUNTIME BINDER ONLY CHANGE // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // 13.1.8 User-defined implicit conversions // // A user-defined implicit conversion consists of an optional standard implicit conversion, // followed by execution of a user-defined implicit conversion operator, followed by another // optional standard implicit conversion. The exact rules for evaluating user-defined // conversions are described in 13.4.3. if (0 == (_flags & CONVERTTYPE.NOUDC)) { return _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, _typeDest, _needsExprDest, out _exprDest, true); } // No conversion was found. return false; } /*************************************************************************************************** Called by BindImplicitConversion when the destination type is Nullable<T>. The following conversions are handled by this method: * For S in { object, ValueType, interfaces implemented by underlying type} there is an explicit unboxing conversion S => T? * System.Enum => T? there is an unboxing conversion if T is an enum type * null => T? implemented as default(T?) * Implicit T?* => T?+ implemented by either wrapping or calling GetValueOrDefault the appropriate number of times. * If imp/exp S => T then imp/exp S => T?+ implemented by converting to T then wrapping the appropriate number of times. * If imp/exp S => T then imp/exp S?+ => T?+ implemented by calling GetValueOrDefault (m-1) times then calling HasValue, producing a null if it returns false, otherwise calling Value, converting to T then wrapping the appropriate number of times. The 3 rules above can be summarized with the following recursive rules: * If imp/exp S => T? then imp/exp S? => T? implemented as qs.HasValue ? (T?)(qs.Value) : default(T?) * If imp/exp S => T then imp/exp S => T? implemented as new T?((T)s) This method also handles calling bindUserDefinedConverion. This method does NOT handle the following conversions: * Implicit boxing conversion from S? to { object, ValueType, Enum, ifaces implemented by S }. (Handled by BindImplicitConversion.) * If imp/exp S => T then explicit S?+ => T implemented by calling Value the appropriate number of times. (Handled by BindExplicitConversion.) The recursive equivalent is: * If imp/exp S => T and T is not nullable then explicit S? => T implemented as qs.Value Some nullable conversion are NOT standard conversions. In particular, if S => T is implicit then S? => T is not standard. Similarly if S => T is not implicit then S => T? is not standard. ***************************************************************************************************/ private bool BindNubConversion(NullableType nubDst) { // This code assumes that STANDARD and ISEXPLICIT are never both set. // bindUserDefinedConversion should ensure this! Debug.Assert(0 != (~_flags & (CONVERTTYPE.STANDARD | CONVERTTYPE.ISEXPLICIT))); Debug.Assert(_exprSrc == null || _exprSrc.type == _typeSrc); Debug.Assert(!_needsExprDest || _exprSrc != null); Debug.Assert(_typeSrc != nubDst); // BindImplicitConversion should have taken care of this already. AggregateType atsDst = nubDst.GetAts(GetErrorContext()); if (atsDst == null) return false; // Check for the unboxing conversion. This takes precedence over the wrapping conversions. if (GetSymbolLoader().HasBaseConversion(nubDst.GetUnderlyingType(), _typeSrc) && !CConversions.FWrappingConv(_typeSrc, nubDst)) { // These should be different! Fix the caller if typeSrc is an AggregateType of Nullable. Debug.Assert(atsDst != _typeSrc); // typeSrc is a base type of the destination nullable type so there is an explicit // unboxing conversion. if (0 == (_flags & CONVERTTYPE.ISEXPLICIT)) { return false; } if (_needsExprDest) { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_UNBOX); } return true; } int cnubDst; int cnubSrc; CType typeDstBase = nubDst.StripNubs(out cnubDst); EXPRCLASS exprTypeDstBase = GetExprFactory().MakeClass(typeDstBase); CType typeSrcBase = _typeSrc.StripNubs(out cnubSrc); ConversionFunc pfn = (_flags & CONVERTTYPE.ISEXPLICIT) != 0 ? (ConversionFunc)_binder.BindExplicitConversion : (ConversionFunc)_binder.BindImplicitConversion; if (cnubSrc == 0) { Debug.Assert(_typeSrc == typeSrcBase); // The null type can be implicitly converted to T? as the default value. if (_typeSrc.IsNullType()) { // If we have the constant null, generate it as a default value of T?. If we have // some crazy expression which has been determined to be always null, like (null??null) // keep it in its expression form and transform it in the nullable rewrite pass. if (_needsExprDest) { if (_exprSrc.isCONSTANT_OK()) { _exprDest = GetExprFactory().CreateZeroInit(nubDst); } else { _exprDest = GetExprFactory().CreateCast(0x00, _typeDest, _exprSrc); } } return true; } EXPR exprTmp = _exprSrc; // If there is an implicit/explicit S => T then there is an implicit/explicit S => T? if (_typeSrc == typeDstBase || pfn(_exprSrc, _typeSrc, exprTypeDstBase, nubDst, _needsExprDest, out exprTmp, _flags | CONVERTTYPE.NOUDC)) { if (_needsExprDest) { EXPRUSERDEFINEDCONVERSION exprUDC = exprTmp.kind == ExpressionKind.EK_USERDEFINEDCONVERSION ? exprTmp.asUSERDEFINEDCONVERSION() : null; if (exprUDC != null) { exprTmp = exprUDC.UserDefinedCall; } // This logic is left over from the days when T?? was legal. However there are error/LAF cases that necessitates the loop. // typeSrc is not nullable so just wrap the required number of times. For legal code (cnubDst <= 0). for (int i = 0; i < cnubDst; i++) { exprTmp = _binder.BindNubNew(exprTmp); exprTmp.asCALL().nubLiftKind = NullableCallLiftKind.NullableConversionConstructor; } if (exprUDC != null) { exprUDC.UserDefinedCall = exprTmp; exprUDC.setType((CType)exprTmp.type); exprTmp = exprUDC; } Debug.Assert(exprTmp.type == nubDst); _exprDest = exprTmp; } return true; } // No builtin conversion. Maybe there is a user defined conversion.... return 0 == (_flags & CONVERTTYPE.NOUDC) && _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, nubDst, _needsExprDest, out _exprDest, 0 == (_flags & CONVERTTYPE.ISEXPLICIT)); } // Both are Nullable so there is only a conversion if there is a conversion between the base types. // That is, if there is an implicit/explicit S => T then there is an implicit/explicit S?+ => T?+. if (typeSrcBase != typeDstBase && !pfn(null, typeSrcBase, exprTypeDstBase, nubDst, false, out _exprDest, _flags | CONVERTTYPE.NOUDC)) { // No builtin conversion. Maybe there is a user defined conversion.... return 0 == (_flags & CONVERTTYPE.NOUDC) && _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, nubDst, _needsExprDest, out _exprDest, 0 == (_flags & CONVERTTYPE.ISEXPLICIT)); } if (_needsExprDest) { MethWithInst mwi = new MethWithInst(null, null); EXPRMEMGRP pMemGroup = GetExprFactory().CreateMemGroup(null, mwi); EXPRCALL exprDst = GetExprFactory().CreateCall(0, nubDst, _exprSrc, pMemGroup, null); // Here we want to first check whether or not the conversions work on the base types. EXPR arg1 = _binder.mustCast(_exprSrc, typeSrcBase); EXPRCLASS arg2 = GetExprFactory().MakeClass(typeDstBase); bool convertible; if (0 != (_flags & CONVERTTYPE.ISEXPLICIT)) { convertible = _binder.BindExplicitConversion(arg1, arg1.type, arg2, typeDstBase, out arg1, _flags | CONVERTTYPE.NOUDC); } else { convertible = _binder.BindImplicitConversion(arg1, arg1.type, arg2, typeDstBase, out arg1, _flags | CONVERTTYPE.NOUDC); } if (!convertible) { VSFAIL("bind(Im|Ex)plicitConversion failed unexpectedly"); return false; } exprDst.castOfNonLiftedResultToLiftedType = _binder.mustCast(arg1, nubDst, 0); exprDst.nubLiftKind = NullableCallLiftKind.NullableConversion; exprDst.pConversions = exprDst.castOfNonLiftedResultToLiftedType; _exprDest = exprDst; } return true; } private bool bindImplicitConversionFromNull() { // null type can be implicitly converted to any reference type or pointer type or type // variable with reference-type constraint. FUNDTYPE ftDest = _typeDest.fundType(); if (ftDest != FUNDTYPE.FT_REF && ftDest != FUNDTYPE.FT_PTR && (ftDest != FUNDTYPE.FT_VAR || !_typeDest.AsTypeParameterType().IsReferenceType()) && // null is convertible to System.Nullable<T>. !_typeDest.isPredefType(PredefinedType.PT_G_OPTIONAL)) { return false; } if (_needsExprDest) { // If the conversion argument is a constant null then return a ZEROINIT. // Otherwise, bind this as a cast to the destination type. In a later // rewrite pass we will rewrite the cast as SEQ(side effects, ZEROINIT). if (_exprSrc.isCONSTANT_OK()) { _exprDest = GetExprFactory().CreateZeroInit(_typeDest); } else { _exprDest = GetExprFactory().CreateCast(0x00, _typeDest, _exprSrc); } } return true; } private bool bindImplicitConversionFromNullable(NullableType nubSrc) { // We can convert T? using a boxing conversion, we can convert it to ValueType, and // we can convert it to any interface implemented by T. // // 13.1.5 Boxing Conversions // // A nullable-type has a boxing conversion to the same set of types to which the nullable-type's // underlying type has boxing conversions. A boxing conversion applied to a value of a nullable-type // proceeds as follows: // // * If the HasValue property of the nullable value evaluates to false, then the result of the // boxing conversion is the null reference of the appropriate type. // // Otherwise, the result is obtained by boxing the result of evaluating the Value property on // the nullable value. AggregateType atsNub = nubSrc.GetAts(GetErrorContext()); if (atsNub == null) { return false; } if (atsNub == _typeDest) { if (_needsExprDest) { _exprDest = _exprSrc; } return true; } if (GetSymbolLoader().HasBaseConversion(nubSrc.GetUnderlyingType(), _typeDest) && !CConversions.FUnwrappingConv(nubSrc, _typeDest)) { if (_needsExprDest) { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_BOX); if (!_typeDest.isPredefType(PredefinedType.PT_OBJECT)) { // The base type of a nullable is always a non-nullable value type, // therefore so is typeDest unless typeDest is PT_OBJECT. In this case the conversion // needs to be unboxed. We only need this if we actually will use the result. _binder.bindSimpleCast(_exprDest, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_FORCE_UNBOX); } } return true; } return 0 == (_flags & CONVERTTYPE.NOUDC) && _binder.bindUserDefinedConversion(_exprSrc, nubSrc, _typeDest, _needsExprDest, out _exprDest, true); } private bool bindImplicitConversionFromArray() { // 13.1.4 // // The implicit reference conversions are: // // * From an array-type S with an element type SE to an array-type T with an element // type TE, provided all of the following are true: // * S and T differ only in element type. In other words, S and T have the same number of dimensions. // * An implicit reference conversion exists from SE to TE. // * From a one-dimensional array-type S[] to System.Collections.Generic.IList<S>, // System.Collections.Generic.IReadOnlyList<S> and their base interfaces // * From a one-dimensional array-type S[] to System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyList<T> // and their base interfaces, provided there is an implicit reference conversion from S to T. // * From any array-type to System.Array. // * From any array-type to any interface implemented by System.Array. if (!GetSymbolLoader().HasBaseConversion(_typeSrc, _typeDest)) { return false; } EXPRFLAG grfex = 0; // The above if checks for dest==Array, object or an interface the array implements, // including IList<T>, ICollection<T>, IEnumerable<T>, IReadOnlyList<T>, IReadOnlyCollection<T> // and the non-generic versions. if ((_typeDest.IsArrayType() || (_typeDest.isInterfaceType() && _typeDest.AsAggregateType().GetTypeArgsAll().Size == 1 && ((_typeDest.AsAggregateType().GetTypeArgsAll().Item(0) != _typeSrc.AsArrayType().GetElementType()) || 0 != (_flags & CONVERTTYPE.FORCECAST)))) && (0 != (_flags & CONVERTTYPE.FORCECAST) || TypeManager.TypeContainsTyVars(_typeSrc, null) || TypeManager.TypeContainsTyVars(_typeDest, null))) { grfex = EXPRFLAG.EXF_REFCHECK; } if (_needsExprDest) { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, grfex); } return true; } private bool bindImplicitConversionFromPointer() { // 27.4 Pointer conversions // // In an unsafe context, the set of available implicit conversions (13.1) is extended to include // the following implicit pointer conversions: // // * From any pointer-type to the type void*. if (_typeDest.IsPointerType() && _typeDest.AsPointerType().GetReferentType() == _binder.getVoidType()) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest); return true; } return false; } private bool bindImplicitConversionFromAgg(AggregateType aggTypeSrc) { // GENERICS: The case for constructed types is very similar to types with // no parameters. The parameters are irrelevant for most of the conversions // below. They could be relevant if we had user-defined conversions on // generic types. AggregateSymbol aggSrc = aggTypeSrc.getAggregate(); if (aggSrc.IsEnum()) { return bindImplicitConversionFromEnum(aggTypeSrc); } if (_typeDest.isEnumType()) { if (bindImplicitConversionToEnum(aggTypeSrc)) { return true; } // Even though enum is sealed, a class can derive from enum in LAF scenarios -- // continue testing for derived to base conversions below. } else if (aggSrc.getThisType().isSimpleType() && _typeDest.isSimpleType()) { if (bindImplicitConversionBetweenSimpleTypes(aggTypeSrc)) { return true; } // No simple conversion -- continue testing for derived to base conversions below. } return bindImplicitConversionToBase(aggTypeSrc); } private bool bindImplicitConversionToBase(AggregateType pSource) { // 13.1.4 Implicit reference conversions // // * From any reference-type to object. // * From any class-type S to any class-type T, provided S is derived from T. // * From any class-type S to any interface-type T, provided S implements T. // * From any interface-type S to any interface-type T, provided S is derived from T. // * From any delegate-type to System.Delegate. // * From any delegate-type to System.ICloneable. if (!_typeDest.IsAggregateType() || !GetSymbolLoader().HasBaseConversion(pSource, _typeDest)) { return false; } EXPRFLAG flags = 0x00; if (pSource.getAggregate().IsStruct() && _typeDest.fundType() == FUNDTYPE.FT_REF) { flags = EXPRFLAG.EXF_BOX | EXPRFLAG.EXF_CANTBENULL; } else if (_exprSrc != null) { flags = _exprSrc.flags & EXPRFLAG.EXF_CANTBENULL; } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, flags); return true; } private bool bindImplicitConversionFromEnum(AggregateType aggTypeSrc) { // 13.1.5 Boxing conversions // // A boxing conversion permits any non-nullable-value-type to be implicitly converted to the type // object or System.ValueType or to any interface-type implemented by the value-type, and any enum // type to be implicitly converted to System.Enum as well. Boxing a value of a // non-nullable-value-type consists of allocating an object instance and copying the value-type // value into that instance. An enum can be boxed to the type System.Enum, since that is the direct // base class for all enums (21.4). A struct or enum can be boxed to the type System.ValueType, // since that is the direct base class for all structs (18.3.2) and a base class for all enums. if (_typeDest.IsAggregateType() && GetSymbolLoader().HasBaseConversion(aggTypeSrc, _typeDest.AsAggregateType())) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_BOX | EXPRFLAG.EXF_CANTBENULL); return true; } return false; } private bool bindImplicitConversionToEnum(AggregateType aggTypeSrc) { // The spec states: // ***************** // 13.1.3 Implicit enumeration conversions // // An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any // enum-type. // ***************** // However, we actually allow any constant zero, not just the integer literal zero, to be converted // to enum. The reason for this is for backwards compatibility with a premature optimization // that used to be in the binding layer. We would optimize away expressions such as 0 | blah to be // just 0, but not erase the "is literal" bit. This meant that expression such as 0 | 0 | E.X // would succeed rather than correctly producing an error pointing out that 0 | 0 is not a literal // zero and therefore does not convert to any enum. // // We have removed the premature optimization but want old code to continue to compile. Rather than // try to emulate the somewhat complex behaviour of the previous optimizer, it is easier to simply // say that any compile time constant zero is convertible to any enum. This means unfortunately // expressions such as (7-7) * 12 are convertible to enum, but frankly, that's better than having // some terribly complex rule about what constitutes a legal zero and what doesn't. // Note: Don't use GetConst here since the conversion only applies to bona-fide compile time constants. if ( aggTypeSrc.getAggregate().GetPredefType() != PredefinedType.PT_BOOL && _exprSrc != null && _exprSrc.isZero() && _exprSrc.type.isNumericType() && /*(exprSrc.flags & EXF_LITERALCONST) &&*/ 0 == (_flags & CONVERTTYPE.STANDARD)) { // NOTE: This allows conversions from uint, long, ulong, float, double, and hexadecimal int // NOTE: This is for backwards compatibility with Everett // This is another place where we lose EXPR fidelity. We shouldn't fold this // into a constant here - we should move this to a later pass. if (_needsExprDest) { _exprDest = GetExprFactory().CreateConstant(_typeDest, ConstValFactory.GetDefaultValue(_typeDest.constValKind())); } return true; } return false; } private bool bindImplicitConversionBetweenSimpleTypes(AggregateType aggTypeSrc) { AggregateSymbol aggSrc = aggTypeSrc.getAggregate(); Debug.Assert(aggSrc.getThisType().isSimpleType()); Debug.Assert(_typeDest.isSimpleType()); Debug.Assert(aggSrc.IsPredefined() && _typeDest.isPredefined()); PredefinedType ptSrc = aggSrc.GetPredefType(); PredefinedType ptDest = _typeDest.getPredefType(); ConvKind convertKind; bool fConstShrinkCast = false; Debug.Assert((int)ptSrc < NUM_SIMPLE_TYPES && (int)ptDest < NUM_SIMPLE_TYPES); // 13.1.7 Implicit constant expression conversions // // An implicit constant expression conversion permits the following conversions: // * A constant-expression (14.16) of type int can be converted to type sbyte, byte, short, // ushort, uint, or ulong, provided the value of the constant-expression is within the range // of the destination type. // * A constant-expression of type long can be converted to type ulong, provided the value of // the constant-expression is not negative. // Note: Don't use GetConst here since the conversion only applies to bona-fide compile time constants. if (_exprSrc != null && _exprSrc.isCONSTANT_OK() && ((ptSrc == PredefinedType.PT_INT && ptDest != PredefinedType.PT_BOOL && ptDest != PredefinedType.PT_CHAR) || (ptSrc == PredefinedType.PT_LONG && ptDest == PredefinedType.PT_ULONG)) && isConstantInRange(_exprSrc.asCONSTANT(), _typeDest)) { // Special case (CLR 6.1.6): if integral constant is in range, the conversion is a legal implicit conversion. convertKind = ConvKind.Implicit; fConstShrinkCast = _needsExprDest && (GetConvKind(ptSrc, ptDest) != ConvKind.Implicit); } else if (ptSrc == ptDest) { // Special case: precision limiting casts to float or double Debug.Assert(ptSrc == PredefinedType.PT_FLOAT || ptSrc == PredefinedType.PT_DOUBLE); Debug.Assert(0 != (_flags & CONVERTTYPE.ISEXPLICIT)); convertKind = ConvKind.Implicit; } else { convertKind = GetConvKind(ptSrc, ptDest); Debug.Assert(convertKind != ConvKind.Identity); // identity conversion should have been handled at first. } if (convertKind != ConvKind.Implicit) { return false; } // An implicit conversion exists. Do the conversion. if (_exprSrc.GetConst() != null) { // Fold the constant cast if possible. ConstCastResult result = _binder.bindConstantCast(_exprSrc, _exprTypeDest, _needsExprDest, out _exprDest, false); if (result == ConstCastResult.Success) { return true; // else, don't fold and use a regular cast, below. } } if (isUserDefinedConversion(ptSrc, ptDest)) { if (!_needsExprDest) { return true; } // According the language, this is a standard conversion, but it is implemented // through a user-defined conversion. Because it's a standard conversion, we don't // test the NOUDC flag here. return _binder.bindUserDefinedConversion(_exprSrc, aggTypeSrc, _typeDest, _needsExprDest, out _exprDest, true); } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest); return true; } private bool bindImplicitConversionFromTypeVar(TypeParameterType tyVarSrc) { // 13.1.4 // // For a type-parameter T that is known to be a reference type (25.7), the following implicit // reference conversions exist: // // * From T to its effective base class C, from T to any base class of C, and from T to any // interface implemented by C. // * From T to an interface-type I in T's effective interface set and from T to any base // interface of I. // * From T to a type parameter U provided that T depends on U (25.7). [Note: Since T is known // to be a reference type, within the scope of T, the run-time type of U will always be a // reference type, even if U is not known to be a reference type at compile-time.] // * From the null type (11.2.7) to T. // // 13.1.5 // // For a type-parameter T that is not known to be a reference type (25.7), the following conversions // involving T are considered to be boxing conversions at compile-time. At run-time, if T is a value // type, the conversion is executed as a boxing conversion. At run-time, if T is a reference type, // the conversion is executed as an implicit reference conversion or identity conversion. // // * From T to its effective base class C, from T to any base class of C, and from T to any // interface implemented by C. [Note: C will be one of the types System.Object, System.ValueType, // or System.Enum (otherwise T would be known to be a reference type and 13.1.4 would apply // instead of this clause).] // * From T to an interface-type I in T's effective interface set and from T to any base // interface of I. // // 13.1.6 Implicit type parameter conversions // // This clause details implicit conversions involving type parameters that are not classified as // implicit reference conversions or implicit boxing conversions. // // For a type-parameter T that is not known to be a reference type, there is an implicit conversion // from T to a type parameter U provided T depends on U. At run-time, if T is a value type and U is // a reference type, the conversion is executed as a boxing conversion. At run-time, if both T and U // are value types, then T and U are necessarily the same type and no conversion is performed. At // run-time, if T is a reference type, then U is necessarily also a reference type and the conversion // is executed as an implicit reference conversion or identity conversion (25.7). CType typeTmp = tyVarSrc.GetEffectiveBaseClass(); TypeArray bnds = tyVarSrc.GetBounds(); int itype = -1; for (; ;) { if (_binder.canConvert(typeTmp, _typeDest, _flags | CONVERTTYPE.NOUDC)) { if (!_needsExprDest) { return true; } if (_typeDest.IsTypeParameterType()) { // For a type var destination we need to cast to object then to the other type var. EXPR exprT; EXPRCLASS exprObj = GetExprFactory().MakeClass(_binder.GetReqPDT(PredefinedType.PT_OBJECT)); _binder.bindSimpleCast(_exprSrc, exprObj, out exprT, EXPRFLAG.EXF_FORCE_BOX); _binder.bindSimpleCast(exprT, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_FORCE_UNBOX); } else { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_FORCE_BOX); } return true; } do { if (++itype >= bnds.Size) { return false; } typeTmp = bnds.Item(itype); } while (!typeTmp.isInterfaceType() && !typeTmp.IsTypeParameterType()); } } private SymbolLoader GetSymbolLoader() { return _binder.GetSymbolLoader(); } private ExprFactory GetExprFactory() { return _binder.GetExprFactory(); } private ErrorHandling GetErrorContext() { return _binder.GetErrorContext(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Globalization; using System.Reflection; namespace System.Net { internal enum CookieToken { // State types Nothing, NameValuePair, // X=Y Attribute, // X EndToken, // ';' EndCookie, // ',' End, // EOLN Equals, // Value types Comment, CommentUrl, CookieName, Discard, Domain, Expires, MaxAge, Path, Port, Secure, HttpOnly, Unknown, Version } // CookieTokenizer // // Used to split a single or multi-cookie (header) string into individual // tokens. internal class CookieTokenizer { private bool _eofCookie; private int _index; private int _length; private string _name; private bool _quoted; private int _start; private CookieToken _token; private int _tokenLength; private string _tokenStream; private string _value; private int _cookieStartIndex; private int _cookieLength; internal CookieTokenizer(string tokenStream) { _length = tokenStream.Length; _tokenStream = tokenStream; } internal bool EndOfCookie { get { return _eofCookie; } set { _eofCookie = value; } } internal bool Eof { get { return _index >= _length; } } internal string Name { get { return _name; } set { _name = value; } } internal bool Quoted { get { return _quoted; } set { _quoted = value; } } internal CookieToken Token { get { return _token; } set { _token = value; } } internal string Value { get { return _value; } set { _value = value; } } // Extract // // Extracts the current token internal string Extract() { string tokenString = string.Empty; if (_tokenLength != 0) { tokenString = Quoted ? _tokenStream.Substring(_start, _tokenLength) : _tokenStream.SubstringTrim(_start, _tokenLength); } return tokenString; } // FindNext // // Find the start and length of the next token. The token is terminated // by one of: // - end-of-line // - end-of-cookie: unquoted comma separates multiple cookies // - end-of-token: unquoted semi-colon // - end-of-name: unquoted equals // // Inputs: // <argument> ignoreComma // true if parsing doesn't stop at a comma. This is only true when // we know we're parsing an original cookie that has an expires= // attribute, because the format of the time/date used in expires // is: // Wdy, dd-mmm-yyyy HH:MM:SS GMT // // <argument> ignoreEquals // true if parsing doesn't stop at an equals sign. The LHS of the // first equals sign is an attribute name. The next token may // include one or more equals signs. For example: // SESSIONID=ID=MSNx45&q=33 // // Outputs: // <member> _index // incremented to the last position in _tokenStream contained by // the current token // // <member> _start // incremented to the start of the current token // // <member> _tokenLength // set to the length of the current token // // Assumes: Nothing // // Returns: // type of CookieToken found: // // End - end of the cookie string // EndCookie - end of current cookie in (potentially) a // multi-cookie string // EndToken - end of name=value pair, or end of an attribute // Equals - end of name= // // Throws: Nothing internal CookieToken FindNext(bool ignoreComma, bool ignoreEquals) { _tokenLength = 0; _start = _index; while ((_index < _length) && char.IsWhiteSpace(_tokenStream[_index])) { ++_index; ++_start; } CookieToken token = CookieToken.End; int increment = 1; if (!Eof) { if (_tokenStream[_index] == '"') { Quoted = true; ++_index; bool quoteOn = false; while (_index < _length) { char currChar = _tokenStream[_index]; if (!quoteOn && currChar == '"') { break; } if (quoteOn) { quoteOn = false; } else if (currChar == '\\') { quoteOn = true; } ++_index; } if (_index < _length) { ++_index; } _tokenLength = _index - _start; increment = 0; // If we are here, reset ignoreComma. // In effect, we ignore everything after quoted string until the next delimiter. ignoreComma = false; } while ((_index < _length) && (_tokenStream[_index] != ';') && (ignoreEquals || (_tokenStream[_index] != '=')) && (ignoreComma || (_tokenStream[_index] != ','))) { // Fixing 2 things: // 1) ignore day of week in cookie string // 2) revert ignoreComma once meet it, so won't miss the next cookie) if (_tokenStream[_index] == ',') { _start = _index + 1; _tokenLength = -1; ignoreComma = false; } ++_index; _tokenLength += increment; } if (!Eof) { switch (_tokenStream[_index]) { case ';': token = CookieToken.EndToken; break; case '=': token = CookieToken.Equals; break; default: _cookieLength = _index - _cookieStartIndex; token = CookieToken.EndCookie; break; } ++_index; } if (Eof) { _cookieLength = _index - _cookieStartIndex; } } return token; } // Next // // Get the next cookie name/value or attribute // // Cookies come in the following formats: // // 1. Version0 // Set-Cookie: [<name>][=][<value>] // [; expires=<date>] // [; path=<path>] // [; domain=<domain>] // [; secure] // Cookie: <name>=<value> // // Notes: <name> and/or <value> may be blank // <date> is the RFC 822/1123 date format that // incorporates commas, e.g. // "Wednesday, 09-Nov-99 23:12:40 GMT" // // 2. RFC 2109 // Set-Cookie: 1#{ // <name>=<value> // [; comment=<comment>] // [; domain=<domain>] // [; max-age=<seconds>] // [; path=<path>] // [; secure] // ; Version=<version> // } // Cookie: $Version=<version> // 1#{ // ; <name>=<value> // [; path=<path>] // [; domain=<domain>] // } // // 3. RFC 2965 // Set-Cookie2: 1#{ // <name>=<value> // [; comment=<comment>] // [; commentURL=<comment>] // [; discard] // [; domain=<domain>] // [; max-age=<seconds>] // [; path=<path>] // [; ports=<portlist>] // [; secure] // ; Version=<version> // } // Cookie: $Version=<version> // 1#{ // ; <name>=<value> // [; path=<path>] // [; domain=<domain>] // [; port="<port>"] // } // [Cookie2: $Version=<version>] // // Inputs: // <argument> first // true if this is the first name/attribute that we have looked for // in the cookie stream // // Outputs: // // Assumes: // Nothing // // Returns: // type of CookieToken found: // // - Attribute // - token was single-value. May be empty. Caller should check // Eof or EndCookie to determine if any more action needs to // be taken // // - NameValuePair // - Name and Value are meaningful. Either may be empty // // Throws: // Nothing internal CookieToken Next(bool first, bool parseResponseCookies) { Reset(); if (first) { _cookieStartIndex = _index; _cookieLength = 0; } CookieToken terminator = FindNext(false, false); if (terminator == CookieToken.EndCookie) { EndOfCookie = true; } if ((terminator == CookieToken.End) || (terminator == CookieToken.EndCookie)) { if ((Name = Extract()).Length != 0) { Token = TokenFromName(parseResponseCookies); return CookieToken.Attribute; } return terminator; } Name = Extract(); if (first) { Token = CookieToken.CookieName; } else { Token = TokenFromName(parseResponseCookies); } if (terminator == CookieToken.Equals) { terminator = FindNext(!first && (Token == CookieToken.Expires), true); if (terminator == CookieToken.EndCookie) { EndOfCookie = true; } Value = Extract(); return CookieToken.NameValuePair; } else { return CookieToken.Attribute; } } // Reset // // Sets this tokenizer up for finding the next name/value pair, // attribute, or end-of-{token,cookie,line}. internal void Reset() { _eofCookie = false; _name = string.Empty; _quoted = false; _start = _index; _token = CookieToken.Nothing; _tokenLength = 0; _value = string.Empty; } private struct RecognizedAttribute { private string _name; private CookieToken _token; internal RecognizedAttribute(string name, CookieToken token) { _name = name; _token = token; } internal CookieToken Token { get { return _token; } } internal bool IsEqualTo(string value) { return string.Equals(_name, value, StringComparison.OrdinalIgnoreCase); } } // Recognized attributes in order of expected frequency. private static readonly RecognizedAttribute[] s_recognizedAttributes = { new RecognizedAttribute(CookieFields.PathAttributeName, CookieToken.Path), new RecognizedAttribute(CookieFields.MaxAgeAttributeName, CookieToken.MaxAge), new RecognizedAttribute(CookieFields.ExpiresAttributeName, CookieToken.Expires), new RecognizedAttribute(CookieFields.VersionAttributeName, CookieToken.Version), new RecognizedAttribute(CookieFields.DomainAttributeName, CookieToken.Domain), new RecognizedAttribute(CookieFields.SecureAttributeName, CookieToken.Secure), new RecognizedAttribute(CookieFields.DiscardAttributeName, CookieToken.Discard), new RecognizedAttribute(CookieFields.PortAttributeName, CookieToken.Port), new RecognizedAttribute(CookieFields.CommentAttributeName, CookieToken.Comment), new RecognizedAttribute(CookieFields.CommentUrlAttributeName, CookieToken.CommentUrl), new RecognizedAttribute(CookieFields.HttpOnlyAttributeName, CookieToken.HttpOnly), }; private static readonly RecognizedAttribute[] s_recognizedServerAttributes = { new RecognizedAttribute('$' + CookieFields.PathAttributeName, CookieToken.Path), new RecognizedAttribute('$' + CookieFields.VersionAttributeName, CookieToken.Version), new RecognizedAttribute('$' + CookieFields.DomainAttributeName, CookieToken.Domain), new RecognizedAttribute('$' + CookieFields.PortAttributeName, CookieToken.Port), new RecognizedAttribute('$' + CookieFields.HttpOnlyAttributeName, CookieToken.HttpOnly), }; internal CookieToken TokenFromName(bool parseResponseCookies) { if (!parseResponseCookies) { for (int i = 0; i < s_recognizedServerAttributes.Length; ++i) { if (s_recognizedServerAttributes[i].IsEqualTo(Name)) { return s_recognizedServerAttributes[i].Token; } } } else { for (int i = 0; i < s_recognizedAttributes.Length; ++i) { if (s_recognizedAttributes[i].IsEqualTo(Name)) { return s_recognizedAttributes[i].Token; } } } return CookieToken.Unknown; } } // CookieParser // // Takes a cookie header, makes cookies. internal class CookieParser { private CookieTokenizer _tokenizer; private Cookie _savedCookie; internal CookieParser(string cookieString) { _tokenizer = new CookieTokenizer(cookieString); } #if SYSTEM_NET_PRIMITIVES_DLL private static bool InternalSetNameMethod(Cookie cookie, string value) { return cookie.InternalSetName(value); } #else private static Func<Cookie, string, bool> s_internalSetNameMethod; private static Func<Cookie, string, bool> InternalSetNameMethod { get { if (s_internalSetNameMethod == null) { // TODO: #13607 // We need to use Cookie.InternalSetName instead of the Cookie.set_Name wrapped in a try catch block, as // Cookie.set_Name keeps the original name if the string is empty or null. // Unfortunately this API is internal so we use reflection to access it. The method is cached for performance reasons. BindingFlags flags = BindingFlags.Instance; #if uap flags |= BindingFlags.Public; #else flags |= BindingFlags.NonPublic; #endif MethodInfo method = typeof(Cookie).GetMethod("InternalSetName", flags); Debug.Assert(method != null, "We need to use an internal method named InternalSetName that is declared on Cookie."); s_internalSetNameMethod = (Func<Cookie, string, bool>)Delegate.CreateDelegate(typeof(Func<Cookie, string, bool>), method); } return s_internalSetNameMethod; } } #endif private static FieldInfo s_isQuotedDomainField = null; private static FieldInfo IsQuotedDomainField { get { if (s_isQuotedDomainField == null) { // TODO: #13607 BindingFlags flags = BindingFlags.Instance; #if uap flags |= BindingFlags.Public; #else flags |= BindingFlags.NonPublic; #endif FieldInfo field = typeof(Cookie).GetField("IsQuotedDomain", flags); Debug.Assert(field != null, "We need to use an internal field named IsQuotedDomain that is declared on Cookie."); s_isQuotedDomainField = field; } return s_isQuotedDomainField; } } private static FieldInfo s_isQuotedVersionField = null; private static FieldInfo IsQuotedVersionField { get { if (s_isQuotedVersionField == null) { // TODO: #13607 BindingFlags flags = BindingFlags.Instance; #if uap flags |= BindingFlags.Public; #else flags |= BindingFlags.NonPublic; #endif FieldInfo field = typeof(Cookie).GetField("IsQuotedVersion", flags); Debug.Assert(field != null, "We need to use an internal field named IsQuotedVersion that is declared on Cookie."); s_isQuotedVersionField = field; } return s_isQuotedVersionField; } } // Get // // Gets the next cookie or null if there are no more cookies. internal Cookie Get() { Cookie cookie = null; // Only the first occurrence of an attribute value must be counted. bool commentSet = false; bool commentUriSet = false; bool domainSet = false; bool expiresSet = false; bool pathSet = false; bool portSet = false; // Special case: may have no value in header. bool versionSet = false; bool secureSet = false; bool discardSet = false; do { CookieToken token = _tokenizer.Next(cookie == null, true); if (cookie == null && (token == CookieToken.NameValuePair || token == CookieToken.Attribute)) { cookie = new Cookie(); InternalSetNameMethod(cookie, _tokenizer.Name); cookie.Value = _tokenizer.Value; } else { switch (token) { case CookieToken.NameValuePair: switch (_tokenizer.Token) { case CookieToken.Comment: if (!commentSet) { commentSet = true; cookie.Comment = _tokenizer.Value; } break; case CookieToken.CommentUrl: if (!commentUriSet) { commentUriSet = true; if (Uri.TryCreate(CheckQuoted(_tokenizer.Value), UriKind.Absolute, out Uri parsed)) { cookie.CommentUri = parsed; } } break; case CookieToken.Domain: if (!domainSet) { domainSet = true; cookie.Domain = CheckQuoted(_tokenizer.Value); IsQuotedDomainField.SetValue(cookie, _tokenizer.Quoted); } break; case CookieToken.Expires: if (!expiresSet) { expiresSet = true; if (DateTime.TryParse(CheckQuoted(_tokenizer.Value), CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out DateTime expires)) { cookie.Expires = expires; } else { // This cookie will be rejected InternalSetNameMethod(cookie, string.Empty); } } break; case CookieToken.MaxAge: if (!expiresSet) { expiresSet = true; if (int.TryParse(CheckQuoted(_tokenizer.Value), out int parsed)) { cookie.Expires = DateTime.Now.AddSeconds(parsed); } else { // This cookie will be rejected InternalSetNameMethod(cookie, string.Empty); } } break; case CookieToken.Path: if (!pathSet) { pathSet = true; cookie.Path = _tokenizer.Value; } break; case CookieToken.Port: if (!portSet) { portSet = true; try { cookie.Port = _tokenizer.Value; } catch { // This cookie will be rejected InternalSetNameMethod(cookie, string.Empty); } } break; case CookieToken.Version: if (!versionSet) { versionSet = true; int parsed; if (int.TryParse(CheckQuoted(_tokenizer.Value), out parsed)) { cookie.Version = parsed; IsQuotedVersionField.SetValue(cookie, _tokenizer.Quoted); } else { // This cookie will be rejected InternalSetNameMethod(cookie, string.Empty); } } break; } break; case CookieToken.Attribute: switch (_tokenizer.Token) { case CookieToken.Discard: if (!discardSet) { discardSet = true; cookie.Discard = true; } break; case CookieToken.Secure: if (!secureSet) { secureSet = true; cookie.Secure = true; } break; case CookieToken.HttpOnly: cookie.HttpOnly = true; break; case CookieToken.Port: if (!portSet) { portSet = true; cookie.Port = string.Empty; } break; } break; } } } while (!_tokenizer.Eof && !_tokenizer.EndOfCookie); return cookie; } internal Cookie GetServer() { Cookie cookie = _savedCookie; _savedCookie = null; // Only the first occurrence of an attribute value must be counted. bool domainSet = false; bool pathSet = false; bool portSet = false; // Special case: may have no value in header. do { bool first = cookie == null || string.IsNullOrEmpty(cookie.Name); CookieToken token = _tokenizer.Next(first, false); if (first && (token == CookieToken.NameValuePair || token == CookieToken.Attribute)) { if (cookie == null) { cookie = new Cookie(); } InternalSetNameMethod(cookie, _tokenizer.Name); cookie.Value = _tokenizer.Value; } else { switch (token) { case CookieToken.NameValuePair: switch (_tokenizer.Token) { case CookieToken.Domain: if (!domainSet) { domainSet = true; cookie.Domain = CheckQuoted(_tokenizer.Value); IsQuotedDomainField.SetValue(cookie, _tokenizer.Quoted); } break; case CookieToken.Path: if (!pathSet) { pathSet = true; cookie.Path = _tokenizer.Value; } break; case CookieToken.Port: if (!portSet) { portSet = true; try { cookie.Port = _tokenizer.Value; } catch (CookieException) { // This cookie will be rejected InternalSetNameMethod(cookie, string.Empty); } } break; case CookieToken.Version: // this is a new cookie, this token is for the next cookie. _savedCookie = new Cookie(); if (int.TryParse(_tokenizer.Value, out int parsed)) { _savedCookie.Version = parsed; } return cookie; case CookieToken.Unknown: // this is a new cookie, the token is for the next cookie. _savedCookie = new Cookie(); InternalSetNameMethod(_savedCookie, _tokenizer.Name); _savedCookie.Value = _tokenizer.Value; return cookie; } break; case CookieToken.Attribute: if (_tokenizer.Token == CookieToken.Port && !portSet) { portSet = true; cookie.Port = string.Empty; } break; } } } while (!_tokenizer.Eof && !_tokenizer.EndOfCookie); return cookie; } internal static string CheckQuoted(string value) { if (value.Length < 2 || value[0] != '\"' || value[value.Length - 1] != '\"') return value; return value.Length == 2 ? string.Empty : value.Substring(1, value.Length - 2); } internal bool EndofHeader() { return _tokenizer.Eof; } } }
//----------------------------------------------------------------------------- // Verve // Copyright (C) - Violent Tulip //----------------------------------------------------------------------------- singleton GuiControlProfile( VEditorDefaultProfile ) { opaque = true; fillColor = "70 70 70"; fillColorHL = "90 90 90"; fillColorNA = "70 70 70"; border = 1; borderColor = "120 120 120"; borderColorHL = "100 100 100"; borderColorNA = "240 240 240"; fontType = "Arial"; fontSize = 12; fontCharset = ANSI; fontColor = "255 255 255"; fontColorHL = "255 255 255"; fontColorNA = "255 255 255"; fontColorSEL = "255 255 255"; }; singleton GuiControlProfile( VEditorTestProfile ) { opaque = true; fillColor = "255 255 0"; fillColorHL = "255 255 0"; fillColorNA = "255 255 0"; }; singleton GuiControlProfile( VEditorNoFillProfile : VEditorDefaultProfile ) { opaque = false; }; singleton GuiControlProfile( VEditorNoBorderProfile : VEditorDefaultProfile ) { border = false; }; singleton GuiControlProfile( VEditorTransparentProfile : VEditorDefaultProfile ) { opaque = false; border = false; }; //----------------------------------------------------------------------------- singleton GuiControlProfile( VEditorTextProfile : VEditorDefaultProfile ) { border = false; opaque = false; fontType = "Arial Bold"; }; singleton GuiControlProfile( VEditorTextEditProfile : VEditorDefaultProfile ) { fillColor = "70 70 70"; fillColorHL = "90 90 90"; fillColorSEL = "0 0 0"; fillColorNA = "70 70 70"; fontColor = "255 255 255"; fontColorHL = "0 0 0"; fontColorSEL = "128 128 128"; fontColorNA = "128 128 128"; textOffset = "4 2"; autoSizeWidth = false; autoSizeHeight = false; justify = "left"; tab = true; canKeyFocus = true; }; singleton GuiControlProfile( VEditorPopupMenuProfile : GuiPopUpMenuProfile ) { FillColorHL = "90 90 90"; FillColorSEL = "0 0 0"; FontColorHL = "255 255 255"; }; singleton GuiControlProfile ( VEditorBitmapButtonProfile : VEditorDefaultProfile ) { justify = "center"; hasBitmapArray = true; bitmap = "./Images/Button"; }; //----------------------------------------------------------------------------- singleton GuiControlProfile( VEditorGroupHeaderProfile : VEditorDefaultProfile ) { CanKeyFocus = true; TextOffset = "23 0"; fontColor = "70 70 70"; }; singleton GuiControlProfile( VEditorGroupHeaderErrorProfile : VEditorGroupHeaderProfile ) { fontColor = "255 70 70"; }; singleton GuiControlProfile( VEditorGroupTrackProfile : VEditorTransparentProfile ) { CanKeyFocus = true; }; singleton GuiControlProfile( VEditorTrackProfile : VEditorDefaultProfile ) { CanKeyFocus = true; TextOffset = "33 0"; opaque = true; fillColor = "255 255 255 15"; fillColorHL = "151 166 191 60"; borderColor = "100 100 100"; }; singleton GuiControlProfile( VEditorTrackErrorProfile : VEditorTrackProfile ) { fontColor = "255 70 70"; }; singleton GuiControlProfile( VEditorEventProfile : VEditorDefaultProfile ) { CanKeyFocus = true; Justify = "left"; TextOffset = "6 1"; fillColor = "81 81 81"; fillColorHL = "102 102 102"; borderColor = "255 255 255"; borderColorHL = "255 255 255"; borderColorNA = "100 100 100"; }; singleton GuiControlProfile( VEditorTimeLineProfile : VEditorDefaultProfile ) { CanKeyFocus = true; opaque = false; fillColorHL = "255 255 255 15"; border = false; borderColor = "100 100 100"; }; singleton GuiControlProfile( VEditorPropertyProfile : VEditorDefaultProfile ) { fillColor = "102 102 102"; }; //----------------------------------------------------------------------------- singleton GuiControlProfile ( VEditorScrollProfile : VEditorDefaultProfile ) { opaque = false; border = false; hasBitmapArray = true; bitmap = "./Images/ScrollBar"; }; singleton GuiControlProfile ( VEditorCheckBoxProfile : GuiCheckBoxProfile ) { // Void. }; //----------------------------------------------------------------------------- singleton GuiControlProfile( VEditorPropertyRolloutProfile : GuiRolloutProfile ) { border = 0; hasBitmapArray = true; bitmap = "./Images/PropertyRollout"; fontType = "Arial"; fontSize = 12; fontCharset = ANSI; fontColor = "255 255 255"; fontColorHL = "255 255 255"; fontColorNA = "255 255 255"; fontColorSEL = "255 255 255"; }; singleton GuiControlProfile( VEditorPropertyLabelProfile : VEditorTextProfile ) { border = "1"; justify = "center"; }; //----------------------------------------------------------------------------- singleton GuiControlProfile( VEditorPreferenceLabelProfile : GuiTextProfile ) { opaque = true; fillColor = "242 241 240"; fillColorHL = "242 241 240"; fillColorNA = "242 241 240"; };
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO.PortsTests; using System.Linq; using System.Text; using System.Threading; using Legacy.Support; using Xunit; namespace System.IO.Ports.Tests { public class ReadExisting_Generic : PortsTest { //Set bounds fore random timeout values. //If the min is to low read will not timeout accurately and the testcase will fail private const int minRandomTimeout = 250; //If the max is to large then the testcase will take forever to run private const int maxRandomTimeout = 2000; //Since ReadExisting should return immediately this is the maximum time in ms that ReadExisting should take //before we consider ReadExisting to be blocking and cause the test case to fail private const double maxTimeout = 50; //The number of random characters to receive private const int numRndChar = 8; private const int NUM_TRYS = 5; #region Test Cases [Fact] public void ReadWithoutOpen() { using (SerialPort com = new SerialPort()) { Debug.WriteLine("Verifying read method throws exception without a call to Open()"); VerifyReadException(com, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void ReadAfterFailedOpen() { using (SerialPort com = new SerialPort("BAD_PORT_NAME")) { Debug.WriteLine("Verifying read method throws exception with a failed call to Open()"); //Since the PortName is set to a bad port name Open will thrown an exception //however we don't care what it is since we are verifying a read method Assert.ThrowsAny<Exception>(() => com.Open()); VerifyReadException(com, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void ReadAfterClose() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying read method throws exception after a call to Cloes()"); com.Open(); com.Close(); VerifyReadException(com, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void Timeout() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout); com.Open(); VerifyTimeout(com); } } [ConditionalFact(nameof(HasOneSerialPort))] public void Default_MaxInt() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { com.ReadTimeout = int.MaxValue; Debug.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout); com.Open(); VerifyTimeout(com); } } [ConditionalFact(nameof(HasOneSerialPort))] public void SuccessiveReadTimeoutNoData() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com.Encoding = Encoding.Unicode; Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout); com.Open(); Assert.Equal("", com.ReadExisting()); VerifyTimeout(com); } } [ConditionalFact(nameof(HasNullModem))] public void DefaultParityReplaceByte() { VerifyParityReplaceByte(-1, numRndChar - 2); } [ConditionalFact(nameof(HasNullModem))] public void NoParityReplaceByte() { Random rndGen = new Random(-55); VerifyParityReplaceByte('\0', rndGen.Next(0, numRndChar - 1)); } [ConditionalFact(nameof(HasNullModem))] public void RNDParityReplaceByte() { Random rndGen = new Random(-55); VerifyParityReplaceByte(rndGen.Next(0, 128), 0); } [ConditionalFact(nameof(HasNullModem))] public void ParityErrorOnLastByte() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(15); byte[] bytesToWrite = new byte[numRndChar]; char[] expectedChars = new char[numRndChar]; /* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */ Debug.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte"); //Genrate random characters without an parity error for (int i = 0; i < bytesToWrite.Length; i++) { byte randByte = (byte)rndGen.Next(0, 128); bytesToWrite[i] = randByte; expectedChars[i] = (char)randByte; } bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80); //Create a parity error on the last byte expectedChars[expectedChars.Length - 1] = (char)com1.ParityReplace; // Set the last expected char to be the ParityReplace Byte com1.Parity = Parity.Space; com1.DataBits = 7; com1.ReadTimeout = 250; com1.Open(); com2.Open(); com2.Write(bytesToWrite, 0, bytesToWrite.Length); TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length); char[] actualChars = (com1.ReadExisting()).ToCharArray(); //Compare the chars that were written with the ones we expected to read Assert.Equal(expectedChars, actualChars.Take(expectedChars.Length).ToArray()); if (1 < com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead); Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]); } com1.DiscardInBuffer(); bytesToWrite[bytesToWrite.Length - 1] = (byte)'\n'; expectedChars[expectedChars.Length - 1] = (char)bytesToWrite[bytesToWrite.Length - 1]; VerifyRead(com1, com2, bytesToWrite, expectedChars); } } #endregion #region Verification for Test Cases private void VerifyTimeout(SerialPort com) { Stopwatch timer = new Stopwatch(); int actualTime = 0; string strReadReturn = com.ReadExisting(); Assert.Equal("", strReadReturn); Thread.CurrentThread.Priority = ThreadPriority.Highest; for (int i = 0; i < NUM_TRYS; i++) { timer.Start(); strReadReturn = com.ReadExisting(); timer.Stop(); Assert.Equal("", strReadReturn); actualTime += (int)timer.ElapsedMilliseconds; timer.Reset(); } Thread.CurrentThread.Priority = ThreadPriority.Normal; actualTime /= NUM_TRYS; //Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference if (maxTimeout < actualTime) { Fail("ERROR!!!: The read method timedout in {0} expected {1}", actualTime, 0); } } private void VerifyReadException(SerialPort com, Type expectedException) { Assert.Throws(expectedException, com.ReadExisting); } private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex) { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); byte[] byteBuffer = new byte[numRndChar]; char[] charBuffer = new char[numRndChar]; int expectedChar; //Genrate random characters without an parity error for (int i = 0; i < byteBuffer.Length; i++) { int randChar = rndGen.Next(0, 128); byteBuffer[i] = (byte)randChar; charBuffer[i] = (char)randChar; } if (-1 == parityReplace) { //If parityReplace is -1 and we should just use the default value expectedChar = com1.ParityReplace; } else if ('\0' == parityReplace) { //If parityReplace is the null charachater and parity replacement should not occur com1.ParityReplace = (byte)parityReplace; expectedChar = charBuffer[parityErrorIndex]; } else { //Else parityReplace was set to a value and we should expect this value to be returned on a parity error com1.ParityReplace = (byte)parityReplace; expectedChar = parityReplace; } //Create an parity error by setting the highest order bit to true byteBuffer[parityErrorIndex] = (byte)(byteBuffer[parityErrorIndex] | 0x80); charBuffer[parityErrorIndex] = (char)expectedChar; Debug.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace, parityErrorIndex); com1.Parity = Parity.Space; com1.DataBits = 7; com1.Open(); com2.Open(); VerifyRead(com1, com2, byteBuffer, charBuffer); } } private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars) { char[] buffer = new char[expectedChars.Length]; int totalBytesRead; int totalCharsRead; com2.Write(bytesToWrite, 0, bytesToWrite.Length); com1.ReadTimeout = 250; TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length); totalBytesRead = 0; totalCharsRead = 0; Stopwatch sw = Stopwatch.StartNew(); while (0 != com1.BytesToRead) { //While their are more characters to be read string rcvString = com1.ReadExisting(); char[] rcvBuffer = rcvString.ToCharArray(); int charsRead = rcvBuffer.Length; int bytesRead = com1.Encoding.GetByteCount(rcvBuffer, 0, charsRead); if (expectedChars.Length < totalCharsRead + charsRead) { //If we have read in more characters then we expect Fail("ERROR!!!: We have received more characters then were sent"); } Array.Copy(rcvBuffer, 0, buffer, totalCharsRead, charsRead); totalBytesRead += bytesRead; totalCharsRead += charsRead; if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead); } Assert.True(sw.ElapsedMilliseconds < 5000, "Timeout waiting for read data"); } //Compare the chars that were written with the ones we expected to read Assert.Equal(expectedChars, buffer); } #endregion } }
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel // // 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.Runtime.InteropServices; namespace SharpDX.DirectWrite { public partial class TextAnalyzer { /// <summary> /// Returns an interface for performing text analysis. /// </summary> /// <param name="factory">A reference to a DirectWrite factory <see cref="Factory"/></param> /// <unmanaged>HRESULT IDWriteFactory::CreateTextAnalyzer([Out] IDWriteTextAnalyzer** textAnalyzer)</unmanaged> public TextAnalyzer(Factory factory) { factory.CreateTextAnalyzer(this); } /// <summary> /// Analyzes a text range for script boundaries, reading text attributes from the source and reporting the Unicode script ID to the sink callback {{SetScript}}. /// </summary> /// <param name="analysisSource">A reference to the source object to analyze.</param> /// <param name="textPosition">The starting text position within the source object.</param> /// <param name="textLength">The text length to analyze.</param> /// <param name="analysisSink">A reference to the sink callback object that receives the text analysis.</param> /// <returns> /// If the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code. /// </returns> /// <unmanaged>HRESULT IDWriteTextAnalyzer::AnalyzeScript([None] IDWriteTextAnalysisSource* analysisSource,[None] int textPosition,[None] int textLength,[None] IDWriteTextAnalysisSink* analysisSink)</unmanaged> public void AnalyzeScript(TextAnalysisSource analysisSource, int textPosition, int textLength, TextAnalysisSink analysisSink) { AnalyzeScript__(TextAnalysisSourceShadow.ToIntPtr(analysisSource), textPosition, textLength, TextAnalysisSinkShadow.ToIntPtr(analysisSink)); } /// <summary> /// Analyzes a text range for script directionality, reading attributes from the source and reporting levels to the sink callback {{SetBidiLevel}}. /// </summary> /// <param name="analysisSource">A reference to a source object to analyze.</param> /// <param name="textPosition">The starting text position within the source object.</param> /// <param name="textLength">The text length to analyze.</param> /// <param name="analysisSink">A reference to the sink callback object that receives the text analysis.</param> /// <returns> /// If the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code. /// </returns> /// <unmanaged>HRESULT IDWriteTextAnalyzer::AnalyzeBidi([None] IDWriteTextAnalysisSource* analysisSource,[None] int textPosition,[None] int textLength,[None] IDWriteTextAnalysisSink* analysisSink)</unmanaged> /// <remarks> /// While the function can handle multiple paragraphs, the text range should not arbitrarily split the middle of paragraphs. Otherwise, the returned levels may be wrong, because the Bidi algorithm is meant to apply to the paragraph as a whole. /// </remarks> public void AnalyzeBidi(TextAnalysisSource analysisSource, int textPosition, int textLength, TextAnalysisSink analysisSink) { AnalyzeBidi__(TextAnalysisSourceShadow.ToIntPtr(analysisSource), textPosition, textLength, TextAnalysisSinkShadow.ToIntPtr(analysisSink)); } /// <summary> /// Analyzes a text range for spans where number substitution is applicable, reading attributes from the source and reporting substitutable ranges to the sink callback {{SetNumberSubstitution}}. /// </summary> /// <param name="analysisSource">The source object to analyze.</param> /// <param name="textPosition">The starting position within the source object.</param> /// <param name="textLength">The length to analyze.</param> /// <param name="analysisSink">A reference to the sink callback object that receives the text analysis.</param> /// <returns> /// If the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code. /// </returns> /// <unmanaged>HRESULT IDWriteTextAnalyzer::AnalyzeNumberSubstitution([None] IDWriteTextAnalysisSource* analysisSource,[None] int textPosition,[None] int textLength,[None] IDWriteTextAnalysisSink* analysisSink)</unmanaged> /// <remarks> /// Although the function can handle multiple ranges of differing number substitutions, the text ranges should not arbitrarily split the middle of numbers. Otherwise, it will treat the numbers separately and will not translate any intervening punctuation. /// </remarks> public void AnalyzeNumberSubstitution(TextAnalysisSource analysisSource, int textPosition, int textLength, TextAnalysisSink analysisSink) { AnalyzeNumberSubstitution__(TextAnalysisSourceShadow.ToIntPtr(analysisSource), textPosition, textLength, TextAnalysisSinkShadow.ToIntPtr(analysisSink)); } /// <summary> /// Analyzes a text range for potential breakpoint opportunities, reading attributes from the source and reporting breakpoint opportunities to the sink callback {{SetLineBreakpoints}}. /// </summary> /// <param name="analysisSource">A reference to the source object to analyze.</param> /// <param name="textPosition">The starting text position within the source object.</param> /// <param name="textLength">The text length to analyze.</param> /// <param name="analysisSink">A reference to the sink callback object that receives the text analysis.</param> /// <returns> /// If the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code. /// </returns> /// <unmanaged>HRESULT IDWriteTextAnalyzer::AnalyzeLineBreakpoints([None] IDWriteTextAnalysisSource* analysisSource,[None] int textPosition,[None] int textLength,[None] IDWriteTextAnalysisSink* analysisSink)</unmanaged> /// <remarks> /// Although the function can handle multiple paragraphs, the text range should not arbitrarily split the middle of paragraphs, unless the specified text span is considered a whole unit. Otherwise, the returned properties for the first and last characters will inappropriately allow breaks. /// </remarks> public void AnalyzeLineBreakpoints(TextAnalysisSource analysisSource, int textPosition, int textLength, TextAnalysisSink analysisSink) { AnalyzeLineBreakpoints__(TextAnalysisSourceShadow.ToIntPtr(analysisSource), textPosition, textLength, TextAnalysisSinkShadow.ToIntPtr(analysisSink)); } /// <summary> /// Gets the glyphs (TODO doc) /// </summary> /// <param name="textString">The text string.</param> /// <param name="textLength">Length of the text.</param> /// <param name="fontFace">The font face.</param> /// <param name="isSideways">if set to <c>true</c> [is sideways].</param> /// <param name="isRightToLeft">if set to <c>true</c> [is right to left].</param> /// <param name="scriptAnalysis">The script analysis.</param> /// <param name="localeName">Name of the locale.</param> /// <param name="numberSubstitution">The number substitution.</param> /// <param name="features">The features.</param> /// <param name="featureRangeLengths">The feature range lengths.</param> /// <param name="maxGlyphCount">The max glyph count.</param> /// <param name="clusterMap">The cluster map.</param> /// <param name="textProps">The text props.</param> /// <param name="glyphIndices">The glyph indices.</param> /// <param name="glyphProps">The glyph props.</param> /// <param name="actualGlyphCount">The actual glyph count.</param> /// <returns> /// If the method succeeds, it returns <see cref="Result.Ok"/>. /// </returns> /// <unmanaged>HRESULT IDWriteTextAnalyzer::GetGlyphs([In, Buffer] const wchar_t* textString,[In] unsigned int textLength,[In] IDWriteFontFace* fontFace,[In] BOOL isSideways,[In] BOOL isRightToLeft,[In] const DWRITE_SCRIPT_ANALYSIS* scriptAnalysis,[In, Buffer, Optional] const wchar_t* localeName,[In, Optional] IDWriteNumberSubstitution* numberSubstitution,[In, Optional] const void** features,[In, Buffer, Optional] const unsigned int* featureRangeLengths,[In] unsigned int featureRanges,[In] unsigned int maxGlyphCount,[Out, Buffer] unsigned short* clusterMap,[Out, Buffer] DWRITE_SHAPING_TEXT_PROPERTIES* textProps,[Out, Buffer] unsigned short* glyphIndices,[Out, Buffer] DWRITE_SHAPING_GLYPH_PROPERTIES* glyphProps,[Out] unsigned int* actualGlyphCount)</unmanaged> public void GetGlyphs(string textString, int textLength, SharpDX.DirectWrite.FontFace fontFace, bool isSideways, bool isRightToLeft, SharpDX.DirectWrite.ScriptAnalysis scriptAnalysis, string localeName, SharpDX.DirectWrite.NumberSubstitution numberSubstitution, FontFeature[][] features, int[] featureRangeLengths, int maxGlyphCount, short[] clusterMap, SharpDX.DirectWrite.ShapingTextProperties[] textProps, short[] glyphIndices, SharpDX.DirectWrite.ShapingGlyphProperties[] glyphProps, out int actualGlyphCount) { var pFeatures = AllocateFeatures(features); try { GetGlyphs( textString, textLength, fontFace, isSideways, isRightToLeft, scriptAnalysis, localeName, numberSubstitution, pFeatures, featureRangeLengths, featureRangeLengths == null ? 0 : featureRangeLengths.Length, maxGlyphCount, clusterMap, textProps, glyphIndices, glyphProps, out actualGlyphCount); } finally { if (pFeatures != IntPtr.Zero) Marshal.FreeHGlobal(pFeatures); } } /// <summary> /// Gets the glyph placements. /// </summary> /// <param name="textString">The text string.</param> /// <param name="clusterMap">The cluster map.</param> /// <param name="textProps">The text props.</param> /// <param name="textLength">Length of the text.</param> /// <param name="glyphIndices">The glyph indices.</param> /// <param name="glyphProps">The glyph props.</param> /// <param name="glyphCount">The glyph count.</param> /// <param name="fontFace">The font face.</param> /// <param name="fontEmSize">Size of the font in ems.</param> /// <param name="isSideways">if set to <c>true</c> [is sideways].</param> /// <param name="isRightToLeft">if set to <c>true</c> [is right to left].</param> /// <param name="scriptAnalysis">The script analysis.</param> /// <param name="localeName">Name of the locale.</param> /// <param name="features">The features.</param> /// <param name="featureRangeLengths">The feature range lengths.</param> /// <param name="glyphAdvances">The glyph advances.</param> /// <param name="glyphOffsets">The glyph offsets.</param> /// <returns> /// If the method succeeds, it returns <see cref="Result.Ok"/>. /// </returns> /// <unmanaged>HRESULT IDWriteTextAnalyzer::GetGlyphPlacements([In, Buffer] const wchar_t* textString,[In, Buffer] const unsigned short* clusterMap,[In, Buffer] DWRITE_SHAPING_TEXT_PROPERTIES* textProps,[In] unsigned int textLength,[In, Buffer] const unsigned short* glyphIndices,[In, Buffer] const DWRITE_SHAPING_GLYPH_PROPERTIES* glyphProps,[In] unsigned int glyphCount,[In] IDWriteFontFace* fontFace,[In] float fontEmSize,[In] BOOL isSideways,[In] BOOL isRightToLeft,[In] const DWRITE_SCRIPT_ANALYSIS* scriptAnalysis,[In, Buffer, Optional] const wchar_t* localeName,[In, Optional] const void** features,[In, Buffer, Optional] const unsigned int* featureRangeLengths,[In] unsigned int featureRanges,[Out, Buffer] float* glyphAdvances,[Out, Buffer] DWRITE_GLYPH_OFFSET* glyphOffsets)</unmanaged> public void GetGlyphPlacements(string textString, short[] clusterMap, SharpDX.DirectWrite.ShapingTextProperties[] textProps, int textLength, short[] glyphIndices, SharpDX.DirectWrite.ShapingGlyphProperties[] glyphProps, int glyphCount, SharpDX.DirectWrite.FontFace fontFace, float fontEmSize, bool isSideways, bool isRightToLeft, SharpDX.DirectWrite.ScriptAnalysis scriptAnalysis, string localeName, FontFeature[][] features, int[] featureRangeLengths, float[] glyphAdvances, SharpDX.DirectWrite.GlyphOffset[] glyphOffsets) { var pFeatures = AllocateFeatures(features); try { GetGlyphPlacements( textString, clusterMap, textProps, textLength, glyphIndices, glyphProps, glyphCount, fontFace, fontEmSize, isSideways, isRightToLeft, scriptAnalysis, localeName, pFeatures, featureRangeLengths, featureRangeLengths == null ? 0 : featureRangeLengths.Length, glyphAdvances, glyphOffsets ); } finally { if (pFeatures != IntPtr.Zero) Marshal.FreeHGlobal(pFeatures); } } /// <summary> /// Gets the GDI compatible glyph placements. /// </summary> /// <param name="textString">The text string.</param> /// <param name="clusterMap">The cluster map.</param> /// <param name="textProps">The text props.</param> /// <param name="textLength">Length of the text.</param> /// <param name="glyphIndices">The glyph indices.</param> /// <param name="glyphProps">The glyph props.</param> /// <param name="glyphCount">The glyph count.</param> /// <param name="fontFace">The font face.</param> /// <param name="fontEmSize">Size of the font em.</param> /// <param name="pixelsPerDip">The pixels per dip.</param> /// <param name="transform">The transform.</param> /// <param name="useGdiNatural">if set to <c>true</c> [use GDI natural].</param> /// <param name="isSideways">if set to <c>true</c> [is sideways].</param> /// <param name="isRightToLeft">if set to <c>true</c> [is right to left].</param> /// <param name="scriptAnalysis">The script analysis.</param> /// <param name="localeName">Name of the locale.</param> /// <param name="features">The features.</param> /// <param name="featureRangeLengths">The feature range lengths.</param> /// <param name="glyphAdvances">The glyph advances.</param> /// <param name="glyphOffsets">The glyph offsets.</param> /// <returns> /// If the method succeeds, it returns <see cref="Result.Ok"/>. /// </returns> /// <unmanaged>HRESULT IDWriteTextAnalyzer::GetGdiCompatibleGlyphPlacements([In, Buffer] const wchar_t* textString,[In, Buffer] const unsigned short* clusterMap,[In, Buffer] DWRITE_SHAPING_TEXT_PROPERTIES* textProps,[In] unsigned int textLength,[In, Buffer] const unsigned short* glyphIndices,[In, Buffer] const DWRITE_SHAPING_GLYPH_PROPERTIES* glyphProps,[In] unsigned int glyphCount,[In] IDWriteFontFace* fontFace,[In] float fontEmSize,[In] float pixelsPerDip,[In, Optional] const DWRITE_MATRIX* transform,[In] BOOL useGdiNatural,[In] BOOL isSideways,[In] BOOL isRightToLeft,[In] const DWRITE_SCRIPT_ANALYSIS* scriptAnalysis,[In, Buffer, Optional] const wchar_t* localeName,[In, Optional] const void** features,[In, Buffer, Optional] const unsigned int* featureRangeLengths,[In] unsigned int featureRanges,[Out, Buffer] float* glyphAdvances,[Out, Buffer] DWRITE_GLYPH_OFFSET* glyphOffsets)</unmanaged> public void GetGdiCompatibleGlyphPlacements(string textString, short[] clusterMap, SharpDX.DirectWrite.ShapingTextProperties[] textProps, int textLength, short[] glyphIndices, SharpDX.DirectWrite.ShapingGlyphProperties[] glyphProps, int glyphCount, SharpDX.DirectWrite.FontFace fontFace, float fontEmSize, float pixelsPerDip, Matrix3x2? transform, bool useGdiNatural, bool isSideways, bool isRightToLeft, SharpDX.DirectWrite.ScriptAnalysis scriptAnalysis, string localeName, FontFeature[][] features, int[] featureRangeLengths, float[] glyphAdvances, SharpDX.DirectWrite.GlyphOffset[] glyphOffsets) { var pFeatures = AllocateFeatures(features); try { GetGdiCompatibleGlyphPlacements( textString, clusterMap, textProps, textLength, glyphIndices, glyphProps, glyphCount, fontFace, fontEmSize, pixelsPerDip, transform, useGdiNatural, isSideways, isRightToLeft, scriptAnalysis, localeName, pFeatures, featureRangeLengths, featureRangeLengths == null ? 0 : featureRangeLengths.Length, glyphAdvances, glyphOffsets ); } finally { if (pFeatures != IntPtr.Zero) Marshal.FreeHGlobal(pFeatures); } } /// <summary> /// Allocates the features from the jagged array.. /// </summary> /// <param name="features">The features.</param> /// <returns>A pointer to the allocated native features or 0 if features is null or empty.</returns> private static IntPtr AllocateFeatures(FontFeature[][] features) { unsafe { var pFeatures = (byte*)0; if (features != null && features.Length > 0) { // Calculate the total size of the buffer to allocate: // (0) (1) (2) // ------------------------------------------------------------- // | array | TypographicFeatures || FontFeatures || // | ptr to (1) | | | || || // | | ptr to FontFeatures || || // ------------------------------------------------------------- // Offset in bytes to (1) int offsetToTypographicFeatures = sizeof(IntPtr) * features.Length; // Add offset (1) and Size in bytes to (1) int calcSize = offsetToTypographicFeatures + sizeof(TypographicFeatures) * features.Length; // Calculate size (2) foreach (var fontFeature in features) { if (fontFeature == null) throw new ArgumentNullException("features", "FontFeature[] inside features array cannot be null."); // calcSize += typographicFeatures.Length * sizeof(FontFeature) calcSize += sizeof(FontFeature) * fontFeature.Length; } // Allocate the whole buffer pFeatures = (byte*)Marshal.AllocHGlobal(calcSize); // Pointer to (1) var pTypographicFeatures = (TypographicFeatures*)(pFeatures + offsetToTypographicFeatures); // Pointer to (2) var pFontFeatures = (FontFeature*)(pTypographicFeatures + features.Length); // Iterate on features and copy them to (2) for (int i = 0; i < features.Length; i++) { // Write array pointers in (0) ((void**)pFeatures)[i] = pTypographicFeatures; var featureSet = features[i]; // Write TypographicFeatures in (1) pTypographicFeatures->Features = (IntPtr)pFontFeatures; pTypographicFeatures->FeatureCount = featureSet.Length; pTypographicFeatures++; // Write FontFeatures in (2) for (int j = 0; j < featureSet.Length; j++) { *pFontFeatures = featureSet[j]; pFontFeatures++; } } } return (IntPtr)pFeatures; } } } }
// 2017-11-09 // // This works more or less, but the defintion is ambiguous. // Are uncancelled duplicates allowed? // Limit this to only one digit, or more? // This only considers a single digit that may occur more than once. That means // - There is no way to consider multiple cancellations at the same time. // For instance, can't cancel the 2 and 3 in xxx2xx3xx / x23xxxxxx at the same time // - In the same way, two digit or more numbers can't be cancelled. For instance, // can't cancel the 23 in x23 / 23x // http://mathworld.wolfram.com/AnomalousCancellation.html int min = 100; int max = 1000; int totalCount = 0; for (int num = min; num <= max; num++) { for (int den = min; den < num; den++) { if (num == den) { continue; } var numDigits = num.ToString().Select(x => x.ToString()); var denDigits = den.ToString().Select(x => x.ToString()); var distinct = numDigits.Distinct(); foreach (var digit in distinct) { // If digit is zero if (digit == "0") { continue; } // If there's nothing to cancel. if (!denDigits.Contains(digit)) { continue; } // If there are not equal number of the digit to cancel. var numCancelCount = numDigits.Where(x => x == digit).Count(); var denCancelCount = denDigits.Where(x => x == digit).Count(); if (numCancelCount != denCancelCount /* || numCancelCount != 1*/) { continue; } //// If this is dividing by 10. //if (digit == "0" && numDigits.Last() == "0" && denDigits.Last() == "0") //{ // continue; //} // var newNumComb = numDigits.Select((x,i) => Tuple.Create(x,i)).Where(x => x.Item1 != digit); var newDenComb = denDigits.Select((x,i) => Tuple.Create(x,i)).Where(x => x.Item1 != digit); var newNumDigits = newNumComb.Select(x => x.Item1); var newDenDigits = newDenComb.Select(x => x.Item1); var newNumIndeces = newNumComb.Select(x => x.Item2); var newDenIndeces = newDenComb.Select(x => x.Item2); // If the indeces for the cancelled digits are the same in the numerator and denominator. //if (newNumIndeces.SequenceEqual(newDenIndeces)) //{ // continue; //} //var newNumDigits = numDigits.Where(x => x != digit); //var newDenDigits = denDigits.Where(x => x != digit); // If everything got cancelled in the numerator or denominator. if (newNumDigits.Count() == 0 || newDenDigits.Count() == 0) { continue; } //// If there are still overlapping digits that have not been cancelled. //if (newNumDigits.Intersect(newDenDigits).Any()) //{ // continue; //} var newNum = int.Parse(String.Join(String.Empty, newNumDigits)); var newDen = int.Parse(String.Join(String.Empty, newDenDigits)); // If it got simplified to zero. if (newNum == 0 || newDen == 0) { continue; } var lhs = num * newDen; var rhs = newNum * den; if (lhs == rhs) { totalCount++; Console.WriteLine($"Cancel {digit}: {num} / {den} == {newNum} / {newDen}"); } } } } Console.WriteLine($"TotalCount: {totalCount}"); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Update // // This will consider any substring as a factor. For example "1234" will have factors {1, 2, 3, 4, 12, 23, 34, 123, 234}. // // However, I think this is not enough, which is why this count is still wrong. From the mathworld page, // there is 1019 / 5095 = 11 / 55 which I can not consider at all. public void CountAnomalousCancellation(int min, int max) { int totalCount = 0; for (int num = min; num <= max; num++) { var numDivisors = GetDivisors(num); if (numDivisors.Contains(2) && numDivisors.Contains(5)) { continue; } for (int den = num + 1; den < max; den++) { var numString = num.ToString(); var denString = den.ToString(); foreach (var factor in ProperSubstrings(denString)) { var f = int.Parse(factor); if (f == 0 || f % 10 == 0) { continue; } var denDivisors = GetDivisors(den); if (numDivisors.Contains(f) || denDivisors.Contains(f)) { continue; } if (denDivisors.Contains(2) && denDivisors.Contains(5)) { continue; } // If there's nothing to factor. if (!numString.Contains(factor)) { continue; } var newNumString = numString.ReplaceFirst(factor, String.Empty); var newDenString = denString.ReplaceFirst(factor, String.Empty); // If the factor appears multiple times. if (newNumString.Contains(factor) || newDenString.Contains(factor)) { continue; } if (string.IsNullOrWhiteSpace(newNumString) || string.IsNullOrWhiteSpace(newDenString)) { continue; } var newNum = int.Parse(newNumString); var newDen = int.Parse(newDenString); // If the result got factored to nothing. if (newNum == 0 || newDen == 0) { continue; } var lhs = num * newDen; var rhs = newNum * den; if (lhs == rhs) { Console.WriteLine($"Cancel {factor}: {num} / {den} == {newNum} / {newDen}"); totalCount++; } } } } Console.WriteLine($"TotalCount: {totalCount}"); } public IEnumerable<string> ProperSubstrings(string input) { var ret = new List<string>(); if (string.IsNullOrWhiteSpace(input)) { yield break; } int len = input.Length; int maxLength = len - 1; if (maxLength < 1) { yield break; } int position = 0; int currentLength = 1; while (true) { yield return input.Substring(position, currentLength); position++; if (position + currentLength > len) { position = 0; currentLength++; } if (currentLength > maxLength) { break; } } } public static string ReplaceFirst(this string text, string search, string replace) { int pos = text.IndexOf(search); if (pos < 0) { return text; } return text.Substring(0, pos) + replace + text.Substring(pos + search.Length); } public static HashSet<int> Primes = new HashSet<int>(); public static List<int> PrimesList = new List<int>(); public static Dictionary<int, List<int>> DivisorsCash = new Dictionary<int, List<int>>(); public static void BuildPrimes() { Primes.Clear(); PrimesList.Clear(); var max = 10000; var maxs = 100; var arr = Enumerable.Range(0, max).ToArray(); arr[1] = 0; for (int i = 2; i < maxs; i++) { for (int j = i + i; j < max; j += i) { arr[j] = 0; } } foreach (var x in arr) { if (x > 0) { Primes.Add(x); } } PrimesList = Primes.ToList(); } public static List<int> GetDivisors(int input) { if (Primes.Count < 1) { BuildPrimes(); } List<int> ret = null; if (!DivisorsCash.TryGetValue(input, out ret)) { ret = new List<int>(); } else { return ret; } if (Primes.Contains(input)) { ret.Add(input); DivisorsCash[input] = ret; return ret; } var potentialDivisors = PrimesList.Where(x => x < input); foreach (var d in potentialDivisors) { int i; Math.DivRem(input, d, out i); if (i == 0) { ret.Add(d); } } DivisorsCash[input] = ret; return ret; }
// Copyright 2011 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Threading; using JetBrains.Annotations; using NodaTime.Calendars; using NodaTime.Properties; using NodaTime.Text; using NodaTime.Text.Patterns; using NodaTime.TimeZones; using NodaTime.Utility; namespace NodaTime.Globalization { /// <summary> /// A <see cref="IFormatProvider"/> for Noda Time types, initialised from a <see cref="CultureInfo"/>. /// This provides a single place defining how NodaTime values are formatted and displayed, depending on the culture. /// </summary> /// <remarks> /// Currently this is "shallow-immutable" - although none of these properties can be changed, the /// CultureInfo itself may be mutable. In the future we will make this fully immutable. /// </remarks> /// <threadsafety>Instances which use read-only CultureInfo instances are immutable, /// and may be used freely between threads. Instances with mutable cultures should not be shared between threads /// without external synchronization. /// See the thread safety section of the user guide for more information.</threadsafety> internal sealed class NodaFormatInfo { // Names that we can use to check for broken Mono behaviour. // The cloning is *also* to work around a Mono bug, where even read-only cultures can change... // See http://bugzilla.xamarin.com/show_bug.cgi?id=3279 private static readonly string[] ShortInvariantMonthNames = (string[]) CultureInfo.InvariantCulture.DateTimeFormat.AbbreviatedMonthNames.Clone(); private static readonly string[] LongInvariantMonthNames = (string[]) CultureInfo.InvariantCulture.DateTimeFormat.MonthNames.Clone(); #region Patterns private readonly object fieldLock = new object(); private FixedFormatInfoPatternParser<Duration> durationPatternParser; private FixedFormatInfoPatternParser<Offset> offsetPatternParser; private FixedFormatInfoPatternParser<Instant> instantPatternParser; private FixedFormatInfoPatternParser<LocalTime> localTimePatternParser; private FixedFormatInfoPatternParser<LocalDate> localDatePatternParser; private FixedFormatInfoPatternParser<LocalDateTime> localDateTimePatternParser; private FixedFormatInfoPatternParser<OffsetDateTime> offsetDateTimePatternParser; private FixedFormatInfoPatternParser<ZonedDateTime> zonedDateTimePatternParser; #endregion /// <summary> /// A NodaFormatInfo wrapping the invariant culture. /// </summary> // Note: this must occur below the pattern parsers, to make type initialization work... public static readonly NodaFormatInfo InvariantInfo = new NodaFormatInfo(CultureInfo.InvariantCulture); // Justification for max size: CultureInfo.GetCultures(CultureTypes.AllCultures) returns 378 cultures // on Windows 8 in mid-2013. 500 should be ample, without being enormous. private static readonly Cache<CultureInfo, NodaFormatInfo> Cache = new Cache<CultureInfo, NodaFormatInfo> (500, culture => new NodaFormatInfo(culture), new ReferenceEqualityComparer<CultureInfo>()); #if PCL private readonly string dateSeparator; private readonly string timeSeparator; #endif private IList<string> longMonthNames; private IList<string> longMonthGenitiveNames; private IList<string> longDayNames; private IList<string> shortMonthNames; private IList<string> shortMonthGenitiveNames; private IList<string> shortDayNames; private readonly Dictionary<Era, EraDescription> eraDescriptions; /// <summary> /// Initializes a new instance of the <see cref="NodaFormatInfo" /> class. /// </summary> /// <param name="cultureInfo">The culture info to base this on.</param> internal NodaFormatInfo([NotNull] CultureInfo cultureInfo) { Preconditions.CheckNotNull(cultureInfo, nameof(cultureInfo)); this.CultureInfo = cultureInfo; eraDescriptions = new Dictionary<Era, EraDescription>(); #if PCL // Horrible, but it does the job... dateSeparator = DateTime.MinValue.ToString("%/", cultureInfo); timeSeparator = DateTime.MinValue.ToString("%:", cultureInfo); #endif } private void EnsureMonthsInitialized() { lock (fieldLock) { if (longMonthNames != null) { return; } // Turn month names into 1-based read-only lists longMonthNames = ConvertMonthArray(CultureInfo.DateTimeFormat.MonthNames); shortMonthNames = ConvertMonthArray(CultureInfo.DateTimeFormat.AbbreviatedMonthNames); longMonthGenitiveNames = ConvertGenitiveMonthArray(longMonthNames, CultureInfo.DateTimeFormat.MonthGenitiveNames, LongInvariantMonthNames); shortMonthGenitiveNames = ConvertGenitiveMonthArray(shortMonthNames, CultureInfo.DateTimeFormat.AbbreviatedMonthGenitiveNames, ShortInvariantMonthNames); } } /// <summary> /// The BCL returns arrays of month names starting at 0; we want a read-only list starting at 1 (with 0 as null). /// </summary> private static IList<string> ConvertMonthArray(string[] monthNames) { List<string> list = new List<string>(monthNames); list.Insert(0, null); return new ReadOnlyCollection<string>(list); } private void EnsureDaysInitialized() { lock (fieldLock) { if (longDayNames != null) { return; } longDayNames = ConvertDayArray(CultureInfo.DateTimeFormat.DayNames); shortDayNames = ConvertDayArray(CultureInfo.DateTimeFormat.AbbreviatedDayNames); } } /// <summary> /// The BCL returns arrays of week names starting at 0 as Sunday; we want a read-only list starting at 1 (with 0 as null) /// and with 7 as Sunday. /// </summary> private static IList<string> ConvertDayArray(string[] dayNames) { List<string> list = new List<string>(dayNames); list.Add(dayNames[0]); list[0] = null; return new ReadOnlyCollection<string>(list); } /// <summary> /// Checks whether any of the genitive names differ from the non-genitive names, and returns /// either a reference to the non-genitive names or a converted list as per ConvertMonthArray. /// </summary> /// <remarks> /// <para> /// Mono uses the invariant month names for the genitive month names by default, so we'll assume that /// if we see an invariant name, that *isn't* deliberately a genitive month name. A non-invariant culture /// which decided to have genitive month names exactly matching the invariant ones would be distinctly odd. /// See http://bugzilla.xamarin.com/show_bug.cgi?id=3278 for more details and progress. /// </para> /// <para> /// Mono 3.0.6 has an exciting and different bug, where all the abbreviated genitive month names are just numbers ("1" etc). /// So again, if we detect that, we'll go back to the non-genitive version. /// See http://bugzilla.xamarin.com/show_bug.cgi?id=11361 for more details and progress. /// </para> /// </remarks> private IList<string> ConvertGenitiveMonthArray(IList<string> nonGenitiveNames, string[] bclNames, string[] invariantNames) { int ignored; if (int.TryParse(bclNames[0], out ignored)) { return nonGenitiveNames; } for (int i = 0; i < bclNames.Length; i++) { if (bclNames[i] != nonGenitiveNames[i + 1] && bclNames[i] != invariantNames[i]) { return ConvertMonthArray(bclNames); } } return nonGenitiveNames; } /// <summary> /// Gets the culture info associated with this format provider. /// </summary> public CultureInfo CultureInfo { get; } /// <summary> /// Gets the text comparison information associated with this format provider. /// </summary> public CompareInfo CompareInfo => CultureInfo.CompareInfo; internal FixedFormatInfoPatternParser<Duration> DurationPatternParser => EnsureFixedFormatInitialized(ref durationPatternParser, () => new DurationPatternParser()); internal FixedFormatInfoPatternParser<Offset> OffsetPatternParser => EnsureFixedFormatInitialized(ref offsetPatternParser, () => new OffsetPatternParser()); internal FixedFormatInfoPatternParser<Instant> InstantPatternParser => EnsureFixedFormatInitialized(ref instantPatternParser, () => new InstantPatternParser()); internal FixedFormatInfoPatternParser<LocalTime> LocalTimePatternParser => EnsureFixedFormatInitialized(ref localTimePatternParser, () => new LocalTimePatternParser(LocalTime.Midnight)); internal FixedFormatInfoPatternParser<LocalDate> LocalDatePatternParser => EnsureFixedFormatInitialized(ref localDatePatternParser, () => new LocalDatePatternParser(LocalDatePattern.DefaultTemplateValue)); internal FixedFormatInfoPatternParser<LocalDateTime> LocalDateTimePatternParser => EnsureFixedFormatInitialized(ref localDateTimePatternParser, () => new LocalDateTimePatternParser(LocalDateTimePattern.DefaultTemplateValue)); internal FixedFormatInfoPatternParser<OffsetDateTime> OffsetDateTimePatternParser => EnsureFixedFormatInitialized(ref offsetDateTimePatternParser, () => new OffsetDateTimePatternParser(OffsetDateTimePattern.DefaultTemplateValue)); internal FixedFormatInfoPatternParser<ZonedDateTime> ZonedDateTimePatternParser => EnsureFixedFormatInitialized(ref zonedDateTimePatternParser, () => new ZonedDateTimePatternParser(ZonedDateTimePattern.DefaultTemplateValue, Resolvers.StrictResolver, null)); private FixedFormatInfoPatternParser<T> EnsureFixedFormatInitialized<T>(ref FixedFormatInfoPatternParser<T> field, Func<IPatternParser<T>> patternParserFactory) { lock (fieldLock) { if (field == null) { field = new FixedFormatInfoPatternParser<T>(patternParserFactory(), this); } return field; } } /// <summary> /// Returns a read-only list of the names of the months for the default calendar for this culture. /// See the usage guide for caveats around the use of these names for other calendars. /// Element 0 of the list is null, to allow a more natural mapping from (say) 1 to the string "January". /// </summary> public IList<string> LongMonthNames { get { EnsureMonthsInitialized(); return longMonthNames; } } /// <summary> /// Returns a read-only list of the abbreviated names of the months for the default calendar for this culture. /// See the usage guide for caveats around the use of these names for other calendars. /// Element 0 of the list is null, to allow a more natural mapping from (say) 1 to the string "Jan". /// </summary> public IList<string> ShortMonthNames { get { EnsureMonthsInitialized(); return shortMonthNames; } } /// <summary> /// Returns a read-only list of the names of the months for the default calendar for this culture. /// See the usage guide for caveats around the use of these names for other calendars. /// Element 0 of the list is null, to allow a more natural mapping from (say) 1 to the string "January". /// The genitive form is used for month text where the day of month also appears in the pattern. /// If the culture does not use genitive month names, this property will return the same reference as /// <see cref="LongMonthNames"/>. /// </summary> public IList<string> LongMonthGenitiveNames { get { EnsureMonthsInitialized(); return longMonthGenitiveNames; } } /// <summary> /// Returns a read-only list of the abbreviated names of the months for the default calendar for this culture. /// See the usage guide for caveats around the use of these names for other calendars. /// Element 0 of the list is null, to allow a more natural mapping from (say) 1 to the string "Jan". /// The genitive form is used for month text where the day also appears in the pattern. /// If the culture does not use genitive month names, this property will return the same reference as /// <see cref="ShortMonthNames"/>. /// </summary> public IList<string> ShortMonthGenitiveNames { get { EnsureMonthsInitialized(); return shortMonthGenitiveNames; } } /// <summary> /// Returns a read-only list of the names of the days of the week for the default calendar for this culture. /// See the usage guide for caveats around the use of these names for other calendars. /// Element 0 of the list is null, and the other elements correspond with the index values returned from /// <see cref="LocalDateTime.DayOfWeek"/> and similar properties. /// </summary> public IList<string> LongDayNames { get { EnsureDaysInitialized(); return longDayNames; } } /// <summary> /// Returns a read-only list of the abbreviated names of the days of the week for the default calendar for this culture. /// See the usage guide for caveats around the use of these names for other calendars. /// Element 0 of the list is null, and the other elements correspond with the index values returned from /// <see cref="LocalDateTime.DayOfWeek"/> and similar properties. /// </summary> public IList<string> ShortDayNames { get { EnsureDaysInitialized(); return shortDayNames; } } /// <summary> /// Gets the number format associated with this formatting information. /// </summary> public NumberFormatInfo NumberFormat => CultureInfo.NumberFormat; /// <summary> /// Gets the BCL date time format associated with this formatting information. /// </summary> public DateTimeFormatInfo DateTimeFormat => CultureInfo.DateTimeFormat; /// <summary> /// Gets the positive sign. /// </summary> public string PositiveSign => NumberFormat.PositiveSign; /// <summary> /// Gets the negative sign. /// </summary> public string NegativeSign => NumberFormat.NegativeSign; #if PCL /// <summary> /// Gets the time separator. /// </summary> public string TimeSeparator => timeSeparator; /// <summary> /// Gets the date separator. /// </summary> public string DateSeparator => dateSeparator; #else /// <summary> /// Gets the time separator. /// </summary> public string TimeSeparator => DateTimeFormat.TimeSeparator; /// <summary> /// Gets the date separator. /// </summary> public string DateSeparator => DateTimeFormat.DateSeparator; #endif /// <summary> /// Gets the AM designator. /// </summary> public string AMDesignator => DateTimeFormat.AMDesignator; /// <summary> /// Gets the PM designator. /// </summary> public string PMDesignator => DateTimeFormat.PMDesignator; /// <summary> /// Returns the names for the given era in this culture. /// </summary> /// <param name="era">The era to find the names of.</param> /// <returns>A read-only list of names for the given era, or an empty list if /// the era is not known in this culture.</returns> public IList<string> GetEraNames([NotNull] Era era) { Preconditions.CheckNotNull(era, nameof(era)); return GetEraDescription(era).AllNames; } /// <summary> /// Returns the primary name for the given era in this culture. /// </summary> /// <param name="era">The era to find the primary name of.</param> /// <returns>The primary name for the given era, or an empty string if the era name is not known.</returns> public string GetEraPrimaryName([NotNull] Era era) { Preconditions.CheckNotNull(era, nameof(era)); return GetEraDescription(era).PrimaryName; } private EraDescription GetEraDescription(Era era) { lock (eraDescriptions) { EraDescription ret; if (!eraDescriptions.TryGetValue(era, out ret)) { ret = EraDescription.ForEra(era, CultureInfo); eraDescriptions[era] = ret; } return ret; } } /// <summary> /// Gets the <see cref="NodaFormatInfo" /> object for the current thread. /// </summary> public static NodaFormatInfo CurrentInfo => GetInstance(Thread.CurrentThread.CurrentCulture); /// <summary> /// Gets the <see cref="Offset" /> "l" pattern. /// </summary> public string OffsetPatternLong => PatternResources.ResourceManager.GetString("OffsetPatternLong", CultureInfo); /// <summary> /// Gets the <see cref="Offset" /> "m" pattern. /// </summary> public string OffsetPatternMedium => PatternResources.ResourceManager.GetString("OffsetPatternMedium", CultureInfo); /// <summary> /// Gets the <see cref="Offset" /> "s" pattern. /// </summary> public string OffsetPatternShort => PatternResources.ResourceManager.GetString("OffsetPatternShort", CultureInfo); /// <summary> /// Gets the <see cref="Offset" /> "L" pattern. /// </summary> public string OffsetPatternLongNoPunctuation => PatternResources.ResourceManager.GetString("OffsetPatternLongNoPunctuation", CultureInfo); /// <summary> /// Gets the <see cref="Offset" /> "M" pattern. /// </summary> public string OffsetPatternMediumNoPunctuation => PatternResources.ResourceManager.GetString("OffsetPatternMediumNoPunctuation", CultureInfo); /// <summary> /// Gets the <see cref="Offset" /> "S" pattern. /// </summary> public string OffsetPatternShortNoPunctuation => PatternResources.ResourceManager.GetString("OffsetPatternShortNoPunctuation", CultureInfo); /// <summary> /// Clears the cache. Only used for test purposes. /// </summary> internal static void ClearCache() => Cache.Clear(); /// <summary> /// Gets the <see cref="NodaFormatInfo" /> for the given <see cref="CultureInfo" />. /// </summary> /// <remarks> /// This method maintains a cache of results for read-only cultures. /// </remarks> /// <param name="cultureInfo">The culture info.</param> /// <returns>The <see cref="NodaFormatInfo" />. Will never be null.</returns> internal static NodaFormatInfo GetFormatInfo([NotNull] CultureInfo cultureInfo) { Preconditions.CheckNotNull(cultureInfo, nameof(cultureInfo)); if (cultureInfo == CultureInfo.InvariantCulture) { return InvariantInfo; } // Never cache (or consult the cache) for non-read-only cultures. if (!cultureInfo.IsReadOnly) { return new NodaFormatInfo(cultureInfo); } return Cache.GetOrAdd(cultureInfo); } /// <summary> /// Gets the <see cref="NodaFormatInfo" /> for the given <see cref="IFormatProvider" />. If the /// format provider is null or if it does not provide a <see cref="NodaFormatInfo" /> /// object then the format object for the current thread is returned. /// </summary> /// <param name="provider">The <see cref="IFormatProvider" />.</param> /// <returns>The <see cref="NodaFormatInfo" />. Will never be null.</returns> public static NodaFormatInfo GetInstance(IFormatProvider provider) { if (provider != null) { var cultureInfo = provider as CultureInfo; if (cultureInfo != null) { return GetFormatInfo(cultureInfo); } } return GetInstance(CultureInfo.CurrentCulture); } /// <summary> /// Returns a <see cref="System.String" /> that represents this instance. /// </summary> public override string ToString() => "NodaFormatInfo[" + CultureInfo.Name + "]"; /// <summary> /// The description for an era: the primary name and all possible names. /// </summary> private class EraDescription { internal string PrimaryName { get; } internal ReadOnlyCollection<string> AllNames { get; } private EraDescription(string primaryName, ReadOnlyCollection<string> allNames) { this.PrimaryName = primaryName; this.AllNames = allNames; } internal static EraDescription ForEra(Era era, CultureInfo cultureInfo) { string pipeDelimited = PatternResources.ResourceManager.GetString(era.ResourceIdentifier, cultureInfo); string primaryName; string[] allNames; if (pipeDelimited == null) { allNames = new string[0]; primaryName = ""; } else { string eraNameFromCulture = GetEraNameFromBcl(era, cultureInfo); if (eraNameFromCulture != null && !pipeDelimited.StartsWith(eraNameFromCulture + "|")) { pipeDelimited = eraNameFromCulture + "|" + pipeDelimited; } allNames = pipeDelimited.Split('|'); primaryName = allNames[0]; // Order by length, descending to avoid early out (e.g. parsing BCE as BC and then having a spare E) Array.Sort(allNames, (x, y) => y.Length.CompareTo(x.Length)); } return new EraDescription(primaryName, new ReadOnlyCollection<string>(allNames)); } /// <summary> /// Returns the name of the era within a culture according to the BCL, if this is known and we're confident that /// it's correct. (The selection here seems small, but it covers most cases.) This isn't ideal, but it's better /// than nothing, and fixes an issue where non-English BCL cultures have "gg" in their patterns. /// </summary> private static string GetEraNameFromBcl(Era era, CultureInfo culture) { var calendar = culture.DateTimeFormat.Calendar; #if PCL var calendarTypeName = calendar.GetType().FullName; bool getEraFromCalendar = (era == Era.Common && calendarTypeName == "System.Globalization.GregorianCalendar") || (era == Era.AnnoPersico && calendarTypeName == "System.Globalization.PersianCalendar") || (era == Era.AnnoHegirae && (calendarTypeName == "System.Globalization.HijriCalendar" || calendarTypeName == "System.Globalization.UmAlQuraCalendar")); #else bool getEraFromCalendar = (era == Era.Common && calendar is GregorianCalendar) || (era == Era.AnnoPersico && calendar is PersianCalendar) || (era == Era.AnnoHegirae && (calendar is HijriCalendar || calendar is UmAlQuraCalendar)); #endif return getEraFromCalendar ? culture.DateTimeFormat.GetEraName(1) : null; } } } }
// Copyright (c) 2016-2020 Alexander Ong // See LICENSE in project root for license information. // Thank you DarkAngel2096 for your previous contributions to get lyrics into // more charts! using MoonscraperChartEditor.Song; using System.Collections.Generic; using UnityEngine.UI; using System.Text.RegularExpressions; public class LyricEditor2Controller : UnityEngine.MonoBehaviour { // Stores a set of all commands which have been invoked to modify chart // events. When the lyric editor is exited, a single ICommand will be pushed // to the command stack which contains all the changes which were made to // events public class SongEditCommandSet : MoonscraperEngine.ICommand { List<SongEditCommand> commands = new List<SongEditCommand>(); BatchedSongEditCommand batchedCommands = null; public bool isEmpty {get {return commands.Count == 0;}} public void Add(SongEditCommand c) { commands.Add(c); } public bool Remove(SongEditCommand c) { return commands.Remove(c); } public void Invoke() { if (batchedCommands == null) { batchedCommands = new BatchedSongEditCommand(commands); } else { batchedCommands.Invoke(); } } public void Revoke() { batchedCommands?.Revoke(); } } class PickupFromCommand : MoonscraperEngine.ICommand { public delegate void Refresh(); Refresh refreshAfterUpdate; BatchedICommand pickupCommands; public PickupFromCommand(BatchedICommand pickupCommands, Refresh refreshAfterUpdate) { this.pickupCommands = pickupCommands; this.refreshAfterUpdate = refreshAfterUpdate; } public void Invoke() { pickupCommands.Invoke(); refreshAfterUpdate(); } public void Revoke() { pickupCommands.Revoke(); refreshAfterUpdate(); } } enum InputState { Full, Phrase } static Song currentSong {get {return ChartEditor.Instance.currentSong;}} static float songResolution {get {return currentSong.resolution;}} static bool playbackActive {get {return (ChartEditor.Instance.currentState == ChartEditor.State.Playing);}} public SongEditCommandSet editCommands; LyricEditorCommandStack m_commandStack = new LyricEditorCommandStack(); [UnityEngine.SerializeField] LyricEditor2AutoScroller autoScroller; [UnityEngine.SerializeField] LyricEditor2PhraseController phraseTemplate; [UnityEngine.SerializeField] LyricEditor2InputMenu lyricInputMenu; [UnityEngine.SerializeField] [UnityEngine.Range(0, 1)] float phrasePaddingFactor; [UnityEngine.SerializeField] [UnityEngine.Tooltip("Phrase padding as 1/n measures; i.e. a value of 16 means one sixteenth note")] int phrasePaddingMax; // 16 refers to one sixteenth the length of a phrase in the current song. // So with a resolution of 192, the phrase_start event should have at least 12 ticks of spacing LyricEditor2PhraseController currentPhrase; List<LyricEditor2PhraseController> phrases = new List<LyricEditor2PhraseController>(); // commandStackPushes keeps a record of all command stack pushes so they can // be removed from the main command stack (Pop() method returns void, not // the revoked command; see CommandStack.cs) List<PickupFromCommand> commandStackPushes = new List<PickupFromCommand>(); int numCommandStackPushes = 0; LyricEditor2PhraseController lastPlaybackTarget = null; InputState inputState = InputState.Full; LyricEditor2PhraseController inputPhrase; uint currentTickPos {get {return ChartEditor.Instance.currentTickPos;}} uint currentSnappedTickPos { get { return Globals.gameSettings.lyricEditorSettings.stepSnappingEnabled ? Snapable.TickToSnappedTick(currentTickPos, Globals.gameSettings.step, ChartEditor.Instance.currentSong) : currentTickPos; } } bool playbackScrolling = false; bool onePhrasePickedUp = false; uint playbackEndTick; int lastPlaybackTargetIndex = 0; string savedUnplacedSyllables = ""; string savedPlacedSyllables = ""; // Called every time the "place lyric" button is pressed; places the next // lyric in the current phrase, and sets the phrase's start tick, if it has // not been set public void PlaceNextLyric() { currentPhrase = GetNextUnfinishedPhrase(); if (currentPhrase != null && IsLegalToPlaceNow()) { // Clear command stack commands to prevent duplication after redo ClearPickupCommands(); onePhrasePickedUp = false; // Distance check phase end event to this new start event. // If these two events are too close to each other then delete the phase end event to let CH automatically handle it. { var lastFinishedPhase = GetPreviousPhrase(currentPhrase); if (lastFinishedPhase != null) { uint? endTick = lastFinishedPhase.endTick; if (endTick.HasValue) { uint endPhaseTick = endTick.Value; float oldPhaseEndTime = ChartEditor.Instance.currentSong.TickToTime(endPhaseTick); float newPhaseStartTime = ChartEditor.Instance.currentSong.TickToTime(currentSnappedTickPos); if ((newPhaseStartTime - oldPhaseEndTime) < Globals.gameSettings.lyricEditorSettings.phaseEndThreashold) { // Remove phase end event lastFinishedPhase.PickupPhraseEnd(); } } } } // Set the next lyric's tick currentPhrase.StartPlaceNextLyric(currentSnappedTickPos); // Set phrase_start if it is not already set if (!currentPhrase.phraseStartPlaced) { AutoPlacePhraseStart(currentPhrase); } } // All phrases placed already, so currentPhrase was null } // Called every time the "place lyric" button is released; stops placing the // next lyric in the current phrase and, if necessary, moves to the next // phrase. phrase_end events are placed here if necessary public void StopPlaceNextLyric() { if (currentPhrase != null) { currentPhrase.StopPlaceNextLyric(); // Place phrase_end event and move to next phrase if all syllables // were just placed if (currentPhrase.allSyllablesPlaced) { if (IsLegalToPlaceNow()) { currentPhrase.SetPhraseEnd(currentSnappedTickPos); } else { AutoPlacePhraseEnd(currentPhrase); } currentPhrase = GetNextUnfinishedPhrase(); autoScroller.ScrollTo(currentPhrase?.rectTransform); ClearPickupCommands(); } } } // Display a large input field for the user to enter lyrics in dash- // newline notation; field should be populated with a string given by // GetTextRepresentation() public void EnableInputMenu() { lyricInputMenu.SetTitle("Input Lyrics"); inputState = InputState.Full; string existingLyrics = GetTextRepresentation(); lyricInputMenu.Display(existingLyrics); } // Take dash-newline formatted lyrics from the lyric input menu and parse // them into phrases. Called when the user hits "submit" in the input menu. // Consider the input state! public void InputLyrics() { if (inputState == InputState.Full) { ClearPickupCommands(); PickupAllPhrases(); ClearPhraseObjects(); string inputLyrics = lyricInputMenu.text ?? ""; phrases.AddRange(CreatePhrases(inputLyrics)); if (phrases.Count > 0) { currentPhrase = phrases[0]; } // Update search order UpdateSortIds(); } else if (inputState == InputState.Phrase) { ClearPickupCommands(); string inputLyrics = lyricInputMenu.text ?? ""; int inputIndex = phrases.BinarySearch(inputPhrase); if (inputIndex >= 0) { // Remove existing phrases PickupFrom(inputPhrase, false, true); for (int i = inputIndex; i < phrases.Count; i++) { UnityEngine.Object.Destroy(phrases[i].gameObject); } phrases.RemoveRange(inputIndex, phrases.Count - inputIndex); // Create new phrases var newPhrases = CreatePhrases(inputLyrics); phrases.InsertRange(inputIndex, newPhrases); UpdateSortIds(); UpdateDisplayOrder(); } } } public void PickupFrom(LyricEditor2PhraseController start, bool pushToStack = true, bool forcePickupAll = false) { if (forcePickupAll || onePhrasePickedUp || start.numSyllables == 1 || HasFollowingLyrics(start)) { List<MoonscraperEngine.ICommand> commands = new List<MoonscraperEngine.ICommand>(); int startIndex = phrases.BinarySearch(start); if (startIndex >= 0) { for (int i = startIndex; i < phrases.Count; i++) { if (phrases[i].anySyllablesPlaced) { commands.Add(phrases[i].Pickup()); } } } currentPhrase = GetNextUnfinishedPhrase(); // Invoke commands if (commands.Count > 0) { var batchedCommands = new BatchedICommand(commands); var pickupFromCommand = new PickupFromCommand(batchedCommands, RefreshAfterPickupFrom); if (pushToStack) { commandStackPushes.Add(pickupFromCommand); ChartEditor.Instance.commandStack.Push(pickupFromCommand); } else { pickupFromCommand.Invoke(); } } onePhrasePickedUp = true; } else if (start.anySyllablesPlaced) { ClearPickupCommands(); start.PickupLastSyllable(); onePhrasePickedUp = true; currentPhrase = GetNextUnfinishedPhrase(); if (!playbackActive) { AutoPlacePhraseStartEnd(start); } } } // Opens the lyric input menu to edit the given lyrics public void EditPhrase(LyricEditor2PhraseController phrase) { inputPhrase = phrase; inputState = InputState.Phrase; string rep = ""; int startIndex = phrases.BinarySearch(phrase); for (int i = startIndex; i >= 0 && i < phrases.Count; i++) { rep += phrases[i].GetTextRepresentation(); } EnableInputMenu(rep, title: (startIndex < phrases.Count - 1) ? "Edit Phrases" : "Edit Phrase"); } public void OnStateChanged(in ChartEditor.State newState) { if (!isActiveAndEnabled) return; autoScroller.enabled = playbackActive; playbackScrolling = playbackActive; if (playbackActive) { if (!IsLegalToPlaceNow()) { StartPlaybackScroll(); } else { autoScroller.ScrollTo(currentPhrase?.rectTransform); } } else { lastPlaybackTarget?.PlaybackHighlight(null); } } public void onCommandStackPush(in MoonscraperEngine.ICommand command) { UnityEngine.Debug.Assert(command is PickupFromCommand, "Trying to push a non-lyric editor command onto the lyrics editor stack! Did you miss a call to ChartEditor.Instance.SetDefaultCommandStack?"); if (!(command is PickupFromCommand c && commandStackPushes.Contains(c))) { gameObject.SetActive(false); } else { numCommandStackPushes++; } } public void onCommandStackPop(in MoonscraperEngine.ICommand command) { UnityEngine.Debug.Assert(command is PickupFromCommand, "Trying to pop a non-lyric editor command from the lyrics editor stack! Did you miss a call to ChartEditor.Instance.SetDefaultCommandStack?"); if (!(command is PickupFromCommand c && commandStackPushes.Contains(c))) { gameObject.SetActive(false); } else { numCommandStackPushes--; } } public void Reset() { savedPlacedSyllables = ""; savedUnplacedSyllables = ""; numCommandStackPushes = 0; ClearPhraseObjects(); OnEnable(); } void OnEnable() { ChartEditor.Instance.SetActiveCommandStack(m_commandStack); // Create a new edit command set editCommands = new SongEditCommandSet(); ImportExistingLyrics(); AddSavedSyllables(); currentPhrase = GetNextUnfinishedPhrase(); // Activate auto-scrolling if playback is active on lyric editor enable autoScroller.enabled = playbackActive; UnityEngine.Debug.Log("Opened lyric editor"); } void OnDisable() { // Save lyrics SaveUnplacedSyllables(); SavePlacedSyllables(); // Place phrase_end for current phrase if it hasn't been placed if (currentPhrase != null && !currentPhrase.phraseEndPlaced && currentPhrase.anySyllablesPlaced) { // Ensure valid placement AutoPlacePhraseEnd(currentPhrase); } ClearPhraseObjects(); autoScroller.enabled = false; // Remove command stack commands ClearPickupCommands(); // Push batched edits to command stack ChartEditor.Instance.SetDefaultCommandStack(); if (!editCommands.isEmpty) { // Push the finalised commands back onto the primary stack ChartEditor.Instance.commandStack.Push(editCommands); } editCommands = null; // Release memory, don't wait for the next OnEnable call m_commandStack.Clear(); UnityEngine.Debug.Log("Closed lyric editor"); } void Start() { phraseTemplate.gameObject.SetActive(false); ChartEditor.Instance.events.editorStateChangedEvent.Register(OnStateChanged); ChartEditor.Instance.events.songLoadedEvent.Register(Reset); m_commandStack.onPush.Register(onCommandStackPush); m_commandStack.onPop.Register(onCommandStackPop); } void Update() { if (MSChartEditorInput.GetInputDown(MSChartEditorInputActions.LyricEditorSetTime)) { PlaceNextLyric(); } else if (MSChartEditorInput.GetInputUp(MSChartEditorInputActions.LyricEditorSetTime)) { StopPlaceNextLyric(); } if (playbackScrolling) { PlaybackScroll(false); } } static bool HasLyricEvents(List<SongEditCommand> commands) { foreach (SongEditCommand c in commands) { if (HasLyricEvents(c)) { return true; } } // No lyric events found return false; } static bool HasLyricEvents(SongEditCommand command) { // Check for batched commands if (command is BatchedSongEditCommand batched && HasLyricEvents(batched.GetSongEditCommands())) { return true; } // Not a batched command var songObjects = command.GetSongObjects(); foreach (SongObject o in songObjects) { if (o is Event e && IsLyricEvent(e)) { return true; } } // No lyric events found return false; } static bool IsLyricEvent(Event selectedEvent) { if (selectedEvent.IsLyric() || selectedEvent.title.Equals(LyricEditor2PhraseController.c_phraseStartKeyword) || selectedEvent.title.Equals(LyricEditor2PhraseController.c_phraseEndKeyword)) { return true; } else { return false; } } static bool MakesValidPhrase (List<Event> potentialPhrase) { for (int i = 0; i < potentialPhrase.Count; i++) { if (potentialPhrase[i].IsLyric()) { return true; } } // No lyric events found return false; } // Compare two events for use with List.Sort(). Events should be sorted by // tick; if two Events have the same tick, then lyric events should be // sorted before phrase_end and after phrase_start events. Unrelated events // can be sorted alphabetically using String.Compare() static int CompareEditorEvents (Event event1, Event event2) { if (event1 == null && event2 == null) { // Both events null and are equivalent return 0; } else if (event1 == null) { // event1 null return 1; } else if (event2 == null) { // event2 null return -1; } else if (event1.tick != event2.tick) { // Two events at different ticks return event1.tick > event2.tick ? 1 : -1; } else if (event1.title.Equals(LyricEditor2PhraseController.c_phraseStartKeyword) || event2.title.Equals(LyricEditor2PhraseController.c_phraseEndKeyword)) { // Two events at the same tick, event1 is phrase_start or event2 is phrase_end return -1; } else if (event2.title.Equals(LyricEditor2PhraseController.c_phraseStartKeyword) || event1.title.Equals(LyricEditor2PhraseController.c_phraseEndKeyword)) { // Two events at the same tick, event1 is phrase_end or event2 is phrase_start return 1; } else { // Two events at the same tick, neither is phrase_start or phrase_end return System.String.Compare(event1.title, event2.title); } } // Import existing lyric events from the current song. Called in Start() void ImportExistingLyrics() { // Use CompareEditorEvents (below) to sort events, then group events into // sections by looking for phrase_start events List<Event> importedEvents = new List<Event>(); foreach (Event eventObject in ChartEditor.Instance.currentSong.events) { if (IsLyricEvent(eventObject)) { importedEvents.Add(eventObject); } } importedEvents.Sort(CompareEditorEvents); List<Event> tempEvents = new List<Event>(); for (int i = 0; i < importedEvents.Count; i++) { Event currentEvent = importedEvents[i]; if (currentEvent.title.TrimEnd().Equals(LyricHelper.LYRIC_EVENT_PREFIX.TrimEnd())) { var deleteCommand = new SongEditDelete(currentEvent); deleteCommand.Invoke(); editCommands.Add(deleteCommand); continue; } tempEvents.Add(currentEvent); if (currentEvent.title.Equals(LyricEditor2PhraseController.c_phraseEndKeyword) || i == importedEvents.Count - 1 || (importedEvents[i+1].title.Equals(LyricEditor2PhraseController.c_phraseStartKeyword))) { if (MakesValidPhrase(tempEvents)) { LyricEditor2PhraseController newPhrase = Instantiate(phraseTemplate, phraseTemplate.transform.parent).GetComponent<LyricEditor2PhraseController>(); newPhrase.InitializeSyllables(tempEvents); phrases.Add(newPhrase); newPhrase.gameObject.SetActive(true); } else { // phrase has no associated lyrics, delete it foreach (var e in tempEvents) { var deleteCommand = new SongEditDelete(e); deleteCommand.Invoke(); editCommands.Add(deleteCommand); } } // No lyrics in the current phrase, clear temp events to avoid pollution with extra phrase events tempEvents.Clear(); } } // Update search order UpdateSortIds(); // Check to ensure all fully-placed phrases have their phrase_start and // phrase_end events set, if appropriate for(int i = 0; i < phrases.Count; i++) { LyricEditor2PhraseController currentPhrase = phrases[i]; AutoPlacePhraseStartEnd(currentPhrase); } } void AutoPlacePhraseStartEnd(LyricEditor2PhraseController currentPhrase) { if ((currentPhrase.allSyllablesPlaced && !currentPhrase.phraseStartPlaced) || (currentPhrase.GetFirstEventTick() < currentPhrase.startTick)) { AutoPlacePhraseStart(currentPhrase); } // Check for phrase_end is a little more complex, only auto-place // phrase_end if the spacing between phrases is small enough var nextPhrase = GetNextPhrase(currentPhrase); if (currentPhrase.allSyllablesPlaced && !currentPhrase.phraseEndPlaced) { if (nextPhrase == null) { AutoPlacePhraseEnd(currentPhrase); } else { uint nextPhraseStart = (uint)nextPhrase.GetFirstEventTick(); float nextPhraseStartTime = ChartEditor.Instance.currentSong.TickToTime(nextPhraseStart); uint thisPhraseEnd = PhraseEndAutoSpacer(currentPhrase); float thisPhraseEndTime = ChartEditor.Instance.currentSong.TickToTime(thisPhraseEnd); // UnityEngine.Debug.LogFormat("Time difference was calculated to be {0} (from nextPhraseStartTime {1} and thisPhraseEnd {2})", (nextPhraseStartTime - thisPhraseEndTime), nextPhraseStartTime, thisPhraseEndTime); if ((nextPhraseStartTime - thisPhraseEndTime) >= Globals.gameSettings.lyricEditorSettings.phaseEndThreashold) { AutoPlacePhraseEnd(currentPhrase); } } } } // Add phrases from last session, if the other imported lyrics match the // previously-stored lyrics void AddSavedSyllables() { if (savedUnplacedSyllables.Length != 0 && GetTextRepresentation().Equals(savedPlacedSyllables)) { int firstNewline = savedUnplacedSyllables.IndexOf('\n'); string firstLine = savedUnplacedSyllables.Substring(0, firstNewline); List<List<string>> firstLineSyllablesRaw = ParseLyrics(firstLine); if (firstLineSyllablesRaw.Count > 0) { List<string> firstLineSyllables = firstLineSyllablesRaw[0]; phrases[phrases.Count-1].AddSyllables(firstLineSyllables); phrases[phrases.Count-1].PickupPhraseEnd(); } string otherLines = savedUnplacedSyllables.Substring(firstNewline+1); List<LyricEditor2PhraseController> extraPhrases = CreatePhrases(otherLines); phrases.AddRange(extraPhrases); UpdateSortIds(); } } // Destroy all phrase GameObjects and dereference their corresponding // phrase controller components void ClearPhraseObjects() { foreach (LyricEditor2PhraseController controller in phrases) { UnityEngine.Object.Destroy(controller.gameObject); } phrases.Clear(); } // Display input field with custom prepopulated field; function is called // internally only, so it should not update inputState void EnableInputMenu(string prefilledLyrics, string title = "Input Lyrics") { lyricInputMenu.SetTitle(title); lyricInputMenu.Display(prefilledLyrics); } // Check to see if the current tick is valid to place a lyric; if the // current time falls before the last element of currentPhrase, the // placement is considered invalid bool IsLegalToPlaceNow() { uint firstPhraseTick = GetFirstSafeTick(currentPhrase); uint snappedTick = currentSnappedTickPos; if (snappedTick <= firstPhraseTick) { // Current position is before first safe tick return false; } else if (snappedTick <= currentPhrase?.startTick || snappedTick <= currentPhrase?.GetLastEventTick()) { // Current position is in the middle of currentPhrase return false; } else { // No illegal state found return true; } } // Find the most recent previous phrase which has been placed and return its // end tick. If no such phrase exists, return 0. If the passed targetPhrase // is null, return the last safe tick of the entire song. uint GetFirstSafeTick(LyricEditor2PhraseController targetPhrase) { int currentPhraseIndex = phrases.BinarySearch(targetPhrase); if (currentPhraseIndex == -1 || targetPhrase == null) { currentPhraseIndex = phrases.Count; } // Iterate through up to the last 50 phrases for (int i = currentPhraseIndex - 1; i > currentPhraseIndex - 51; i--) { if (i < 0) { break; } // Check for any placed lyrics first, as a phrase with no unplaced // lyrics will not have an endTick or lastEventTick if (phrases[i].anySyllablesPlaced) { uint? finalTick = phrases[i].endTick; if (finalTick == null) { finalTick = phrases[i].GetLastEventTick(); } if (finalTick != null) { return (uint)finalTick + 1; } } } // No previous phrase found, return 0 return 0; } // Gets the last safe tick a given phrase can legally occupy uint GetLastSafeTick(LyricEditor2PhraseController targetPhrase) { // Look for a next-up phrase int targetIndex = phrases.BinarySearch(targetPhrase); if (targetIndex + 1 < phrases.Count) { LyricEditor2PhraseController nextPhrase = phrases[targetIndex + 1]; uint? nextPhraseStart = nextPhrase.startTick ?? nextPhrase.GetFirstEventTick(); if (nextPhraseStart != null) { return (uint)nextPhraseStart - 1; } } // No next phrase start found uint songEnd = currentSong.TimeToTick(ChartEditor.Instance.currentSongLength, songResolution); return songEnd; } void AutoPlacePhraseStart (LyricEditor2PhraseController phrase) { uint firstSafeTick = GetFirstSafeTick(phrase); // Tick calculation by set distance before first lyric uint startTick1 = (uint)(phrase.GetFirstEventTick() - (int)(songResolution / phrasePaddingMax * 4)); // Tick calculation proportional to distance to last phrase uint startTick2 = (uint)(firstSafeTick + (int)((phrase.GetFirstEventTick() - firstSafeTick) * (1 - phrasePaddingFactor))); // Actual start tick is the maximum of these two values uint startTick = System.Math.Max(startTick1, startTick2); // Set the start tick phrase.SetPhraseStart(startTick); } // Place the end event of the target phrase automatically void AutoPlacePhraseEnd (LyricEditor2PhraseController phrase) { phrase.SetPhraseEnd(PhraseEndAutoSpacer(phrase)); } // Returns the phrase-end auto-spacing when the phrase end event is placed // automatically uint PhraseEndAutoSpacer(LyricEditor2PhraseController targetPhrase) { uint lastSafeTick = GetLastSafeTick(targetPhrase); // Tick calculation by set distance uint endTick1 = (uint)(targetPhrase.GetLastEventTick() + (int)(songResolution / phrasePaddingMax * 4)); // Tick calculation by proportional distance uint endTick2 = (uint)(lastSafeTick - (int)((targetPhrase.GetLastEventTick() - lastSafeTick) * phrasePaddingFactor)); // Actual start tick is the minimum of these two values uint endTick = System.Math.Min(endTick1, endTick2); return endTick; } // Get the latest phrase which does have all its syllables placed LyricEditor2PhraseController GetPreviousPhrase(LyricEditor2PhraseController phrase) { int previousPhraseIndex = phrases.IndexOf(phrase) - 1; return previousPhraseIndex >= 0 ? phrases[previousPhraseIndex] : null; } LyricEditor2PhraseController GetNextPhrase(LyricEditor2PhraseController phrase) { int nextIndex = phrases.IndexOf(phrase) + 1; return nextIndex < phrases.Count ? phrases[nextIndex] : null; } // Get the next phrase which does not yet have all its syllables placed LyricEditor2PhraseController GetNextUnfinishedPhrase() { for (int i = 0; i < phrases.Count; i++) { LyricEditor2PhraseController currentPhrase = phrases[i]; if (!currentPhrase.allSyllablesPlaced) { return currentPhrase; } } // No incomplete phrase found return null; } // Checks whether a phrase has any subsequent placed lyrics bool HasFollowingLyrics(LyricEditor2PhraseController phrase) { int phraseIndex = phrases.BinarySearch(phrase); if (phraseIndex == phrases.Count - 1) { return false; // Phrase is last } else { return phrases[phraseIndex + 1].anySyllablesPlaced; } } // Pickup all phrases; not revokable, as references to phrases and events // are lost when ClearPickupCommands() is called void PickupAllPhrases() { foreach (var phrase in phrases) { phrase.Pickup().Invoke(); } ClearPickupCommands(); } // Set the search IDs of all phrase controllers based on their position in // phrases void UpdateSortIds() { for (int i = 0; i < phrases.Count; i++) { phrases[i].sortID = i; } } void UpdateDisplayOrder() { for (int i = 0; i < phrases.Count; i++) { phrases[i].transform.SetSiblingIndex(phrases[i].sortID); } } // Creates a list of LyricEditor2PhraseController objects from a string // input List<LyricEditor2PhraseController> CreatePhrases(string inputLyrics) { List<LyricEditor2PhraseController> createdPhrases = new List<LyricEditor2PhraseController>(); List<List<string>> parsedLyrics = ParseLyrics(inputLyrics); for (int i = 0; i < parsedLyrics.Count; i++) { LyricEditor2PhraseController newPhrase = UnityEngine.GameObject.Instantiate(phraseTemplate, phraseTemplate.transform.parent).GetComponent<LyricEditor2PhraseController>(); newPhrase.InitializeSyllables(parsedLyrics[i]); createdPhrases.Add(newPhrase); newPhrase.gameObject.SetActive(true); } return createdPhrases; } // Parse a string into a double string array (phrases of syllables) to be // given as phrase controller input. Does not have an implemented time-out // period in case of excessively long strings to be parsed. List<List<string>> ParseLyrics(string inputString) { // Remove short tags (5 characters or less), plus any other < or > keys // inputString = Regex.Replace(inputString, "</?[^<>]{0,5}>|<|>", System.String.Empty); // Regex was NOT the answer // https://blog.codinghorror.com/content/images/2014/Apr/stack-overflow-regex-zalgo.png // Split into phrases char[] newlineCharacters = {'\n', '\r'}; string[] tempPhrases = inputString.Split(newlineCharacters, System.StringSplitOptions.RemoveEmptyEntries); // Prepare the regex engine to parse each phrase List<List<string>> parsedLyrics = new List<List<string>>(); // [^-^=\s]+ matches one or more characters in a syllable, excluding // spaces, dashes, and equals signs // (-|=|\s?) matches a dash, equals sign, or trailing whitespace string regexPattern = @"[^-^=\s]+(-|=|\s?)"; Regex rx = new Regex(regexPattern); foreach (string basePhrase in tempPhrases) { // Match each phrase MatchCollection matches = rx.Matches(basePhrase); // Convert the MatchCollection into a List and append that to // parsedLyrics List<string> matchesList = new List<string>(); for (int i = 0; i < matches.Count; i++) { matchesList.Add(matches[i].ToString()); } parsedLyrics.Add(matchesList); } return parsedLyrics; } // Create a text representation of stored lyrics which can be pushed to the // input menu when the user wants to edit lyrics string GetTextRepresentation() { string rep = ""; for (int i = 0; i < phrases.Count; i++) { rep += phrases[i].GetTextRepresentation(); } return rep.TrimEnd(); } // Begin auto-scrolling for lyric playback (before the user can place more // phrases) void StartPlaybackScroll() { playbackScrolling = true; lastPlaybackTargetIndex = 0; LyricEditor2PhraseController firstUnplacedPhrase = GetNextUnfinishedPhrase(); playbackEndTick = GetFirstSafeTick(firstUnplacedPhrase); PlaybackScroll(true); } // Auto-scroll during lyric playback void PlaybackScroll(bool forceScroll) { // Check for playback end if (currentTickPos >= playbackEndTick) { playbackScrolling = false; currentPhrase = GetNextUnfinishedPhrase(); autoScroller.ScrollTo(currentPhrase?.rectTransform); return; } // Find target phrase LyricEditor2PhraseController playbackTarget = lastPlaybackTarget; for (int i = lastPlaybackTargetIndex; i < phrases.Count; i++) { if (phrases[i].anySyllablesPlaced) { uint endBound = phrases[i].endTick ?? PhraseEndAutoSpacer(phrases[i]); if (currentTickPos < endBound) { playbackTarget = phrases[i]; // update lastPlaybackTargetIndex lastPlaybackTargetIndex = i; break; } } } // Scroll to phrase if (forceScroll || playbackTarget != lastPlaybackTarget) { autoScroller.ScrollTo(playbackTarget?.rectTransform); lastPlaybackTarget?.PlaybackHighlight(null); } // Update lastPlaybackTarget lastPlaybackTarget = playbackTarget; // Highlight syllables playbackTarget.PlaybackHighlight(currentTickPos); } void RefreshAfterPickupFrom() { currentPhrase = GetNextUnfinishedPhrase(); } void ClearPickupCommands() { // numCommandStackPushes gets decremented automatically, need to assign // to another variable first int pushesToDelete = numCommandStackPushes; for (int i = 0; i < pushesToDelete; ++i) { ChartEditor.Instance.commandStack.Pop(); } if (commandStackPushes.Count > 0) { ChartEditor.Instance.commandStack.ResetTail(); } // Need to redo the changes made in those pushes for (int i = 0; i < pushesToDelete; ++i) { commandStackPushes[i].Invoke(); } commandStackPushes.Clear(); numCommandStackPushes = 0; } // Create a string representation of all unplaced syllables void SaveUnplacedSyllables() { savedUnplacedSyllables = ""; var incompletePhrase = GetNextUnfinishedPhrase(); if (incompletePhrase != null) { int firstSearchIndex; // Check for some, but not all, syllables placed if (incompletePhrase.anySyllablesPlaced && !incompletePhrase.allSyllablesPlaced) { savedUnplacedSyllables += incompletePhrase.GetTextRepresentation(onlyConsiderUnplaced: true); firstSearchIndex = phrases.BinarySearch(incompletePhrase) + 1; } else { firstSearchIndex = phrases.BinarySearch(incompletePhrase); savedUnplacedSyllables += "\n"; } // Save fully-placed phrases for (int i = firstSearchIndex; i < phrases.Count; i++) { savedUnplacedSyllables += phrases[i].GetTextRepresentation(); } } } // Create a string representation of all placed syllables void SavePlacedSyllables() { savedPlacedSyllables = ""; var incompletePhrase = GetNextUnfinishedPhrase(); if (incompletePhrase != null) { int unfinishedIndex = phrases.BinarySearch(incompletePhrase); for (int i = 0; i < unfinishedIndex; i++) { savedPlacedSyllables += phrases[i].GetTextRepresentation(); } savedPlacedSyllables += incompletePhrase.GetTextRepresentation(onlyConsiderPlaced: true); savedPlacedSyllables = savedPlacedSyllables.TrimEnd(); } else { savedPlacedSyllables = GetTextRepresentation(); } } }
// 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.ComponentModel; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Security; using System.Linq; using System.Diagnostics; namespace System.Runtime.Serialization { /// <SecurityNote> /// Critical - Class holds static instances used in serializer. /// Static fields are marked SecurityCritical or readonly to prevent /// data from being modified or leaked to other components in appdomain. /// Safe - All get-only properties marked safe since they only need to be protected for write. /// </SecurityNote> internal static class Globals { /// <SecurityNote> /// Review - changes to const could affect code generation logic; any changes should be reviewed. /// </SecurityNote> internal const BindingFlags ScanAllMembers = BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; [SecurityCritical] private static XmlQualifiedName s_idQualifiedName; internal static XmlQualifiedName IdQualifiedName { [SecuritySafeCritical] get { if (s_idQualifiedName == null) s_idQualifiedName = new XmlQualifiedName(Globals.IdLocalName, Globals.SerializationNamespace); return s_idQualifiedName; } } [SecurityCritical] private static XmlQualifiedName s_refQualifiedName; internal static XmlQualifiedName RefQualifiedName { [SecuritySafeCritical] get { if (s_refQualifiedName == null) s_refQualifiedName = new XmlQualifiedName(Globals.RefLocalName, Globals.SerializationNamespace); return s_refQualifiedName; } } [SecurityCritical] private static Type s_typeOfObject; internal static Type TypeOfObject { [SecuritySafeCritical] get { if (s_typeOfObject == null) s_typeOfObject = typeof(object); return s_typeOfObject; } } [SecurityCritical] private static Type s_typeOfValueType; internal static Type TypeOfValueType { [SecuritySafeCritical] get { if (s_typeOfValueType == null) s_typeOfValueType = typeof(ValueType); return s_typeOfValueType; } } [SecurityCritical] private static Type s_typeOfArray; internal static Type TypeOfArray { [SecuritySafeCritical] get { if (s_typeOfArray == null) s_typeOfArray = typeof(Array); return s_typeOfArray; } } [SecurityCritical] private static Type s_typeOfException; internal static Type TypeOfException { [SecuritySafeCritical] get { if (s_typeOfException == null) s_typeOfException = typeof(Exception); return s_typeOfException; } } [SecurityCritical] private static Type s_typeOfString; internal static Type TypeOfString { [SecuritySafeCritical] get { if (s_typeOfString == null) s_typeOfString = typeof(string); return s_typeOfString; } } [SecurityCritical] private static Type s_typeOfInt; internal static Type TypeOfInt { [SecuritySafeCritical] get { if (s_typeOfInt == null) s_typeOfInt = typeof(int); return s_typeOfInt; } } [SecurityCritical] private static Type s_typeOfULong; internal static Type TypeOfULong { [SecuritySafeCritical] get { if (s_typeOfULong == null) s_typeOfULong = typeof(ulong); return s_typeOfULong; } } [SecurityCritical] private static Type s_typeOfVoid; internal static Type TypeOfVoid { [SecuritySafeCritical] get { if (s_typeOfVoid == null) s_typeOfVoid = typeof(void); return s_typeOfVoid; } } [SecurityCritical] private static Type s_typeOfByteArray; internal static Type TypeOfByteArray { [SecuritySafeCritical] get { if (s_typeOfByteArray == null) s_typeOfByteArray = typeof(byte[]); return s_typeOfByteArray; } } [SecurityCritical] private static Type s_typeOfTimeSpan; internal static Type TypeOfTimeSpan { [SecuritySafeCritical] get { if (s_typeOfTimeSpan == null) s_typeOfTimeSpan = typeof(TimeSpan); return s_typeOfTimeSpan; } } [SecurityCritical] private static Type s_typeOfGuid; internal static Type TypeOfGuid { [SecuritySafeCritical] get { if (s_typeOfGuid == null) s_typeOfGuid = typeof(Guid); return s_typeOfGuid; } } [SecurityCritical] private static Type s_typeOfDateTimeOffset; internal static Type TypeOfDateTimeOffset { [SecuritySafeCritical] get { if (s_typeOfDateTimeOffset == null) s_typeOfDateTimeOffset = typeof(DateTimeOffset); return s_typeOfDateTimeOffset; } } [SecurityCritical] private static Type s_typeOfDateTimeOffsetAdapter; internal static Type TypeOfDateTimeOffsetAdapter { [SecuritySafeCritical] get { if (s_typeOfDateTimeOffsetAdapter == null) s_typeOfDateTimeOffsetAdapter = typeof(DateTimeOffsetAdapter); return s_typeOfDateTimeOffsetAdapter; } } [SecurityCritical] private static Type s_typeOfUri; internal static Type TypeOfUri { [SecuritySafeCritical] get { if (s_typeOfUri == null) s_typeOfUri = typeof(Uri); return s_typeOfUri; } } [SecurityCritical] private static Type s_typeOfTypeEnumerable; internal static Type TypeOfTypeEnumerable { [SecuritySafeCritical] get { if (s_typeOfTypeEnumerable == null) s_typeOfTypeEnumerable = typeof(IEnumerable<Type>); return s_typeOfTypeEnumerable; } } [SecurityCritical] private static Type s_typeOfStreamingContext; internal static Type TypeOfStreamingContext { [SecuritySafeCritical] get { if (s_typeOfStreamingContext == null) s_typeOfStreamingContext = typeof(StreamingContext); return s_typeOfStreamingContext; } } [SecurityCritical] private static Type s_typeOfXmlFormatClassWriterDelegate; internal static Type TypeOfXmlFormatClassWriterDelegate { [SecuritySafeCritical] get { if (s_typeOfXmlFormatClassWriterDelegate == null) s_typeOfXmlFormatClassWriterDelegate = typeof(XmlFormatClassWriterDelegate); return s_typeOfXmlFormatClassWriterDelegate; } } [SecurityCritical] private static Type s_typeOfXmlFormatCollectionWriterDelegate; internal static Type TypeOfXmlFormatCollectionWriterDelegate { [SecuritySafeCritical] get { if (s_typeOfXmlFormatCollectionWriterDelegate == null) s_typeOfXmlFormatCollectionWriterDelegate = typeof(XmlFormatCollectionWriterDelegate); return s_typeOfXmlFormatCollectionWriterDelegate; } } [SecurityCritical] private static Type s_typeOfXmlFormatClassReaderDelegate; internal static Type TypeOfXmlFormatClassReaderDelegate { [SecuritySafeCritical] get { if (s_typeOfXmlFormatClassReaderDelegate == null) s_typeOfXmlFormatClassReaderDelegate = typeof(XmlFormatClassReaderDelegate); return s_typeOfXmlFormatClassReaderDelegate; } } [SecurityCritical] private static Type s_typeOfXmlFormatCollectionReaderDelegate; internal static Type TypeOfXmlFormatCollectionReaderDelegate { [SecuritySafeCritical] get { if (s_typeOfXmlFormatCollectionReaderDelegate == null) s_typeOfXmlFormatCollectionReaderDelegate = typeof(XmlFormatCollectionReaderDelegate); return s_typeOfXmlFormatCollectionReaderDelegate; } } [SecurityCritical] private static Type s_typeOfXmlFormatGetOnlyCollectionReaderDelegate; internal static Type TypeOfXmlFormatGetOnlyCollectionReaderDelegate { [SecuritySafeCritical] get { if (s_typeOfXmlFormatGetOnlyCollectionReaderDelegate == null) s_typeOfXmlFormatGetOnlyCollectionReaderDelegate = typeof(XmlFormatGetOnlyCollectionReaderDelegate); return s_typeOfXmlFormatGetOnlyCollectionReaderDelegate; } } [SecurityCritical] private static Type s_typeOfKnownTypeAttribute; internal static Type TypeOfKnownTypeAttribute { [SecuritySafeCritical] get { if (s_typeOfKnownTypeAttribute == null) s_typeOfKnownTypeAttribute = typeof(KnownTypeAttribute); return s_typeOfKnownTypeAttribute; } } /// <SecurityNote> /// Critical - attrbute type used in security decision /// </SecurityNote> [SecurityCritical] private static Type s_typeOfDataContractAttribute; internal static Type TypeOfDataContractAttribute { /// <SecurityNote> /// Critical - accesses critical field for attribute type /// Safe - controls inputs and logic /// </SecurityNote> [SecuritySafeCritical] get { if (s_typeOfDataContractAttribute == null) s_typeOfDataContractAttribute = typeof(DataContractAttribute); return s_typeOfDataContractAttribute; } } [SecurityCritical] private static Type s_typeOfDataMemberAttribute; internal static Type TypeOfDataMemberAttribute { [SecuritySafeCritical] get { if (s_typeOfDataMemberAttribute == null) s_typeOfDataMemberAttribute = typeof(DataMemberAttribute); return s_typeOfDataMemberAttribute; } } [SecurityCritical] private static Type s_typeOfEnumMemberAttribute; internal static Type TypeOfEnumMemberAttribute { [SecuritySafeCritical] get { if (s_typeOfEnumMemberAttribute == null) s_typeOfEnumMemberAttribute = typeof(EnumMemberAttribute); return s_typeOfEnumMemberAttribute; } } [SecurityCritical] private static Type s_typeOfCollectionDataContractAttribute; internal static Type TypeOfCollectionDataContractAttribute { [SecuritySafeCritical] get { if (s_typeOfCollectionDataContractAttribute == null) s_typeOfCollectionDataContractAttribute = typeof(CollectionDataContractAttribute); return s_typeOfCollectionDataContractAttribute; } } [SecurityCritical] private static Type s_typeOfObjectArray; internal static Type TypeOfObjectArray { [SecuritySafeCritical] get { if (s_typeOfObjectArray == null) s_typeOfObjectArray = typeof(object[]); return s_typeOfObjectArray; } } [SecurityCritical] private static Type s_typeOfOnSerializingAttribute; internal static Type TypeOfOnSerializingAttribute { [SecuritySafeCritical] get { if (s_typeOfOnSerializingAttribute == null) s_typeOfOnSerializingAttribute = typeof(OnSerializingAttribute); return s_typeOfOnSerializingAttribute; } } [SecurityCritical] private static Type s_typeOfOnSerializedAttribute; internal static Type TypeOfOnSerializedAttribute { [SecuritySafeCritical] get { if (s_typeOfOnSerializedAttribute == null) s_typeOfOnSerializedAttribute = typeof(OnSerializedAttribute); return s_typeOfOnSerializedAttribute; } } [SecurityCritical] private static Type s_typeOfOnDeserializingAttribute; internal static Type TypeOfOnDeserializingAttribute { [SecuritySafeCritical] get { if (s_typeOfOnDeserializingAttribute == null) s_typeOfOnDeserializingAttribute = typeof(OnDeserializingAttribute); return s_typeOfOnDeserializingAttribute; } } [SecurityCritical] private static Type s_typeOfOnDeserializedAttribute; internal static Type TypeOfOnDeserializedAttribute { [SecuritySafeCritical] get { if (s_typeOfOnDeserializedAttribute == null) s_typeOfOnDeserializedAttribute = typeof(OnDeserializedAttribute); return s_typeOfOnDeserializedAttribute; } } [SecurityCritical] private static Type s_typeOfFlagsAttribute; internal static Type TypeOfFlagsAttribute { [SecuritySafeCritical] get { if (s_typeOfFlagsAttribute == null) s_typeOfFlagsAttribute = typeof(FlagsAttribute); return s_typeOfFlagsAttribute; } } [SecurityCritical] private static Type s_typeOfIXmlSerializable; internal static Type TypeOfIXmlSerializable { [SecuritySafeCritical] get { if (s_typeOfIXmlSerializable == null) s_typeOfIXmlSerializable = typeof(IXmlSerializable); return s_typeOfIXmlSerializable; } } [SecurityCritical] private static Type s_typeOfXmlSchemaProviderAttribute; internal static Type TypeOfXmlSchemaProviderAttribute { [SecuritySafeCritical] get { if (s_typeOfXmlSchemaProviderAttribute == null) s_typeOfXmlSchemaProviderAttribute = typeof(XmlSchemaProviderAttribute); return s_typeOfXmlSchemaProviderAttribute; } } [SecurityCritical] private static Type s_typeOfXmlRootAttribute; internal static Type TypeOfXmlRootAttribute { [SecuritySafeCritical] get { if (s_typeOfXmlRootAttribute == null) s_typeOfXmlRootAttribute = typeof(XmlRootAttribute); return s_typeOfXmlRootAttribute; } } [SecurityCritical] private static Type s_typeOfXmlQualifiedName; internal static Type TypeOfXmlQualifiedName { [SecuritySafeCritical] get { if (s_typeOfXmlQualifiedName == null) s_typeOfXmlQualifiedName = typeof(XmlQualifiedName); return s_typeOfXmlQualifiedName; } } #if NET_NATIVE [SecurityCritical] private static Type s_typeOfISerializableDataNode; internal static Type TypeOfISerializableDataNode { [SecuritySafeCritical] get { if (s_typeOfISerializableDataNode == null) s_typeOfISerializableDataNode = typeof(ISerializableDataNode); return s_typeOfISerializableDataNode; } } [SecurityCritical] private static Type s_typeOfClassDataNode; internal static Type TypeOfClassDataNode { [SecuritySafeCritical] get { if (s_typeOfClassDataNode == null) s_typeOfClassDataNode = typeof(ClassDataNode); return s_typeOfClassDataNode; } } [SecurityCritical] private static Type s_typeOfCollectionDataNode; internal static Type TypeOfCollectionDataNode { [SecuritySafeCritical] get { if (s_typeOfCollectionDataNode == null) s_typeOfCollectionDataNode = typeof(CollectionDataNode); return s_typeOfCollectionDataNode; } } [SecurityCritical] private static Type s_typeOfSafeSerializationManager; private static bool s_typeOfSafeSerializationManagerSet; internal static Type TypeOfSafeSerializationManager { [SecuritySafeCritical] get { if (!s_typeOfSafeSerializationManagerSet) { s_typeOfSafeSerializationManager = TypeOfInt.GetTypeInfo().Assembly.GetType("System.Runtime.Serialization.SafeSerializationManager"); s_typeOfSafeSerializationManagerSet = true; } return s_typeOfSafeSerializationManager; } } #endif [SecurityCritical] private static Type s_typeOfNullable; internal static Type TypeOfNullable { [SecuritySafeCritical] get { if (s_typeOfNullable == null) s_typeOfNullable = typeof(Nullable<>); return s_typeOfNullable; } } [SecurityCritical] private static Type s_typeOfIDictionaryGeneric; internal static Type TypeOfIDictionaryGeneric { [SecuritySafeCritical] get { if (s_typeOfIDictionaryGeneric == null) s_typeOfIDictionaryGeneric = typeof(IDictionary<,>); return s_typeOfIDictionaryGeneric; } } [SecurityCritical] private static Type s_typeOfIDictionary; internal static Type TypeOfIDictionary { [SecuritySafeCritical] get { if (s_typeOfIDictionary == null) s_typeOfIDictionary = typeof(IDictionary); return s_typeOfIDictionary; } } [SecurityCritical] private static Type s_typeOfIListGeneric; internal static Type TypeOfIListGeneric { [SecuritySafeCritical] get { if (s_typeOfIListGeneric == null) s_typeOfIListGeneric = typeof(IList<>); return s_typeOfIListGeneric; } } [SecurityCritical] private static Type s_typeOfIList; internal static Type TypeOfIList { [SecuritySafeCritical] get { if (s_typeOfIList == null) s_typeOfIList = typeof(IList); return s_typeOfIList; } } [SecurityCritical] private static Type s_typeOfICollectionGeneric; internal static Type TypeOfICollectionGeneric { [SecuritySafeCritical] get { if (s_typeOfICollectionGeneric == null) s_typeOfICollectionGeneric = typeof(ICollection<>); return s_typeOfICollectionGeneric; } } [SecurityCritical] private static Type s_typeOfICollection; internal static Type TypeOfICollection { [SecuritySafeCritical] get { if (s_typeOfICollection == null) s_typeOfICollection = typeof(ICollection); return s_typeOfICollection; } } [SecurityCritical] private static Type s_typeOfIEnumerableGeneric; internal static Type TypeOfIEnumerableGeneric { [SecuritySafeCritical] get { if (s_typeOfIEnumerableGeneric == null) s_typeOfIEnumerableGeneric = typeof(IEnumerable<>); return s_typeOfIEnumerableGeneric; } } [SecurityCritical] private static Type s_typeOfIEnumerable; internal static Type TypeOfIEnumerable { [SecuritySafeCritical] get { if (s_typeOfIEnumerable == null) s_typeOfIEnumerable = typeof(IEnumerable); return s_typeOfIEnumerable; } } [SecurityCritical] private static Type s_typeOfIEnumeratorGeneric; internal static Type TypeOfIEnumeratorGeneric { [SecuritySafeCritical] get { if (s_typeOfIEnumeratorGeneric == null) s_typeOfIEnumeratorGeneric = typeof(IEnumerator<>); return s_typeOfIEnumeratorGeneric; } } [SecurityCritical] private static Type s_typeOfIEnumerator; internal static Type TypeOfIEnumerator { [SecuritySafeCritical] get { if (s_typeOfIEnumerator == null) s_typeOfIEnumerator = typeof(IEnumerator); return s_typeOfIEnumerator; } } [SecurityCritical] private static Type s_typeOfKeyValuePair; internal static Type TypeOfKeyValuePair { [SecuritySafeCritical] get { if (s_typeOfKeyValuePair == null) s_typeOfKeyValuePair = typeof(KeyValuePair<,>); return s_typeOfKeyValuePair; } } [SecurityCritical] private static Type s_typeOfKeyValuePairAdapter; internal static Type TypeOfKeyValuePairAdapter { [SecuritySafeCritical] get { if (s_typeOfKeyValuePairAdapter == null) s_typeOfKeyValuePairAdapter = typeof(KeyValuePairAdapter<,>); return s_typeOfKeyValuePairAdapter; } } [SecurityCritical] private static Type s_typeOfKeyValue; internal static Type TypeOfKeyValue { [SecuritySafeCritical] get { if (s_typeOfKeyValue == null) s_typeOfKeyValue = typeof(KeyValue<,>); return s_typeOfKeyValue; } } [SecurityCritical] private static Type s_typeOfIDictionaryEnumerator; internal static Type TypeOfIDictionaryEnumerator { [SecuritySafeCritical] get { if (s_typeOfIDictionaryEnumerator == null) s_typeOfIDictionaryEnumerator = typeof(IDictionaryEnumerator); return s_typeOfIDictionaryEnumerator; } } [SecurityCritical] private static Type s_typeOfDictionaryEnumerator; internal static Type TypeOfDictionaryEnumerator { [SecuritySafeCritical] get { if (s_typeOfDictionaryEnumerator == null) s_typeOfDictionaryEnumerator = typeof(CollectionDataContract.DictionaryEnumerator); return s_typeOfDictionaryEnumerator; } } [SecurityCritical] private static Type s_typeOfGenericDictionaryEnumerator; internal static Type TypeOfGenericDictionaryEnumerator { [SecuritySafeCritical] get { if (s_typeOfGenericDictionaryEnumerator == null) s_typeOfGenericDictionaryEnumerator = typeof(CollectionDataContract.GenericDictionaryEnumerator<,>); return s_typeOfGenericDictionaryEnumerator; } } [SecurityCritical] private static Type s_typeOfDictionaryGeneric; internal static Type TypeOfDictionaryGeneric { [SecuritySafeCritical] get { if (s_typeOfDictionaryGeneric == null) s_typeOfDictionaryGeneric = typeof(Dictionary<,>); return s_typeOfDictionaryGeneric; } } [SecurityCritical] private static Type s_typeOfHashtable; internal static Type TypeOfHashtable { [SecuritySafeCritical] get { if (s_typeOfHashtable == null) s_typeOfHashtable = TypeOfDictionaryGeneric.MakeGenericType(TypeOfObject, TypeOfObject); return s_typeOfHashtable; } } [SecurityCritical] private static Type s_typeOfListGeneric; internal static Type TypeOfListGeneric { [SecuritySafeCritical] get { if (s_typeOfListGeneric == null) s_typeOfListGeneric = typeof(List<>); return s_typeOfListGeneric; } } [SecurityCritical] private static Type s_typeOfXmlElement; internal static Type TypeOfXmlElement { [SecuritySafeCritical] get { if (s_typeOfXmlElement == null) s_typeOfXmlElement = typeof(XmlElement); return s_typeOfXmlElement; } } [SecurityCritical] private static Type s_typeOfXmlNodeArray; internal static Type TypeOfXmlNodeArray { [SecuritySafeCritical] get { if (s_typeOfXmlNodeArray == null) s_typeOfXmlNodeArray = typeof(XmlNode[]); return s_typeOfXmlNodeArray; } } private static bool s_shouldGetDBNullType = true; [SecurityCritical] private static Type s_typeOfDBNull; internal static Type TypeOfDBNull { [SecuritySafeCritical] get { if (s_typeOfDBNull == null && s_shouldGetDBNullType) { s_typeOfDBNull = Type.GetType("System.DBNull, System.Data.Common, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", false); s_shouldGetDBNullType = false; } return s_typeOfDBNull; } } [SecurityCritical] private static object s_valueOfDBNull; internal static object ValueOfDBNull { [SecuritySafeCritical] get { if (s_valueOfDBNull == null && TypeOfDBNull != null) { var fieldInfo = TypeOfDBNull.GetField("Value"); if (fieldInfo != null) s_valueOfDBNull = fieldInfo.GetValue(null); } return s_valueOfDBNull; } } [SecurityCritical] private static Uri s_dataContractXsdBaseNamespaceUri; internal static Uri DataContractXsdBaseNamespaceUri { [SecuritySafeCritical] get { if (s_dataContractXsdBaseNamespaceUri == null) s_dataContractXsdBaseNamespaceUri = new Uri(DataContractXsdBaseNamespace); return s_dataContractXsdBaseNamespaceUri; } } #region Contract compliance for System.Type private static bool TypeSequenceEqual(Type[] seq1, Type[] seq2) { if (seq1 == null || seq2 == null || seq1.Length != seq2.Length) return false; for (int i = 0; i < seq1.Length; i++) { if (!seq1[i].Equals(seq2[i]) && !seq1[i].IsAssignableFrom(seq2[i])) return false; } return true; } private static MethodBase FilterMethodBases(MethodBase[] methodBases, Type[] parameterTypes, string methodName) { if (methodBases == null || string.IsNullOrEmpty(methodName)) return null; var matchedMethods = methodBases.Where(method => method.Name.Equals(methodName)); matchedMethods = matchedMethods.Where(method => TypeSequenceEqual(method.GetParameters().Select(param => param.ParameterType).ToArray(), parameterTypes)); return matchedMethods.FirstOrDefault(); } internal static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingFlags, Type[] parameterTypes) { var constructorInfos = type.GetConstructors(bindingFlags); var constructorInfo = FilterMethodBases(constructorInfos.Cast<MethodBase>().ToArray(), parameterTypes, ".ctor"); return constructorInfo != null ? (ConstructorInfo)constructorInfo : null; } internal static MethodInfo GetMethod(this Type type, string methodName, BindingFlags bindingFlags, Type[] parameterTypes) { var methodInfos = type.GetMethods(bindingFlags); var methodInfo = FilterMethodBases(methodInfos.Cast<MethodBase>().ToArray(), parameterTypes, methodName); return methodInfo != null ? (MethodInfo)methodInfo : null; } #endregion private static Type s_typeOfScriptObject; private static Func<object, string> s_serializeFunc; private static Func<string, object> s_deserializeFunc; internal static ClassDataContract CreateScriptObjectClassDataContract() { Debug.Assert(s_typeOfScriptObject != null); return new ClassDataContract(s_typeOfScriptObject); } internal static bool TypeOfScriptObject_IsAssignableFrom(Type type) { return s_typeOfScriptObject != null && s_typeOfScriptObject.IsAssignableFrom(type); } internal static void SetScriptObjectJsonSerializer(Type typeOfScriptObject, Func<object, string> serializeFunc, Func<string, object> deserializeFunc) { Globals.s_typeOfScriptObject = typeOfScriptObject; Globals.s_serializeFunc = serializeFunc; Globals.s_deserializeFunc = deserializeFunc; } internal static string ScriptObjectJsonSerialize(object obj) { Debug.Assert(s_serializeFunc != null); return Globals.s_serializeFunc(obj); } internal static object ScriptObjectJsonDeserialize(string json) { Debug.Assert(s_deserializeFunc != null); return Globals.s_deserializeFunc(json); } internal static bool IsDBNullValue(object o) { return o != null && ValueOfDBNull != null && ValueOfDBNull.Equals(o); } public const bool DefaultIsRequired = false; public const bool DefaultEmitDefaultValue = true; public const int DefaultOrder = 0; public const bool DefaultIsReference = false; // The value string.Empty aids comparisons (can do simple length checks // instead of string comparison method calls in IL.) public readonly static string NewObjectId = string.Empty; public const string NullObjectId = null; public const string SimpleSRSInternalsVisiblePattern = @"^[\s]*System\.Runtime\.Serialization[\s]*$"; public const string FullSRSInternalsVisiblePattern = @"^[\s]*System\.Runtime\.Serialization[\s]*,[\s]*PublicKey[\s]*=[\s]*(?i:00240000048000009400000006020000002400005253413100040000010001008d56c76f9e8649383049f383c44be0ec204181822a6c31cf5eb7ef486944d032188ea1d3920763712ccb12d75fb77e9811149e6148e5d32fbaab37611c1878ddc19e20ef135d0cb2cff2bfec3d115810c3d9069638fe4be215dbf795861920e5ab6f7db2e2ceef136ac23d5dd2bf031700aec232f6c6b1c785b4305c123b37ab)[\s]*$"; public const string Space = " "; public const string XsiPrefix = "i"; public const string XsdPrefix = "x"; public const string SerPrefix = "z"; public const string SerPrefixForSchema = "ser"; public const string ElementPrefix = "q"; public const string DataContractXsdBaseNamespace = "http://schemas.datacontract.org/2004/07/"; public const string DataContractXmlNamespace = DataContractXsdBaseNamespace + "System.Xml"; public const string SchemaInstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance"; public const string SchemaNamespace = "http://www.w3.org/2001/XMLSchema"; public const string XsiNilLocalName = "nil"; public const string XsiTypeLocalName = "type"; public const string TnsPrefix = "tns"; public const string OccursUnbounded = "unbounded"; public const string AnyTypeLocalName = "anyType"; public const string StringLocalName = "string"; public const string IntLocalName = "int"; public const string True = "true"; public const string False = "false"; public const string ArrayPrefix = "ArrayOf"; public const string XmlnsNamespace = "http://www.w3.org/2000/xmlns/"; public const string XmlnsPrefix = "xmlns"; public const string SchemaLocalName = "schema"; public const string CollectionsNamespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays"; public const string DefaultClrNamespace = "GeneratedNamespace"; public const string DefaultTypeName = "GeneratedType"; public const string DefaultGeneratedMember = "GeneratedMember"; public const string DefaultFieldSuffix = "Field"; public const string DefaultPropertySuffix = "Property"; public const string DefaultMemberSuffix = "Member"; public const string NameProperty = "Name"; public const string NamespaceProperty = "Namespace"; public const string OrderProperty = "Order"; public const string IsReferenceProperty = "IsReference"; public const string IsRequiredProperty = "IsRequired"; public const string EmitDefaultValueProperty = "EmitDefaultValue"; public const string ClrNamespaceProperty = "ClrNamespace"; public const string ItemNameProperty = "ItemName"; public const string KeyNameProperty = "KeyName"; public const string ValueNameProperty = "ValueName"; public const string SerializationInfoPropertyName = "SerializationInfo"; public const string SerializationInfoFieldName = "info"; public const string NodeArrayPropertyName = "Nodes"; public const string NodeArrayFieldName = "nodesField"; public const string ExportSchemaMethod = "ExportSchema"; public const string IsAnyProperty = "IsAny"; public const string ContextFieldName = "context"; public const string GetObjectDataMethodName = "GetObjectData"; public const string GetEnumeratorMethodName = "GetEnumerator"; public const string MoveNextMethodName = "MoveNext"; public const string AddValueMethodName = "AddValue"; public const string CurrentPropertyName = "Current"; public const string ValueProperty = "Value"; public const string EnumeratorFieldName = "enumerator"; public const string SerializationEntryFieldName = "entry"; public const string ExtensionDataSetMethod = "set_ExtensionData"; public const string ExtensionDataSetExplicitMethod = "System.Runtime.Serialization.IExtensibleDataObject.set_ExtensionData"; public const string ExtensionDataObjectPropertyName = "ExtensionData"; public const string ExtensionDataObjectFieldName = "extensionDataField"; public const string AddMethodName = "Add"; public const string GetCurrentMethodName = "get_Current"; // NOTE: These values are used in schema below. If you modify any value, please make the same change in the schema. public const string SerializationNamespace = "http://schemas.microsoft.com/2003/10/Serialization/"; public const string ClrTypeLocalName = "Type"; public const string ClrAssemblyLocalName = "Assembly"; public const string IsValueTypeLocalName = "IsValueType"; public const string EnumerationValueLocalName = "EnumerationValue"; public const string SurrogateDataLocalName = "Surrogate"; public const string GenericTypeLocalName = "GenericType"; public const string GenericParameterLocalName = "GenericParameter"; public const string GenericNameAttribute = "Name"; public const string GenericNamespaceAttribute = "Namespace"; public const string GenericParameterNestedLevelAttribute = "NestedLevel"; public const string IsDictionaryLocalName = "IsDictionary"; public const string ActualTypeLocalName = "ActualType"; public const string ActualTypeNameAttribute = "Name"; public const string ActualTypeNamespaceAttribute = "Namespace"; public const string DefaultValueLocalName = "DefaultValue"; public const string EmitDefaultValueAttribute = "EmitDefaultValue"; public const string IdLocalName = "Id"; public const string RefLocalName = "Ref"; public const string ArraySizeLocalName = "Size"; public const string KeyLocalName = "Key"; public const string ValueLocalName = "Value"; public const string MscorlibAssemblyName = "0"; #if !NET_NATIVE public const string ParseMethodName = "Parse"; #endif public const string SafeSerializationManagerName = "SafeSerializationManager"; public const string SafeSerializationManagerNamespace = "http://schemas.datacontract.org/2004/07/System.Runtime.Serialization"; public const string ISerializableFactoryTypeLocalName = "FactoryType"; } }
// InflaterHuffmanTree.cs // Copyright (C) 2001 Mike Krueger // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; using ICSharpCode.SharpZipLib.Zip.Compression.Streams; namespace ICSharpCode.SharpZipLib.Zip.Compression { internal class InflaterHuffmanTree { private static int MAX_BITLEN = 15; private short[] tree; public static InflaterHuffmanTree defLitLenTree, defDistTree; static InflaterHuffmanTree() { try { byte[] codeLengths = new byte[288]; int i = 0; while (i < 144) { codeLengths[i++] = 8; } while (i < 256) { codeLengths[i++] = 9; } while (i < 280) { codeLengths[i++] = 7; } while (i < 288) { codeLengths[i++] = 8; } defLitLenTree = new InflaterHuffmanTree(codeLengths); codeLengths = new byte[32]; i = 0; while (i < 32) { codeLengths[i++] = 5; } defDistTree = new InflaterHuffmanTree(codeLengths); } catch (Exception) { throw new Exception("InflaterHuffmanTree: static tree length illegal"); } } /// <summary> /// Constructs a Huffman tree from the array of code lengths. /// </summary> /// <param name = "codeLengths"> /// the array of code lengths /// </param> public InflaterHuffmanTree(byte[] codeLengths) { BuildTree(codeLengths); } private void BuildTree(byte[] codeLengths) { int[] blCount = new int[MAX_BITLEN + 1]; int[] nextCode = new int[MAX_BITLEN + 1]; for (int i = 0; i < codeLengths.Length; i++) { int bits = codeLengths[i]; if (bits > 0) blCount[bits]++; } int code = 0; int treeSize = 512; for (int bits = 1; bits <= MAX_BITLEN; bits++) { nextCode[bits] = code; code += blCount[bits] << (16 - bits); if (bits >= 10) { /* We need an extra table for bit lengths >= 10. */ int start = nextCode[bits] & 0x1ff80; int end = code & 0x1ff80; treeSize += (end - start) >> (16 - bits); } } if (code != 65536) { throw new Exception("Code lengths don't add up properly."); } /* Now create and Fill the extra tables from longest to shortest * bit len. This way the sub trees will be aligned. */ tree = new short[treeSize]; int treePtr = 512; for (int bits = MAX_BITLEN; bits >= 10; bits--) { int end = code & 0x1ff80; code -= blCount[bits] << (16 - bits); int start = code & 0x1ff80; for (int i = start; i < end; i += 1 << 7) { tree[DeflaterHuffman.BitReverse(i)] = (short) ((-treePtr << 4) | bits); treePtr += 1 << (bits-9); } } for (int i = 0; i < codeLengths.Length; i++) { int bits = codeLengths[i]; if (bits == 0) { continue; } code = nextCode[bits]; int revcode = DeflaterHuffman.BitReverse(code); if (bits <= 9) { do { tree[revcode] = (short) ((i << 4) | bits); revcode += 1 << bits; } while (revcode < 512); } else { int subTree = tree[revcode & 511]; int treeLen = 1 << (subTree & 15); subTree = -(subTree >> 4); do { tree[subTree | (revcode >> 9)] = (short) ((i << 4) | bits); revcode += 1 << bits; } while (revcode < treeLen); } nextCode[bits] = code + (1 << (16 - bits)); } } /// <summary> /// Reads the next symbol from input. The symbol is encoded using the /// huffman tree. /// </summary> /// <param name="input"> /// input the input source. /// </param> /// <returns> /// the next symbol, or -1 if not enough input is available. /// </returns> public int GetSymbol(StreamManipulator input) { int lookahead, symbol; if ((lookahead = input.PeekBits(9)) >= 0) { if ((symbol = tree[lookahead]) >= 0) { input.DropBits(symbol & 15); return symbol >> 4; } int subtree = -(symbol >> 4); int bitlen = symbol & 15; if ((lookahead = input.PeekBits(bitlen)) >= 0) { symbol = tree[subtree | (lookahead >> 9)]; input.DropBits(symbol & 15); return symbol >> 4; } else { int bits = input.AvailableBits; lookahead = input.PeekBits(bits); symbol = tree[subtree | (lookahead >> 9)]; if ((symbol & 15) <= bits) { input.DropBits(symbol & 15); return symbol >> 4; } else { return -1; } } } else { int bits = input.AvailableBits; lookahead = input.PeekBits(bits); symbol = tree[lookahead]; if (symbol >= 0 && (symbol & 15) <= bits) { input.DropBits(symbol & 15); return symbol >> 4; } else { return -1; } } } } }
using Lucene.Net.Analysis; using Lucene.Net.Codecs; using Lucene.Net.Diagnostics; using Lucene.Net.Search; using Lucene.Net.Store; using Lucene.Net.Util; using System; using System.Collections; using System.Collections.Generic; using Console = Lucene.Net.Util.SystemConsole; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Silly class that randomizes the indexing experience. EG /// it may swap in a different merge policy/scheduler; may /// commit periodically; may or may not forceMerge in the end, /// may flush by doc count instead of RAM, etc. /// </summary> public class RandomIndexWriter : IDisposable { public IndexWriter IndexWriter { get; set; } // LUCENENET: Renamed from w to IndexWriter to make it clear what this is. private readonly Random r; internal int docCount; internal int flushAt; private double flushAtFactor = 1.0; private bool getReaderCalled; private readonly Codec codec; // sugar public static IndexWriter MockIndexWriter(Directory dir, IndexWriterConfig conf, Random r) { // Randomly calls Thread.yield so we mixup thread scheduling Random random = new Random(r.Next()); return MockIndexWriter(dir, conf, new TestPointAnonymousInnerClassHelper(random)); } private class TestPointAnonymousInnerClassHelper : ITestPoint { private Random random; public TestPointAnonymousInnerClassHelper(Random random) { this.random = random; } public virtual void Apply(string message) { if (random.Next(4) == 2) { System.Threading.Thread.Sleep(0); } } } public static IndexWriter MockIndexWriter(Directory dir, IndexWriterConfig conf, ITestPoint testPoint) { conf.SetInfoStream(new TestPointInfoStream(conf.InfoStream, testPoint)); return new IndexWriter(dir, conf); } #if !FEATURE_INSTANCE_TESTDATA_INITIALIZATION /// <summary> /// Create a <see cref="RandomIndexWriter"/> with a random config: Uses <see cref="LuceneTestCase.TEST_VERSION_CURRENT"/> and <see cref="MockAnalyzer"/>. /// </summary> public RandomIndexWriter(Random r, Directory dir) : this(r, dir, LuceneTestCase.NewIndexWriterConfig(r, LuceneTestCase.TEST_VERSION_CURRENT, new MockAnalyzer(r))) { } /// <summary> /// Create a <see cref="RandomIndexWriter"/> with a random config: Uses <see cref="LuceneTestCase.TEST_VERSION_CURRENT"/>. /// </summary> public RandomIndexWriter(Random r, Directory dir, Analyzer a) : this(r, dir, LuceneTestCase.NewIndexWriterConfig(r, LuceneTestCase.TEST_VERSION_CURRENT, a)) { } /// <summary> /// Creates a <see cref="RandomIndexWriter"/> with a random config. /// </summary> public RandomIndexWriter(Random r, Directory dir, LuceneVersion v, Analyzer a) : this(r, dir, LuceneTestCase.NewIndexWriterConfig(r, v, a)) { } #else /// <summary> /// Create a <see cref="RandomIndexWriter"/> with a random config: Uses <see cref="LuceneTestCase.TEST_VERSION_CURRENT"/> and <see cref="MockAnalyzer"/>. /// </summary> /// <param name="luceneTestCase">The current test instance.</param> /// <param name="r"></param> /// <param name="dir"></param> // LUCENENET specific // Similarity and TimeZone parameters allow a RandomIndexWriter to be // created without adding a dependency on // <see cref="LuceneTestCase.ClassEnv.Similarity"/> and // <see cref="LuceneTestCase.ClassEnv.TimeZone"/> public RandomIndexWriter(LuceneTestCase luceneTestCase, Random r, Directory dir) : this(r, dir, luceneTestCase.NewIndexWriterConfig(r, LuceneTestCase.TEST_VERSION_CURRENT, new MockAnalyzer(r))) { } /// <summary> /// Create a <see cref="RandomIndexWriter"/> with a random config: Uses <see cref="LuceneTestCase.TEST_VERSION_CURRENT"/>. /// </summary> /// <param name="luceneTestCase">The current test instance.</param> /// <param name="r"></param> /// <param name="dir"></param> /// <param name="a"></param> // LUCENENET specific // Similarity and TimeZone parameters allow a RandomIndexWriter to be // created without adding a dependency on // <see cref="LuceneTestCase.ClassEnv.Similarity"/> and // <see cref="LuceneTestCase.ClassEnv.TimeZone"/> public RandomIndexWriter(LuceneTestCase luceneTestCase, Random r, Directory dir, Analyzer a) : this(r, dir, luceneTestCase.NewIndexWriterConfig(r, LuceneTestCase.TEST_VERSION_CURRENT, a)) { } /// <summary> /// Creates a <see cref="RandomIndexWriter"/> with a random config. /// </summary> /// <param name="luceneTestCase">The current test instance.</param> /// <param name="r"></param> /// <param name="dir"></param> /// <param name="v"></param> /// <param name="a"></param> // LUCENENET specific // Similarity and TimeZone parameters allow a RandomIndexWriter to be // created without adding a dependency on // <see cref="LuceneTestCase.ClassEnv.Similarity"/> and // <see cref="LuceneTestCase.ClassEnv.TimeZone"/> public RandomIndexWriter(LuceneTestCase luceneTestCase, Random r, Directory dir, LuceneVersion v, Analyzer a) : this(r, dir, luceneTestCase.NewIndexWriterConfig(r, v, a)) { } #endif /// <summary> /// Creates a <see cref="RandomIndexWriter"/> with the provided config </summary> public RandomIndexWriter(Random r, Directory dir, IndexWriterConfig c) { // TODO: this should be solved in a different way; Random should not be shared (!). this.r = new Random(r.Next()); IndexWriter = MockIndexWriter(dir, c, r); flushAt = TestUtil.NextInt32(r, 10, 1000); codec = IndexWriter.Config.Codec; if (LuceneTestCase.Verbose) { Console.WriteLine("RIW dir=" + dir + " config=" + IndexWriter.Config); Console.WriteLine("codec default=" + codec.Name); } // Make sure we sometimes test indices that don't get // any forced merges: doRandomForceMerge = !(c.MergePolicy is NoMergePolicy) && r.NextBoolean(); } /// <summary> /// Adds a Document. </summary> /// <seealso cref="IndexWriter.AddDocument(IEnumerable{IIndexableField})"/> public virtual void AddDocument(IEnumerable<IIndexableField> doc) { AddDocument(doc, IndexWriter.Analyzer); } public virtual void AddDocument(IEnumerable<IIndexableField> doc, Analyzer a) { if (r.Next(5) == 3) { // TODO: maybe, we should simply buffer up added docs // (but we need to clone them), and only when // getReader, commit, etc. are called, we do an // addDocuments? Would be better testing. IndexWriter.AddDocuments(new IterableAnonymousInnerClassHelper<IIndexableField>(this, doc), a); } else { IndexWriter.AddDocument(doc, a); } MaybeCommit(); } private class IterableAnonymousInnerClassHelper<IndexableField> : IEnumerable<IEnumerable<IndexableField>> { private readonly RandomIndexWriter outerInstance; private readonly IEnumerable<IndexableField> doc; public IterableAnonymousInnerClassHelper(RandomIndexWriter outerInstance, IEnumerable<IndexableField> doc) { this.outerInstance = outerInstance; this.doc = doc; } public IEnumerator<IEnumerable<IndexableField>> GetEnumerator() { return new IteratorAnonymousInnerClassHelper(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private class IteratorAnonymousInnerClassHelper : IEnumerator<IEnumerable<IndexableField>> { private readonly IterableAnonymousInnerClassHelper<IndexableField> outerInstance; public IteratorAnonymousInnerClassHelper(IterableAnonymousInnerClassHelper<IndexableField> outerInstance) { this.outerInstance = outerInstance; } internal bool done; private IEnumerable<IndexableField> current; public bool MoveNext() { if (done) { return false; } done = true; current = outerInstance.doc; return true; } public IEnumerable<IndexableField> Current => current; object IEnumerator.Current => Current; public void Reset() => throw new NotImplementedException(); public void Dispose() { } } } private void MaybeCommit() { if (docCount++ == flushAt) { if (LuceneTestCase.Verbose) { Console.WriteLine("RIW.add/updateDocument: now doing a commit at docCount=" + docCount); } IndexWriter.Commit(); flushAt += TestUtil.NextInt32(r, (int)(flushAtFactor * 10), (int)(flushAtFactor * 1000)); if (flushAtFactor < 2e6) { // gradually but exponentially increase time b/w flushes flushAtFactor *= 1.05; } } } public virtual void AddDocuments(IEnumerable<IEnumerable<IIndexableField>> docs) { IndexWriter.AddDocuments(docs); MaybeCommit(); } public virtual void UpdateDocuments(Term delTerm, IEnumerable<IEnumerable<IIndexableField>> docs) { IndexWriter.UpdateDocuments(delTerm, docs); MaybeCommit(); } /// <summary> /// Updates a document. </summary> /// <see cref="IndexWriter.UpdateDocument(Term, IEnumerable{IIndexableField})"/> public virtual void UpdateDocument(Term t, IEnumerable<IIndexableField> doc) { if (r.Next(5) == 3) { IndexWriter.UpdateDocuments(t, new IterableAnonymousInnerClassHelper2(this, doc)); } else { IndexWriter.UpdateDocument(t, doc); } MaybeCommit(); } private class IterableAnonymousInnerClassHelper2 : IEnumerable<IEnumerable<IIndexableField>> { private readonly RandomIndexWriter outerInstance; private IEnumerable<IIndexableField> doc; public IterableAnonymousInnerClassHelper2(RandomIndexWriter outerInstance, IEnumerable<IIndexableField> doc) { this.outerInstance = outerInstance; this.doc = doc; } public IEnumerator<IEnumerable<IIndexableField>> GetEnumerator() { return new IteratorAnonymousInnerClassHelper2(this); } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); private class IteratorAnonymousInnerClassHelper2 : IEnumerator<IEnumerable<IIndexableField>> { private readonly IterableAnonymousInnerClassHelper2 outerInstance; public IteratorAnonymousInnerClassHelper2(IterableAnonymousInnerClassHelper2 outerInstance) { this.outerInstance = outerInstance; } internal bool done; private IEnumerable<IIndexableField> current; public bool MoveNext() { if (done) { return false; } done = true; current = outerInstance.doc; return true; } public IEnumerable<IIndexableField> Current => current; object IEnumerator.Current => Current; public virtual void Reset() => throw new NotImplementedException(); public void Dispose() { } } } public virtual void AddIndexes(params Directory[] dirs) => IndexWriter.AddIndexes(dirs); public virtual void AddIndexes(params IndexReader[] readers) => IndexWriter.AddIndexes(readers); public virtual void UpdateNumericDocValue(Term term, string field, long? value) => IndexWriter.UpdateNumericDocValue(term, field, value); public virtual void UpdateBinaryDocValue(Term term, string field, BytesRef value) => IndexWriter.UpdateBinaryDocValue(term, field, value); public virtual void DeleteDocuments(Term term) => IndexWriter.DeleteDocuments(term); public virtual void DeleteDocuments(Query q) => IndexWriter.DeleteDocuments(q); public virtual void Commit() => IndexWriter.Commit(); public virtual int NumDocs => IndexWriter.NumDocs; public virtual int MaxDoc => IndexWriter.MaxDoc; public virtual void DeleteAll() => IndexWriter.DeleteAll(); public virtual DirectoryReader GetReader() => GetReader(true); private bool doRandomForceMerge = true; private bool doRandomForceMergeAssert = true; public virtual void ForceMergeDeletes(bool doWait) => IndexWriter.ForceMergeDeletes(doWait); public virtual void ForceMergeDeletes() => IndexWriter.ForceMergeDeletes(); public virtual bool DoRandomForceMerge { get => doRandomForceMerge; // LUCENENET specific - added getter (to follow MSDN property guidelines) set => doRandomForceMerge = value; } public virtual bool DoRandomForceMergeAssert { get => doRandomForceMergeAssert; // LUCENENET specific - added getter (to follow MSDN property guidelines) set => doRandomForceMergeAssert = value; } private void _DoRandomForceMerge() // LUCENENET specific - added leading underscore to keep this from colliding with the DoRandomForceMerge property { if (doRandomForceMerge) { int segCount = IndexWriter.SegmentCount; if (r.NextBoolean() || segCount == 0) { // full forceMerge if (LuceneTestCase.Verbose) { Console.WriteLine("RIW: doRandomForceMerge(1)"); } IndexWriter.ForceMerge(1); } else { // partial forceMerge int limit = TestUtil.NextInt32(r, 1, segCount); if (LuceneTestCase.Verbose) { Console.WriteLine("RIW: doRandomForceMerge(" + limit + ")"); } IndexWriter.ForceMerge(limit); if (Debugging.AssertsEnabled) Debugging.Assert(!doRandomForceMergeAssert || IndexWriter.SegmentCount <= limit, () => "limit=" + limit + " actual=" + IndexWriter.SegmentCount); } } } public virtual DirectoryReader GetReader(bool applyDeletions) { getReaderCalled = true; if (r.Next(20) == 2) { _DoRandomForceMerge(); } // If we are writing with PreFlexRW, force a full // IndexReader.open so terms are sorted in codepoint // order during searching: if (!applyDeletions || !codec.Name.Equals("Lucene3x", StringComparison.Ordinal) && r.NextBoolean()) { if (LuceneTestCase.Verbose) { Console.WriteLine("RIW.getReader: use NRT reader"); } if (r.Next(5) == 1) { IndexWriter.Commit(); } return IndexWriter.GetReader(applyDeletions); } else { if (LuceneTestCase.Verbose) { Console.WriteLine("RIW.getReader: open new reader"); } IndexWriter.Commit(); if (r.NextBoolean()) { return DirectoryReader.Open(IndexWriter.Directory, TestUtil.NextInt32(r, 1, 10)); } else { return IndexWriter.GetReader(applyDeletions); } } } // LUCENENET specific: Implemented dispose pattern /// <summary> /// Dispose this writer. </summary> /// <seealso cref="IndexWriter.Dispose()"/> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Dispose this writer. </summary> /// <seealso cref="IndexWriter.Dispose(bool)"/> protected virtual void Dispose(bool disposing) { if (disposing) { // if someone isn't using getReader() API, we want to be sure to // forceMerge since presumably they might open a reader on the dir. if (getReaderCalled == false && r.Next(8) == 2) { _DoRandomForceMerge(); } IndexWriter.Dispose(); } } /// <summary> /// Forces a forceMerge. /// <para/> /// NOTE: this should be avoided in tests unless absolutely necessary, /// as it will result in less test coverage. </summary> /// <seealso cref="IndexWriter.ForceMerge(int)"/> public virtual void ForceMerge(int maxSegmentCount) { IndexWriter.ForceMerge(maxSegmentCount); } // LUCENENET specific - de-nested TestPointInfoStream // LUCENENET specific - de-nested ITestPoint } public sealed class TestPointInfoStream : InfoStream { private readonly InfoStream @delegate; private readonly ITestPoint testPoint; public TestPointInfoStream(InfoStream @delegate, ITestPoint testPoint) { this.@delegate = @delegate ?? new NullInfoStream(); this.testPoint = testPoint; } protected override void Dispose(bool disposing) { if (disposing) { @delegate.Dispose(); } } public override void Message(string component, string message) { if ("TP".Equals(component, StringComparison.Ordinal)) { testPoint.Apply(message); } if (@delegate.IsEnabled(component)) { @delegate.Message(component, message); } } public override bool IsEnabled(string component) { return "TP".Equals(component, StringComparison.Ordinal) || @delegate.IsEnabled(component); } } /// <summary> /// Simple interface that is executed for each <c>TP</c> <see cref="InfoStream"/> component /// message. See also <see cref="RandomIndexWriter.MockIndexWriter(Directory, IndexWriterConfig, ITestPoint)"/>. /// </summary> public interface ITestPoint { void Apply(string message); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ModestTree; namespace Zenject { public class InjectContext : IDisposable { public static readonly StaticMemoryPool<DiContainer, Type, InjectContext> Pool = new StaticMemoryPool<DiContainer, Type, InjectContext>(OnSpawned, OnDespawned); readonly BindingId _bindingId = new BindingId(); Type _objectType; InjectContext _parentContext; object _objectInstance; string _memberName; bool _optional; InjectSources _sourceType; object _fallBackValue; object _concreteIdentifier; DiContainer _container; public InjectContext() { SetDefaults(); } static void OnSpawned(DiContainer container, Type memberType, InjectContext that) { Assert.IsNull(that._container); that._container = container; that._bindingId.Type = memberType; } static void OnDespawned(InjectContext that) { that.SetDefaults(); } public InjectContext(DiContainer container, Type memberType) : this() { Container = container; MemberType = memberType; } public InjectContext(DiContainer container, Type memberType, object identifier) : this(container, memberType) { Identifier = identifier; } public InjectContext(DiContainer container, Type memberType, object identifier, bool optional) : this(container, memberType, identifier) { Optional = optional; } public void Dispose() { Pool.Despawn(this); } void SetDefaults() { _objectType = null; _parentContext = null; _objectInstance = null; _memberName = ""; _bindingId.Identifier = null; _bindingId.Type = null; _optional = false; _sourceType = InjectSources.Any; _fallBackValue = null; _container = null; } public BindingId BindingId { get { return _bindingId; } } // The type of the object which is having its members injected // NOTE: This is null for root calls to Resolve<> or Instantiate<> public Type ObjectType { get { return _objectType; } set { _objectType = value; } } // Parent context that triggered the creation of ObjectType // This can be used for very complex conditions using parent info such as identifiers, types, etc. // Note that ParentContext.MemberType is not necessarily the same as ObjectType, // since the ObjectType could be a derived type from ParentContext.MemberType public InjectContext ParentContext { get { return _parentContext; } set { _parentContext = value; } } // The instance which is having its members injected // Note that this is null when injecting into the constructor public object ObjectInstance { get { return _objectInstance; } set { _objectInstance = value; } } // Identifier - most of the time this is null // It will match 'foo' in this example: // ... In an installer somewhere: // Container.Bind<Foo>("foo").AsSingle(); // ... // ... In a constructor: // public Foo([Inject(Id = "foo") Foo foo) public object Identifier { get { return _bindingId.Identifier; } set { _bindingId.Identifier = value; } } // The constructor parameter name, or field name, or property name public string MemberName { get { return _memberName; } set { _memberName = value; } } // The type of the constructor parameter, field or property public Type MemberType { get { return _bindingId.Type; } set { _bindingId.Type = value; } } // When optional, null is a valid value to be returned public bool Optional { get { return _optional; } set { _optional = value; } } // When set to true, this will only look up dependencies in the local container and will not // search in parent containers public InjectSources SourceType { get { return _sourceType; } set { _sourceType = value; } } public object ConcreteIdentifier { get { return _concreteIdentifier; } set { _concreteIdentifier = value; } } // When optional, this is used to provide the value public object FallBackValue { get { return _fallBackValue; } set { _fallBackValue = value; } } // The container used for this injection public DiContainer Container { get { return _container; } set { _container = value; } } public IEnumerable<InjectContext> ParentContexts { get { if (ParentContext == null) { yield break; } yield return ParentContext; foreach (var context in ParentContext.ParentContexts) { yield return context; } } } public IEnumerable<InjectContext> ParentContextsAndSelf { get { yield return this; foreach (var context in ParentContexts) { yield return context; } } } // This will return the types of all the objects that are being injected // So if you have class Foo which has constructor parameter of type IBar, // and IBar resolves to Bar, this will be equal to (Bar, Foo) public IEnumerable<Type> AllObjectTypes { get { foreach (var context in ParentContextsAndSelf) { if (context.ObjectType != null) { yield return context.ObjectType; } } } } public InjectContext CreateSubContext(Type memberType) { return CreateSubContext(memberType, null); } public InjectContext CreateSubContext(Type memberType, object identifier) { var subContext = new InjectContext(); subContext.ParentContext = this; subContext.Identifier = identifier; subContext.MemberType = memberType; // Clear these subContext.ConcreteIdentifier = null; subContext.MemberName = ""; subContext.FallBackValue = null; // Inherit these ones by default subContext.ObjectType = this.ObjectType; subContext.ObjectInstance = this.ObjectInstance; subContext.Optional = this.Optional; subContext.SourceType = this.SourceType; subContext.Container = this.Container; return subContext; } public InjectContext Clone() { var clone = new InjectContext(); clone.ObjectType = this.ObjectType; clone.ParentContext = this.ParentContext; clone.ConcreteIdentifier = this.ConcreteIdentifier; clone.ObjectInstance = this.ObjectInstance; clone.Identifier = this.Identifier; clone.MemberType = this.MemberType; clone.MemberName = this.MemberName; clone.Optional = this.Optional; clone.SourceType = this.SourceType; clone.FallBackValue = this.FallBackValue; clone.Container = this.Container; return clone; } // This is very useful to print out for debugging purposes public string GetObjectGraphString() { var result = new StringBuilder(); foreach (var context in ParentContextsAndSelf.Reverse()) { if (context.ObjectType == null) { continue; } result.AppendLine(context.ObjectType.PrettyName()); } return result.ToString(); } } }
/******************************************************************** 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 Multiverse.Tools.ModelViewer { partial class ModelViewer { /// <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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ModelViewer)); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.loadModelToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.designateRepositoryMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.viewToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.wireFrameToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.displayTerrainToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.showGroundPlaneToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.showCollisionVolumesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.showBoundingBoxToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.spinCameraToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.spinLightToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.displayBoneInformationToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.setMaximumFramesPerSecondToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.bgColorToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.materialSchemeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripHelpItem = new System.Windows.Forms.ToolStripMenuItem(); this.launchReleaseNotesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.submitABugReportToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.fpsStatusLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.fpsStatusValueLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.modelHeightLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.modelHeightValueLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.spinCameraToolStripButton = new System.Windows.Forms.ToolStripButton(); this.mouseModeToolStripButton = new System.Windows.Forms.ToolStripSplitButton(); this.moveCameraToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.moveDirectionalLightToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.colorDialog1 = new System.Windows.Forms.ColorDialog(); this.axiomPictureBox = new System.Windows.Forms.PictureBox(); this.bonesPage = new System.Windows.Forms.TabPage(); this.showBonesGroupBox = new System.Windows.Forms.GroupBox(); this.boneAxisSizeTrackBar = new System.Windows.Forms.TrackBar(); this.showBonesCheckBox = new System.Windows.Forms.CheckBox(); this.boneAxisSizeLabel = new System.Windows.Forms.Label(); this.bonesLinkLabel = new System.Windows.Forms.LinkLabel(); this.bonesTreeView = new System.Windows.Forms.TreeView(); this.cameraPage = new System.Windows.Forms.TabPage(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.cameraControlsButton = new System.Windows.Forms.Button(); this.cameraFocusHeightGroupBox = new System.Windows.Forms.GroupBox(); this.cameraControlsLinkLabel = new System.Windows.Forms.LinkLabel(); this.cameraFocusHeightTrackbar = new System.Windows.Forms.TrackBar(); this.label2 = new System.Windows.Forms.Label(); this.cameraNearDistanceGroupBox = new System.Windows.Forms.GroupBox(); this.nearDistanceValueLabel = new System.Windows.Forms.Label(); this.whatsNearDistanceLabel = new System.Windows.Forms.LinkLabel(); this.cameraNearDistanceTrackBar = new System.Windows.Forms.TrackBar(); this.label3 = new System.Windows.Forms.Label(); this.showNormalsGroupBox = new System.Windows.Forms.GroupBox(); this.linkLabel1 = new System.Windows.Forms.LinkLabel(); this.showNormalsCheckBox = new System.Windows.Forms.CheckBox(); this.normalsAxisSizeLabel = new System.Windows.Forms.Label(); this.normalsAxisSizeTrackBar = new System.Windows.Forms.TrackBar(); this.lightingPage = new System.Windows.Forms.TabPage(); this.lightingFlowLayoutPanel = new System.Windows.Forms.FlowLayoutPanel(); this.ambientLightButton = new System.Windows.Forms.Button(); this.ambientLightGroupBox = new System.Windows.Forms.GroupBox(); this.ambientLightLinkLabel = new System.Windows.Forms.LinkLabel(); this.ambientLightColorLabel = new System.Windows.Forms.Label(); this.ambientLightColorButton = new System.Windows.Forms.Button(); this.directionalLightButton = new System.Windows.Forms.Button(); this.directionalLightGroupBox = new System.Windows.Forms.GroupBox(); this.directionalLightLinkLabel = new System.Windows.Forms.LinkLabel(); this.label1 = new System.Windows.Forms.Label(); this.lightZenithTrackBar = new System.Windows.Forms.TrackBar(); this.lightAzimuthTrackBar = new System.Windows.Forms.TrackBar(); this.specularColorButton = new System.Windows.Forms.Button(); this.diffuseColorButton = new System.Windows.Forms.Button(); this.specularColorLabel = new System.Windows.Forms.Label(); this.diffuseColorLabel = new System.Windows.Forms.Label(); this.socketsPage = new System.Windows.Forms.TabPage(); this.showSocketGroupBox = new System.Windows.Forms.GroupBox(); this.socketAxisSizeTrackBar = new System.Windows.Forms.TrackBar(); this.socketAxisSizeLabel = new System.Windows.Forms.Label(); this.showSocketsCheckBox = new System.Windows.Forms.CheckBox(); this.socketsLinkLabel = new System.Windows.Forms.LinkLabel(); this.parentBoneValueLabel = new System.Windows.Forms.Label(); this.parentBoneLabel = new System.Windows.Forms.Label(); this.socketListBox = new System.Windows.Forms.CheckedListBox(); this.animPage = new System.Windows.Forms.TabPage(); this.timeCurrentLabel = new System.Windows.Forms.Label(); this.timeEndLabel = new System.Windows.Forms.Label(); this.timeStartLabel = new System.Windows.Forms.Label(); this.animationTrackBar = new System.Windows.Forms.TrackBar(); this.animLinkLabel = new System.Windows.Forms.LinkLabel(); this.animationSpeedTextBox = new System.Windows.Forms.TextBox(); this.animationSpeedLabel = new System.Windows.Forms.Label(); this.loopingCheckBox = new System.Windows.Forms.CheckBox(); this.playStopButton = new System.Windows.Forms.Button(); this.animationListBox = new System.Windows.Forms.ListBox(); this.subMeshPage = new System.Windows.Forms.TabPage(); this.subMeshTreeView = new System.Windows.Forms.TreeView(); this.subMeshLinkLabel = new System.Windows.Forms.LinkLabel(); this.materialLabel = new System.Windows.Forms.Label(); this.materialTextBox = new System.Windows.Forms.TextBox(); this.hideButton = new System.Windows.Forms.Button(); this.showButton = new System.Windows.Forms.Button(); this.subMeshTextBox = new System.Windows.Forms.TextBox(); this.hideShowLabel = new System.Windows.Forms.Label(); this.hideAllButton = new System.Windows.Forms.Button(); this.showAllButton = new System.Windows.Forms.Button(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.menuStrip1.SuspendLayout(); this.statusStrip1.SuspendLayout(); this.toolStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.axiomPictureBox)).BeginInit(); this.bonesPage.SuspendLayout(); this.showBonesGroupBox.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.boneAxisSizeTrackBar)).BeginInit(); this.cameraPage.SuspendLayout(); this.flowLayoutPanel1.SuspendLayout(); this.cameraFocusHeightGroupBox.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.cameraFocusHeightTrackbar)).BeginInit(); this.cameraNearDistanceGroupBox.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.cameraNearDistanceTrackBar)).BeginInit(); this.showNormalsGroupBox.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.normalsAxisSizeTrackBar)).BeginInit(); this.lightingPage.SuspendLayout(); this.lightingFlowLayoutPanel.SuspendLayout(); this.ambientLightGroupBox.SuspendLayout(); this.directionalLightGroupBox.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.lightZenithTrackBar)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.lightAzimuthTrackBar)).BeginInit(); this.socketsPage.SuspendLayout(); this.showSocketGroupBox.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.socketAxisSizeTrackBar)).BeginInit(); this.animPage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.animationTrackBar)).BeginInit(); this.subMeshPage.SuspendLayout(); this.tabControl1.SuspendLayout(); this.SuspendLayout(); // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.viewToolStripMenuItem1, this.helpToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(1016, 24); this.menuStrip1.TabIndex = 0; this.menuStrip1.Text = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.loadModelToolStripMenuItem, this.designateRepositoryMenuItem, this.exitToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20); this.fileToolStripMenuItem.Text = "&File"; // // loadModelToolStripMenuItem // this.loadModelToolStripMenuItem.Name = "loadModelToolStripMenuItem"; this.loadModelToolStripMenuItem.Size = new System.Drawing.Size(219, 22); this.loadModelToolStripMenuItem.Text = "Load &Model..."; this.loadModelToolStripMenuItem.Click += new System.EventHandler(this.loadModelToolStripMenuItem_Click); // // designateRepositoryMenuItem // this.designateRepositoryMenuItem.Name = "designateRepositoryMenuItem"; this.designateRepositoryMenuItem.Size = new System.Drawing.Size(219, 22); this.designateRepositoryMenuItem.Text = "Designate &Asset Repository..."; this.designateRepositoryMenuItem.Click += new System.EventHandler(this.toolStripMenuItem1_Click); // // exitToolStripMenuItem // this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.Size = new System.Drawing.Size(219, 22); this.exitToolStripMenuItem.Text = "Exit"; this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click); // // viewToolStripMenuItem1 // this.viewToolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.wireFrameToolStripMenuItem, this.displayTerrainToolStripMenuItem, this.showGroundPlaneToolStripMenuItem, this.showCollisionVolumesToolStripMenuItem, this.showBoundingBoxToolStripMenuItem, this.spinCameraToolStripMenuItem, this.spinLightToolStripMenuItem, this.displayBoneInformationToolStripMenuItem, this.setMaximumFramesPerSecondToolStripMenuItem, this.bgColorToolStripMenuItem, this.materialSchemeToolStripMenuItem}); this.viewToolStripMenuItem1.Name = "viewToolStripMenuItem1"; this.viewToolStripMenuItem1.Size = new System.Drawing.Size(41, 20); this.viewToolStripMenuItem1.Text = "&View"; this.viewToolStripMenuItem1.DropDownOpening += new System.EventHandler(this.viewToolStripMenuItem1_DropDownOpening); // // wireFrameToolStripMenuItem // this.wireFrameToolStripMenuItem.Name = "wireFrameToolStripMenuItem"; this.wireFrameToolStripMenuItem.Size = new System.Drawing.Size(232, 22); this.wireFrameToolStripMenuItem.Text = "Wire Frame"; this.wireFrameToolStripMenuItem.Click += new System.EventHandler(this.wireFrameToolStripMenuItem_Click); // // displayTerrainToolStripMenuItem // this.displayTerrainToolStripMenuItem.Name = "displayTerrainToolStripMenuItem"; this.displayTerrainToolStripMenuItem.Size = new System.Drawing.Size(232, 22); this.displayTerrainToolStripMenuItem.Text = "Display Terrain"; this.displayTerrainToolStripMenuItem.Click += new System.EventHandler(this.displayTerrainToolStripMenuItem_Click); // // showGroundPlaneToolStripMenuItem // this.showGroundPlaneToolStripMenuItem.Name = "showGroundPlaneToolStripMenuItem"; this.showGroundPlaneToolStripMenuItem.Size = new System.Drawing.Size(232, 22); this.showGroundPlaneToolStripMenuItem.Text = "Show Ground Plane"; this.showGroundPlaneToolStripMenuItem.Click += new System.EventHandler(this.showGroundPlaneToolStripMenuItem_Click); // // showCollisionVolumesToolStripMenuItem // this.showCollisionVolumesToolStripMenuItem.CheckOnClick = true; this.showCollisionVolumesToolStripMenuItem.Name = "showCollisionVolumesToolStripMenuItem"; this.showCollisionVolumesToolStripMenuItem.Size = new System.Drawing.Size(232, 22); this.showCollisionVolumesToolStripMenuItem.Text = "Show Collision Volumes"; this.showCollisionVolumesToolStripMenuItem.Click += new System.EventHandler(this.showCollisionVolumesToolStripMenuItem_Click); // // showBoundingBoxToolStripMenuItem // this.showBoundingBoxToolStripMenuItem.Name = "showBoundingBoxToolStripMenuItem"; this.showBoundingBoxToolStripMenuItem.Size = new System.Drawing.Size(232, 22); this.showBoundingBoxToolStripMenuItem.Text = "Show Bounding Box"; this.showBoundingBoxToolStripMenuItem.Click += new System.EventHandler(this.showBoundingBoxToolStripMenuItem_Click); // // spinCameraToolStripMenuItem // this.spinCameraToolStripMenuItem.Name = "spinCameraToolStripMenuItem"; this.spinCameraToolStripMenuItem.Size = new System.Drawing.Size(232, 22); this.spinCameraToolStripMenuItem.Text = "Spin Camera"; this.spinCameraToolStripMenuItem.Click += new System.EventHandler(this.spinCameraToolStripMenuItem_Click); // // spinLightToolStripMenuItem // this.spinLightToolStripMenuItem.Name = "spinLightToolStripMenuItem"; this.spinLightToolStripMenuItem.Size = new System.Drawing.Size(232, 22); this.spinLightToolStripMenuItem.Text = "Spin Light"; this.spinLightToolStripMenuItem.Click += new System.EventHandler(this.spinLightToolStripMenuItem_Click); // // displayBoneInformationToolStripMenuItem // this.displayBoneInformationToolStripMenuItem.Name = "displayBoneInformationToolStripMenuItem"; this.displayBoneInformationToolStripMenuItem.Size = new System.Drawing.Size(232, 22); this.displayBoneInformationToolStripMenuItem.Text = "Display Bone Information"; this.displayBoneInformationToolStripMenuItem.Click += new System.EventHandler(this.displayBoneInformationToolStripMenuItem_Click); // // setMaximumFramesPerSecondToolStripMenuItem // this.setMaximumFramesPerSecondToolStripMenuItem.Name = "setMaximumFramesPerSecondToolStripMenuItem"; this.setMaximumFramesPerSecondToolStripMenuItem.Size = new System.Drawing.Size(232, 22); this.setMaximumFramesPerSecondToolStripMenuItem.Text = "Set Maximum Frames Per Second"; this.setMaximumFramesPerSecondToolStripMenuItem.Click += new System.EventHandler(this.setMaximumFramesPerSecondToolStripMenuItem_Click); // // bgColorToolStripMenuItem // this.bgColorToolStripMenuItem.Name = "bgColorToolStripMenuItem"; this.bgColorToolStripMenuItem.Size = new System.Drawing.Size(232, 22); this.bgColorToolStripMenuItem.Text = "Set Background Color"; this.bgColorToolStripMenuItem.Click += new System.EventHandler(this.bgColorToolStripMenuItem_Click); // // materialSchemeToolStripMenuItem // this.materialSchemeToolStripMenuItem.Enabled = false; this.materialSchemeToolStripMenuItem.Name = "materialSchemeToolStripMenuItem"; this.materialSchemeToolStripMenuItem.Size = new System.Drawing.Size(232, 22); this.materialSchemeToolStripMenuItem.Text = "Material Scheme"; this.materialSchemeToolStripMenuItem.Click += new System.EventHandler(this.materialSchemeToolStripMenuItem_Click); // // helpToolStripMenuItem // this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.helpToolStripHelpItem, this.launchReleaseNotesToolStripMenuItem, this.submitABugReportToolStripMenuItem, this.aboutToolStripMenuItem}); this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; this.helpToolStripMenuItem.Size = new System.Drawing.Size(40, 20); this.helpToolStripMenuItem.Text = "&Help"; // // helpToolStripHelpItem // this.helpToolStripHelpItem.Name = "helpToolStripHelpItem"; this.helpToolStripHelpItem.Size = new System.Drawing.Size(198, 22); this.helpToolStripHelpItem.Text = "Launch Online Help"; this.helpToolStripHelpItem.Click += new System.EventHandler(this.helpToolStripHelpItem_Click); // // launchReleaseNotesToolStripMenuItem // this.launchReleaseNotesToolStripMenuItem.Name = "launchReleaseNotesToolStripMenuItem"; this.launchReleaseNotesToolStripMenuItem.Size = new System.Drawing.Size(198, 22); this.launchReleaseNotesToolStripMenuItem.Text = "Launch Release Notes"; this.launchReleaseNotesToolStripMenuItem.Click += new System.EventHandler(this.launchReleaseNotesToolStripMenuItem_Click); // // submitABugReportToolStripMenuItem // this.submitABugReportToolStripMenuItem.Name = "submitABugReportToolStripMenuItem"; this.submitABugReportToolStripMenuItem.Size = new System.Drawing.Size(198, 22); this.submitABugReportToolStripMenuItem.Text = "Submit Feedback or a Bug"; this.submitABugReportToolStripMenuItem.Click += new System.EventHandler(this.submitABugReportToolStripMenuItem_Click); // // aboutToolStripMenuItem // this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem"; this.aboutToolStripMenuItem.Size = new System.Drawing.Size(198, 22); this.aboutToolStripMenuItem.Text = "About ModelViewer"; this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click); // // statusStrip1 // this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fpsStatusLabel, this.fpsStatusValueLabel, this.modelHeightLabel, this.modelHeightValueLabel}); this.statusStrip1.Location = new System.Drawing.Point(0, 719); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Size = new System.Drawing.Size(1016, 22); this.statusStrip1.TabIndex = 1; this.statusStrip1.Text = "statusStrip1"; // // fpsStatusLabel // this.fpsStatusLabel.Name = "fpsStatusLabel"; this.fpsStatusLabel.Size = new System.Drawing.Size(29, 17); this.fpsStatusLabel.Text = "FPS:"; // // fpsStatusValueLabel // this.fpsStatusValueLabel.Name = "fpsStatusValueLabel"; this.fpsStatusValueLabel.Size = new System.Drawing.Size(0, 17); // // modelHeightLabel // this.modelHeightLabel.Name = "modelHeightLabel"; this.modelHeightLabel.Size = new System.Drawing.Size(73, 17); this.modelHeightLabel.Text = "Model Height:"; // // modelHeightValueLabel // this.modelHeightValueLabel.Name = "modelHeightValueLabel"; this.modelHeightValueLabel.Size = new System.Drawing.Size(0, 17); // // toolStrip1 // this.toolStrip1.ImageScalingSize = new System.Drawing.Size(32, 32); this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.spinCameraToolStripButton, this.mouseModeToolStripButton}); this.toolStrip1.Location = new System.Drawing.Point(0, 24); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(1016, 39); this.toolStrip1.TabIndex = 3; this.toolStrip1.Text = "toolStrip1"; // // spinCameraToolStripButton // this.spinCameraToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.spinCameraToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("spinCameraToolStripButton.Image"))); this.spinCameraToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.spinCameraToolStripButton.Name = "spinCameraToolStripButton"; this.spinCameraToolStripButton.Size = new System.Drawing.Size(36, 36); this.spinCameraToolStripButton.Text = "Spin Camera"; this.spinCameraToolStripButton.Click += new System.EventHandler(this.toolStripButton1_Click); // // mouseModeToolStripButton // this.mouseModeToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.mouseModeToolStripButton.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.moveCameraToolStripMenuItem, this.moveDirectionalLightToolStripMenuItem}); this.mouseModeToolStripButton.Image = global::ModelViewer.Properties.Resources.camera; this.mouseModeToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.mouseModeToolStripButton.Name = "mouseModeToolStripButton"; this.mouseModeToolStripButton.Size = new System.Drawing.Size(48, 36); this.mouseModeToolStripButton.Text = "Mouse Mode"; // // moveCameraToolStripMenuItem // this.moveCameraToolStripMenuItem.Image = global::ModelViewer.Properties.Resources.camera; this.moveCameraToolStripMenuItem.Name = "moveCameraToolStripMenuItem"; this.moveCameraToolStripMenuItem.Size = new System.Drawing.Size(179, 22); this.moveCameraToolStripMenuItem.Text = "Move Camera"; this.moveCameraToolStripMenuItem.Click += new System.EventHandler(this.moveCameraToolStripMenuItem_Click); // // moveDirectionalLightToolStripMenuItem // this.moveDirectionalLightToolStripMenuItem.Image = global::ModelViewer.Properties.Resources.lightbulb; this.moveDirectionalLightToolStripMenuItem.Name = "moveDirectionalLightToolStripMenuItem"; this.moveDirectionalLightToolStripMenuItem.Size = new System.Drawing.Size(179, 22); this.moveDirectionalLightToolStripMenuItem.Text = "Move Directional Light"; this.moveDirectionalLightToolStripMenuItem.Click += new System.EventHandler(this.moveDirectionalLightToolStripMenuItem_Click); // // colorDialog1 // this.colorDialog1.AnyColor = true; this.colorDialog1.FullOpen = true; // // axiomPictureBox // this.axiomPictureBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.axiomPictureBox.Location = new System.Drawing.Point(251, 66); this.axiomPictureBox.Name = "axiomPictureBox"; this.axiomPictureBox.Size = new System.Drawing.Size(765, 650); this.axiomPictureBox.TabIndex = 2; this.axiomPictureBox.TabStop = false; // // bonesPage // this.bonesPage.Controls.Add(this.showBonesGroupBox); this.bonesPage.Controls.Add(this.bonesLinkLabel); this.bonesPage.Controls.Add(this.bonesTreeView); this.bonesPage.Location = new System.Drawing.Point(4, 40); this.bonesPage.Name = "bonesPage"; this.bonesPage.Padding = new System.Windows.Forms.Padding(3); this.bonesPage.Size = new System.Drawing.Size(237, 606); this.bonesPage.TabIndex = 5; this.bonesPage.Text = "Bones"; this.bonesPage.UseVisualStyleBackColor = true; // // showBonesGroupBox // this.showBonesGroupBox.Controls.Add(this.boneAxisSizeTrackBar); this.showBonesGroupBox.Controls.Add(this.showBonesCheckBox); this.showBonesGroupBox.Controls.Add(this.boneAxisSizeLabel); this.showBonesGroupBox.Location = new System.Drawing.Point(6, 340); this.showBonesGroupBox.Name = "showBonesGroupBox"; this.showBonesGroupBox.Size = new System.Drawing.Size(225, 118); this.showBonesGroupBox.TabIndex = 11; this.showBonesGroupBox.TabStop = false; // // boneAxisSizeTrackBar // this.boneAxisSizeTrackBar.BackColor = System.Drawing.SystemColors.Control; this.boneAxisSizeTrackBar.Location = new System.Drawing.Point(6, 67); this.boneAxisSizeTrackBar.Maximum = 20; this.boneAxisSizeTrackBar.Name = "boneAxisSizeTrackBar"; this.boneAxisSizeTrackBar.Size = new System.Drawing.Size(211, 45); this.boneAxisSizeTrackBar.TabIndex = 9; this.boneAxisSizeTrackBar.TickStyle = System.Windows.Forms.TickStyle.None; this.boneAxisSizeTrackBar.Scroll += new System.EventHandler(this.boneAxisSizeTrackBar_Scroll); // // showBonesCheckBox // this.showBonesCheckBox.AutoSize = true; this.showBonesCheckBox.Location = new System.Drawing.Point(6, 19); this.showBonesCheckBox.Name = "showBonesCheckBox"; this.showBonesCheckBox.Size = new System.Drawing.Size(86, 17); this.showBonesCheckBox.TabIndex = 8; this.showBonesCheckBox.Text = "Show Bones"; this.showBonesCheckBox.UseVisualStyleBackColor = true; this.showBonesCheckBox.CheckedChanged += new System.EventHandler(this.showBonesCheckBox_CheckedChanged); // // boneAxisSizeLabel // this.boneAxisSizeLabel.AutoSize = true; this.boneAxisSizeLabel.Location = new System.Drawing.Point(3, 51); this.boneAxisSizeLabel.Name = "boneAxisSizeLabel"; this.boneAxisSizeLabel.Size = new System.Drawing.Size(77, 13); this.boneAxisSizeLabel.TabIndex = 10; this.boneAxisSizeLabel.Text = "Bone Axis Size"; // // bonesLinkLabel // this.bonesLinkLabel.AutoSize = true; this.bonesLinkLabel.Location = new System.Drawing.Point(154, 575); this.bonesLinkLabel.Name = "bonesLinkLabel"; this.bonesLinkLabel.Size = new System.Drawing.Size(69, 13); this.bonesLinkLabel.TabIndex = 7; this.bonesLinkLabel.TabStop = true; this.bonesLinkLabel.Text = "What\'s This?"; this.bonesLinkLabel.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.bonesLinkLabel_LinkClicked); // // bonesTreeView // this.bonesTreeView.Location = new System.Drawing.Point(0, 0); this.bonesTreeView.Name = "bonesTreeView"; this.bonesTreeView.Size = new System.Drawing.Size(237, 334); this.bonesTreeView.TabIndex = 0; // // cameraPage // this.cameraPage.Controls.Add(this.flowLayoutPanel1); this.cameraPage.Location = new System.Drawing.Point(4, 40); this.cameraPage.Name = "cameraPage"; this.cameraPage.Padding = new System.Windows.Forms.Padding(3); this.cameraPage.Size = new System.Drawing.Size(237, 606); this.cameraPage.TabIndex = 3; this.cameraPage.Text = "Camera"; this.cameraPage.UseVisualStyleBackColor = true; // // flowLayoutPanel1 // this.flowLayoutPanel1.Controls.Add(this.cameraControlsButton); this.flowLayoutPanel1.Controls.Add(this.cameraFocusHeightGroupBox); this.flowLayoutPanel1.Controls.Add(this.cameraNearDistanceGroupBox); this.flowLayoutPanel1.Controls.Add(this.showNormalsGroupBox); this.flowLayoutPanel1.Location = new System.Drawing.Point(3, 6); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; this.flowLayoutPanel1.Size = new System.Drawing.Size(234, 433); this.flowLayoutPanel1.TabIndex = 0; // // cameraControlsButton // this.cameraControlsButton.Image = ((System.Drawing.Image)(resources.GetObject("cameraControlsButton.Image"))); this.cameraControlsButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.cameraControlsButton.Location = new System.Drawing.Point(3, 3); this.cameraControlsButton.Name = "cameraControlsButton"; this.cameraControlsButton.Size = new System.Drawing.Size(228, 26); this.cameraControlsButton.TabIndex = 0; this.cameraControlsButton.Text = "Camera Controls"; this.cameraControlsButton.UseVisualStyleBackColor = true; this.cameraControlsButton.Click += new System.EventHandler(this.cameraControlsButton_Click); // // cameraFocusHeightGroupBox // this.cameraFocusHeightGroupBox.Controls.Add(this.cameraControlsLinkLabel); this.cameraFocusHeightGroupBox.Controls.Add(this.cameraFocusHeightTrackbar); this.cameraFocusHeightGroupBox.Controls.Add(this.label2); this.cameraFocusHeightGroupBox.Location = new System.Drawing.Point(3, 35); this.cameraFocusHeightGroupBox.Name = "cameraFocusHeightGroupBox"; this.cameraFocusHeightGroupBox.Size = new System.Drawing.Size(228, 125); this.cameraFocusHeightGroupBox.TabIndex = 1; this.cameraFocusHeightGroupBox.TabStop = false; // // cameraControlsLinkLabel // this.cameraControlsLinkLabel.AutoSize = true; this.cameraControlsLinkLabel.Location = new System.Drawing.Point(40, 63); this.cameraControlsLinkLabel.Name = "cameraControlsLinkLabel"; this.cameraControlsLinkLabel.Size = new System.Drawing.Size(69, 13); this.cameraControlsLinkLabel.TabIndex = 2; this.cameraControlsLinkLabel.TabStop = true; this.cameraControlsLinkLabel.Text = "What\'s This?"; this.cameraControlsLinkLabel.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.cameraControlsLinkLabel_LinkClicked); // // cameraFocusHeightTrackbar // this.cameraFocusHeightTrackbar.LargeChange = 10; this.cameraFocusHeightTrackbar.Location = new System.Drawing.Point(167, 19); this.cameraFocusHeightTrackbar.Maximum = 100; this.cameraFocusHeightTrackbar.Name = "cameraFocusHeightTrackbar"; this.cameraFocusHeightTrackbar.Orientation = System.Windows.Forms.Orientation.Vertical; this.cameraFocusHeightTrackbar.Size = new System.Drawing.Size(45, 96); this.cameraFocusHeightTrackbar.TabIndex = 1; this.cameraFocusHeightTrackbar.TickStyle = System.Windows.Forms.TickStyle.None; this.cameraFocusHeightTrackbar.Value = 50; this.cameraFocusHeightTrackbar.Scroll += new System.EventHandler(this.cameraFocusHeightTrackbar_Scroll); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(26, 19); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(112, 13); this.label2.TabIndex = 0; this.label2.Text = "Camera Focus Height:"; // // cameraNearDistanceGroupBox // this.cameraNearDistanceGroupBox.Controls.Add(this.nearDistanceValueLabel); this.cameraNearDistanceGroupBox.Controls.Add(this.whatsNearDistanceLabel); this.cameraNearDistanceGroupBox.Controls.Add(this.cameraNearDistanceTrackBar); this.cameraNearDistanceGroupBox.Controls.Add(this.label3); this.cameraNearDistanceGroupBox.Location = new System.Drawing.Point(3, 166); this.cameraNearDistanceGroupBox.Name = "cameraNearDistanceGroupBox"; this.cameraNearDistanceGroupBox.Size = new System.Drawing.Size(228, 125); this.cameraNearDistanceGroupBox.TabIndex = 2; this.cameraNearDistanceGroupBox.TabStop = false; // // nearDistanceValueLabel // this.nearDistanceValueLabel.AutoSize = true; this.nearDistanceValueLabel.Location = new System.Drawing.Point(44, 37); this.nearDistanceValueLabel.Name = "nearDistanceValueLabel"; this.nearDistanceValueLabel.Size = new System.Drawing.Size(0, 13); this.nearDistanceValueLabel.TabIndex = 3; // // whatsNearDistanceLabel // this.whatsNearDistanceLabel.AutoSize = true; this.whatsNearDistanceLabel.Location = new System.Drawing.Point(40, 63); this.whatsNearDistanceLabel.Name = "whatsNearDistanceLabel"; this.whatsNearDistanceLabel.Size = new System.Drawing.Size(69, 13); this.whatsNearDistanceLabel.TabIndex = 2; this.whatsNearDistanceLabel.TabStop = true; this.whatsNearDistanceLabel.Text = "What\'s This?"; this.whatsNearDistanceLabel.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.whatsNearDistanceLabel_LinkClicked); // // cameraNearDistanceTrackBar // this.cameraNearDistanceTrackBar.LargeChange = 10; this.cameraNearDistanceTrackBar.Location = new System.Drawing.Point(167, 19); this.cameraNearDistanceTrackBar.Maximum = 100; this.cameraNearDistanceTrackBar.Name = "cameraNearDistanceTrackBar"; this.cameraNearDistanceTrackBar.Orientation = System.Windows.Forms.Orientation.Vertical; this.cameraNearDistanceTrackBar.Size = new System.Drawing.Size(45, 96); this.cameraNearDistanceTrackBar.TabIndex = 1; this.cameraNearDistanceTrackBar.TickStyle = System.Windows.Forms.TickStyle.None; this.cameraNearDistanceTrackBar.Value = 50; this.cameraNearDistanceTrackBar.Scroll += new System.EventHandler(this.cameraNearDistanceTrackBar_Scroll); // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(26, 19); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(117, 13); this.label3.TabIndex = 0; this.label3.Text = "Camera Near Distance:"; // // showNormalsGroupBox // this.showNormalsGroupBox.Controls.Add(this.linkLabel1); this.showNormalsGroupBox.Controls.Add(this.showNormalsCheckBox); this.showNormalsGroupBox.Controls.Add(this.normalsAxisSizeLabel); this.showNormalsGroupBox.Controls.Add(this.normalsAxisSizeTrackBar); this.showNormalsGroupBox.Location = new System.Drawing.Point(3, 297); this.showNormalsGroupBox.Name = "showNormalsGroupBox"; this.showNormalsGroupBox.Size = new System.Drawing.Size(228, 124); this.showNormalsGroupBox.TabIndex = 14; this.showNormalsGroupBox.TabStop = false; // // linkLabel1 // this.linkLabel1.AutoSize = true; this.linkLabel1.Location = new System.Drawing.Point(146, 20); this.linkLabel1.Name = "linkLabel1"; this.linkLabel1.Size = new System.Drawing.Size(69, 13); this.linkLabel1.TabIndex = 14; this.linkLabel1.TabStop = true; this.linkLabel1.Text = "What\'s This?"; // // showNormalsCheckBox // this.showNormalsCheckBox.AutoSize = true; this.showNormalsCheckBox.Location = new System.Drawing.Point(6, 19); this.showNormalsCheckBox.Name = "showNormalsCheckBox"; this.showNormalsCheckBox.Size = new System.Drawing.Size(94, 17); this.showNormalsCheckBox.TabIndex = 12; this.showNormalsCheckBox.Text = "Show Normals"; this.showNormalsCheckBox.UseVisualStyleBackColor = true; this.showNormalsCheckBox.CheckedChanged += new System.EventHandler(this.showNormalsCheckBox_CheckedChanged); // // normalsAxisSizeLabel // this.normalsAxisSizeLabel.AutoSize = true; this.normalsAxisSizeLabel.Location = new System.Drawing.Point(3, 51); this.normalsAxisSizeLabel.Name = "normalsAxisSizeLabel"; this.normalsAxisSizeLabel.Size = new System.Drawing.Size(90, 13); this.normalsAxisSizeLabel.TabIndex = 13; this.normalsAxisSizeLabel.Text = "Normals Axis Size"; // // normalsAxisSizeTrackBar // this.normalsAxisSizeTrackBar.BackColor = System.Drawing.SystemColors.Control; this.normalsAxisSizeTrackBar.Location = new System.Drawing.Point(6, 67); this.normalsAxisSizeTrackBar.Maximum = 20; this.normalsAxisSizeTrackBar.Name = "normalsAxisSizeTrackBar"; this.normalsAxisSizeTrackBar.Size = new System.Drawing.Size(211, 45); this.normalsAxisSizeTrackBar.TabIndex = 10; this.normalsAxisSizeTrackBar.TickStyle = System.Windows.Forms.TickStyle.None; this.normalsAxisSizeTrackBar.Scroll += new System.EventHandler(this.normalsAxisSizeTrackBar_Scroll); // // lightingPage // this.lightingPage.Controls.Add(this.lightingFlowLayoutPanel); this.lightingPage.Location = new System.Drawing.Point(4, 40); this.lightingPage.Name = "lightingPage"; this.lightingPage.Size = new System.Drawing.Size(237, 606); this.lightingPage.TabIndex = 2; this.lightingPage.Text = "Lighting"; this.lightingPage.UseVisualStyleBackColor = true; // // lightingFlowLayoutPanel // this.lightingFlowLayoutPanel.Controls.Add(this.ambientLightButton); this.lightingFlowLayoutPanel.Controls.Add(this.ambientLightGroupBox); this.lightingFlowLayoutPanel.Controls.Add(this.directionalLightButton); this.lightingFlowLayoutPanel.Controls.Add(this.directionalLightGroupBox); this.lightingFlowLayoutPanel.Location = new System.Drawing.Point(3, 3); this.lightingFlowLayoutPanel.Name = "lightingFlowLayoutPanel"; this.lightingFlowLayoutPanel.Size = new System.Drawing.Size(231, 469); this.lightingFlowLayoutPanel.TabIndex = 2; // // ambientLightButton // this.ambientLightButton.Image = ((System.Drawing.Image)(resources.GetObject("ambientLightButton.Image"))); this.ambientLightButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.ambientLightButton.Location = new System.Drawing.Point(3, 3); this.ambientLightButton.Name = "ambientLightButton"; this.ambientLightButton.Size = new System.Drawing.Size(228, 29); this.ambientLightButton.TabIndex = 1; this.ambientLightButton.Text = "Ambient Light"; this.ambientLightButton.UseVisualStyleBackColor = true; this.ambientLightButton.Click += new System.EventHandler(this.ambientLightButton_Click); // // ambientLightGroupBox // this.ambientLightGroupBox.Controls.Add(this.ambientLightLinkLabel); this.ambientLightGroupBox.Controls.Add(this.ambientLightColorLabel); this.ambientLightGroupBox.Controls.Add(this.ambientLightColorButton); this.ambientLightGroupBox.Location = new System.Drawing.Point(3, 38); this.ambientLightGroupBox.Name = "ambientLightGroupBox"; this.ambientLightGroupBox.Size = new System.Drawing.Size(228, 86); this.ambientLightGroupBox.TabIndex = 2; this.ambientLightGroupBox.TabStop = false; // // ambientLightLinkLabel // this.ambientLightLinkLabel.AutoSize = true; this.ambientLightLinkLabel.Location = new System.Drawing.Point(133, 60); this.ambientLightLinkLabel.Name = "ambientLightLinkLabel"; this.ambientLightLinkLabel.Size = new System.Drawing.Size(69, 13); this.ambientLightLinkLabel.TabIndex = 2; this.ambientLightLinkLabel.TabStop = true; this.ambientLightLinkLabel.Text = "What\'s This?"; this.ambientLightLinkLabel.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.ambientLightLinkLabel_LinkClicked); // // ambientLightColorLabel // this.ambientLightColorLabel.AutoSize = true; this.ambientLightColorLabel.Location = new System.Drawing.Point(24, 26); this.ambientLightColorLabel.Name = "ambientLightColorLabel"; this.ambientLightColorLabel.Size = new System.Drawing.Size(101, 13); this.ambientLightColorLabel.TabIndex = 1; this.ambientLightColorLabel.Text = "Ambient Light Color:"; // // ambientLightColorButton // this.ambientLightColorButton.Location = new System.Drawing.Point(158, 19); this.ambientLightColorButton.Name = "ambientLightColorButton"; this.ambientLightColorButton.Size = new System.Drawing.Size(44, 26); this.ambientLightColorButton.TabIndex = 0; this.ambientLightColorButton.UseVisualStyleBackColor = true; this.ambientLightColorButton.Click += new System.EventHandler(this.ambientLightColorButton_Click); // // directionalLightButton // this.directionalLightButton.Image = ((System.Drawing.Image)(resources.GetObject("directionalLightButton.Image"))); this.directionalLightButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.directionalLightButton.Location = new System.Drawing.Point(3, 130); this.directionalLightButton.Name = "directionalLightButton"; this.directionalLightButton.Size = new System.Drawing.Size(228, 29); this.directionalLightButton.TabIndex = 3; this.directionalLightButton.Text = "Directional Light"; this.directionalLightButton.UseVisualStyleBackColor = true; this.directionalLightButton.Click += new System.EventHandler(this.directionalLightButton_Click); // // directionalLightGroupBox // this.directionalLightGroupBox.Controls.Add(this.directionalLightLinkLabel); this.directionalLightGroupBox.Controls.Add(this.label1); this.directionalLightGroupBox.Controls.Add(this.lightZenithTrackBar); this.directionalLightGroupBox.Controls.Add(this.lightAzimuthTrackBar); this.directionalLightGroupBox.Controls.Add(this.specularColorButton); this.directionalLightGroupBox.Controls.Add(this.diffuseColorButton); this.directionalLightGroupBox.Controls.Add(this.specularColorLabel); this.directionalLightGroupBox.Controls.Add(this.diffuseColorLabel); this.directionalLightGroupBox.Location = new System.Drawing.Point(3, 165); this.directionalLightGroupBox.Name = "directionalLightGroupBox"; this.directionalLightGroupBox.Size = new System.Drawing.Size(228, 287); this.directionalLightGroupBox.TabIndex = 4; this.directionalLightGroupBox.TabStop = false; // // directionalLightLinkLabel // this.directionalLightLinkLabel.AutoSize = true; this.directionalLightLinkLabel.Location = new System.Drawing.Point(133, 253); this.directionalLightLinkLabel.Name = "directionalLightLinkLabel"; this.directionalLightLinkLabel.Size = new System.Drawing.Size(69, 13); this.directionalLightLinkLabel.TabIndex = 7; this.directionalLightLinkLabel.TabStop = true; this.directionalLightLinkLabel.Text = "What\'s This?"; this.directionalLightLinkLabel.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.directionalLightLinkLabel_LinkClicked); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(24, 109); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(78, 13); this.label1.TabIndex = 6; this.label1.Text = "Light Direction:"; // // lightZenithTrackBar // this.lightZenithTrackBar.Location = new System.Drawing.Point(162, 163); this.lightZenithTrackBar.Maximum = 90; this.lightZenithTrackBar.Minimum = -90; this.lightZenithTrackBar.Name = "lightZenithTrackBar"; this.lightZenithTrackBar.Orientation = System.Windows.Forms.Orientation.Vertical; this.lightZenithTrackBar.Size = new System.Drawing.Size(45, 87); this.lightZenithTrackBar.TabIndex = 5; this.lightZenithTrackBar.TickStyle = System.Windows.Forms.TickStyle.None; this.lightZenithTrackBar.Scroll += new System.EventHandler(this.lightZenithTrackBar_Scroll); // // lightAzimuthTrackBar // this.lightAzimuthTrackBar.Location = new System.Drawing.Point(27, 134); this.lightAzimuthTrackBar.Maximum = 180; this.lightAzimuthTrackBar.Minimum = -180; this.lightAzimuthTrackBar.Name = "lightAzimuthTrackBar"; this.lightAzimuthTrackBar.Size = new System.Drawing.Size(129, 45); this.lightAzimuthTrackBar.TabIndex = 4; this.lightAzimuthTrackBar.TickStyle = System.Windows.Forms.TickStyle.None; this.lightAzimuthTrackBar.Scroll += new System.EventHandler(this.lightAzimuthTrackBar_Scroll); // // specularColorButton // this.specularColorButton.Location = new System.Drawing.Point(158, 61); this.specularColorButton.Name = "specularColorButton"; this.specularColorButton.Size = new System.Drawing.Size(44, 26); this.specularColorButton.TabIndex = 3; this.specularColorButton.UseVisualStyleBackColor = true; this.specularColorButton.Click += new System.EventHandler(this.specularColorButton_Click); // // diffuseColorButton // this.diffuseColorButton.Location = new System.Drawing.Point(158, 19); this.diffuseColorButton.Name = "diffuseColorButton"; this.diffuseColorButton.Size = new System.Drawing.Size(44, 26); this.diffuseColorButton.TabIndex = 2; this.diffuseColorButton.UseVisualStyleBackColor = true; this.diffuseColorButton.Click += new System.EventHandler(this.diffuseColorButton_Click); // // specularColorLabel // this.specularColorLabel.AutoSize = true; this.specularColorLabel.Location = new System.Drawing.Point(24, 68); this.specularColorLabel.Name = "specularColorLabel"; this.specularColorLabel.Size = new System.Drawing.Size(76, 13); this.specularColorLabel.TabIndex = 1; this.specularColorLabel.Text = "Specular Color"; // // diffuseColorLabel // this.diffuseColorLabel.AutoSize = true; this.diffuseColorLabel.Location = new System.Drawing.Point(24, 26); this.diffuseColorLabel.Name = "diffuseColorLabel"; this.diffuseColorLabel.Size = new System.Drawing.Size(70, 13); this.diffuseColorLabel.TabIndex = 0; this.diffuseColorLabel.Text = "Diffuse Color:"; // // socketsPage // this.socketsPage.Controls.Add(this.showSocketGroupBox); this.socketsPage.Controls.Add(this.socketsLinkLabel); this.socketsPage.Controls.Add(this.parentBoneValueLabel); this.socketsPage.Controls.Add(this.parentBoneLabel); this.socketsPage.Controls.Add(this.socketListBox); this.socketsPage.Location = new System.Drawing.Point(4, 40); this.socketsPage.Name = "socketsPage"; this.socketsPage.Padding = new System.Windows.Forms.Padding(3); this.socketsPage.Size = new System.Drawing.Size(237, 606); this.socketsPage.TabIndex = 4; this.socketsPage.Text = "Sockets"; this.socketsPage.UseVisualStyleBackColor = true; // // showSocketGroupBox // this.showSocketGroupBox.Controls.Add(this.socketAxisSizeTrackBar); this.showSocketGroupBox.Controls.Add(this.socketAxisSizeLabel); this.showSocketGroupBox.Controls.Add(this.showSocketsCheckBox); this.showSocketGroupBox.Location = new System.Drawing.Point(6, 340); this.showSocketGroupBox.Name = "showSocketGroupBox"; this.showSocketGroupBox.Size = new System.Drawing.Size(225, 118); this.showSocketGroupBox.TabIndex = 12; this.showSocketGroupBox.TabStop = false; // // socketAxisSizeTrackBar // this.socketAxisSizeTrackBar.Location = new System.Drawing.Point(6, 67); this.socketAxisSizeTrackBar.Maximum = 20; this.socketAxisSizeTrackBar.Name = "socketAxisSizeTrackBar"; this.socketAxisSizeTrackBar.Size = new System.Drawing.Size(211, 45); this.socketAxisSizeTrackBar.TabIndex = 11; this.socketAxisSizeTrackBar.TickStyle = System.Windows.Forms.TickStyle.None; this.socketAxisSizeTrackBar.Scroll += new System.EventHandler(this.socketAxisSizeTrackBar_Scroll); // // socketAxisSizeLabel // this.socketAxisSizeLabel.AutoSize = true; this.socketAxisSizeLabel.Location = new System.Drawing.Point(3, 51); this.socketAxisSizeLabel.Name = "socketAxisSizeLabel"; this.socketAxisSizeLabel.Size = new System.Drawing.Size(86, 13); this.socketAxisSizeLabel.TabIndex = 10; this.socketAxisSizeLabel.Text = "Socket Axis Size"; // // showSocketsCheckBox // this.showSocketsCheckBox.AutoSize = true; this.showSocketsCheckBox.Location = new System.Drawing.Point(6, 19); this.showSocketsCheckBox.Name = "showSocketsCheckBox"; this.showSocketsCheckBox.Size = new System.Drawing.Size(95, 17); this.showSocketsCheckBox.TabIndex = 9; this.showSocketsCheckBox.Text = "Show Sockets"; this.showSocketsCheckBox.UseVisualStyleBackColor = true; this.showSocketsCheckBox.CheckedChanged += new System.EventHandler(this.showSocketsCheckBox_CheckedChanged); // // socketsLinkLabel // this.socketsLinkLabel.AutoSize = true; this.socketsLinkLabel.Location = new System.Drawing.Point(154, 578); this.socketsLinkLabel.Name = "socketsLinkLabel"; this.socketsLinkLabel.Size = new System.Drawing.Size(69, 13); this.socketsLinkLabel.TabIndex = 8; this.socketsLinkLabel.TabStop = true; this.socketsLinkLabel.Text = "What\'s This?"; this.socketsLinkLabel.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.socketsLinkLabel_LinkClicked); // // parentBoneValueLabel // this.parentBoneValueLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.parentBoneValueLabel.AutoSize = true; this.parentBoneValueLabel.Location = new System.Drawing.Point(81, 481); this.parentBoneValueLabel.Name = "parentBoneValueLabel"; this.parentBoneValueLabel.Size = new System.Drawing.Size(33, 13); this.parentBoneValueLabel.TabIndex = 6; this.parentBoneValueLabel.Text = "None"; // // parentBoneLabel // this.parentBoneLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.parentBoneLabel.AutoSize = true; this.parentBoneLabel.Location = new System.Drawing.Point(6, 481); this.parentBoneLabel.Name = "parentBoneLabel"; this.parentBoneLabel.Size = new System.Drawing.Size(69, 13); this.parentBoneLabel.TabIndex = 5; this.parentBoneLabel.Text = "Parent Bone:"; // // socketListBox // this.socketListBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.socketListBox.FormattingEnabled = true; this.socketListBox.Location = new System.Drawing.Point(0, 0); this.socketListBox.Name = "socketListBox"; this.socketListBox.Size = new System.Drawing.Size(237, 334); this.socketListBox.TabIndex = 0; // // animPage // this.animPage.Controls.Add(this.timeCurrentLabel); this.animPage.Controls.Add(this.timeEndLabel); this.animPage.Controls.Add(this.timeStartLabel); this.animPage.Controls.Add(this.animationTrackBar); this.animPage.Controls.Add(this.animLinkLabel); this.animPage.Controls.Add(this.animationSpeedTextBox); this.animPage.Controls.Add(this.animationSpeedLabel); this.animPage.Controls.Add(this.loopingCheckBox); this.animPage.Controls.Add(this.playStopButton); this.animPage.Controls.Add(this.animationListBox); this.animPage.Location = new System.Drawing.Point(4, 40); this.animPage.Name = "animPage"; this.animPage.Padding = new System.Windows.Forms.Padding(3); this.animPage.Size = new System.Drawing.Size(237, 606); this.animPage.TabIndex = 1; this.animPage.Text = "Animations"; this.animPage.UseVisualStyleBackColor = true; // // timeCurrentLabel // this.timeCurrentLabel.AutoSize = true; this.timeCurrentLabel.Location = new System.Drawing.Point(100, 471); this.timeCurrentLabel.Name = "timeCurrentLabel"; this.timeCurrentLabel.Size = new System.Drawing.Size(22, 13); this.timeCurrentLabel.TabIndex = 10; this.timeCurrentLabel.Text = "0.5"; // // timeEndLabel // this.timeEndLabel.AutoSize = true; this.timeEndLabel.Location = new System.Drawing.Point(186, 471); this.timeEndLabel.Name = "timeEndLabel"; this.timeEndLabel.Size = new System.Drawing.Size(22, 13); this.timeEndLabel.TabIndex = 9; this.timeEndLabel.Text = "1.0"; // // timeStartLabel // this.timeStartLabel.AutoSize = true; this.timeStartLabel.Location = new System.Drawing.Point(15, 471); this.timeStartLabel.Name = "timeStartLabel"; this.timeStartLabel.Size = new System.Drawing.Size(22, 13); this.timeStartLabel.TabIndex = 8; this.timeStartLabel.Text = "0.0"; // // animationTrackBar // this.animationTrackBar.Location = new System.Drawing.Point(18, 488); this.animationTrackBar.Name = "animationTrackBar"; this.animationTrackBar.Size = new System.Drawing.Size(203, 45); this.animationTrackBar.TabIndex = 7; // // animLinkLabel // this.animLinkLabel.AutoSize = true; this.animLinkLabel.Location = new System.Drawing.Point(152, 544); this.animLinkLabel.Name = "animLinkLabel"; this.animLinkLabel.Size = new System.Drawing.Size(69, 13); this.animLinkLabel.TabIndex = 6; this.animLinkLabel.TabStop = true; this.animLinkLabel.Text = "What\'s This?"; this.animLinkLabel.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.animLinkLabel_LinkClicked); // // animationSpeedTextBox // this.animationSpeedTextBox.Location = new System.Drawing.Point(121, 393); this.animationSpeedTextBox.Name = "animationSpeedTextBox"; this.animationSpeedTextBox.Size = new System.Drawing.Size(100, 20); this.animationSpeedTextBox.TabIndex = 4; this.animationSpeedTextBox.Text = "1.0"; // // animationSpeedLabel // this.animationSpeedLabel.AutoSize = true; this.animationSpeedLabel.Location = new System.Drawing.Point(15, 396); this.animationSpeedLabel.Name = "animationSpeedLabel"; this.animationSpeedLabel.Size = new System.Drawing.Size(90, 13); this.animationSpeedLabel.TabIndex = 3; this.animationSpeedLabel.Text = "Animation Speed:"; // // loopingCheckBox // this.loopingCheckBox.AutoSize = true; this.loopingCheckBox.Location = new System.Drawing.Point(18, 364); this.loopingCheckBox.Name = "loopingCheckBox"; this.loopingCheckBox.Size = new System.Drawing.Size(99, 17); this.loopingCheckBox.TabIndex = 2; this.loopingCheckBox.Text = "Loop Animation"; this.loopingCheckBox.UseVisualStyleBackColor = true; // // playStopButton // this.playStopButton.Location = new System.Drawing.Point(18, 431); this.playStopButton.Name = "playStopButton"; this.playStopButton.Size = new System.Drawing.Size(75, 23); this.playStopButton.TabIndex = 1; this.playStopButton.Text = "Play"; this.playStopButton.UseVisualStyleBackColor = true; this.playStopButton.Click += new System.EventHandler(this.playPauseButton_Click); // // animationListBox // this.animationListBox.FormattingEnabled = true; this.animationListBox.ImeMode = System.Windows.Forms.ImeMode.NoControl; this.animationListBox.Location = new System.Drawing.Point(0, 0); this.animationListBox.Name = "animationListBox"; this.animationListBox.Size = new System.Drawing.Size(237, 329); this.animationListBox.TabIndex = 0; this.animationListBox.SelectedIndexChanged += new System.EventHandler(this.animationListBox_SelectedIndexChanged); // // subMeshPage // this.subMeshPage.Controls.Add(this.subMeshTreeView); this.subMeshPage.Controls.Add(this.subMeshLinkLabel); this.subMeshPage.Controls.Add(this.materialLabel); this.subMeshPage.Controls.Add(this.materialTextBox); this.subMeshPage.Controls.Add(this.hideButton); this.subMeshPage.Controls.Add(this.showButton); this.subMeshPage.Controls.Add(this.subMeshTextBox); this.subMeshPage.Controls.Add(this.hideShowLabel); this.subMeshPage.Controls.Add(this.hideAllButton); this.subMeshPage.Controls.Add(this.showAllButton); this.subMeshPage.Location = new System.Drawing.Point(4, 40); this.subMeshPage.Name = "subMeshPage"; this.subMeshPage.Padding = new System.Windows.Forms.Padding(3); this.subMeshPage.Size = new System.Drawing.Size(237, 606); this.subMeshPage.TabIndex = 0; this.subMeshPage.Text = "Sub Meshes"; this.subMeshPage.UseVisualStyleBackColor = true; // // subMeshTreeView // this.subMeshTreeView.CheckBoxes = true; this.subMeshTreeView.Location = new System.Drawing.Point(0, 0); this.subMeshTreeView.Name = "subMeshTreeView"; this.subMeshTreeView.Size = new System.Drawing.Size(237, 329); this.subMeshTreeView.TabIndex = 10; this.subMeshTreeView.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.subMeshTreeView_AfterSelect); // // subMeshLinkLabel // this.subMeshLinkLabel.AutoSize = true; this.subMeshLinkLabel.Location = new System.Drawing.Point(145, 566); this.subMeshLinkLabel.Name = "subMeshLinkLabel"; this.subMeshLinkLabel.Size = new System.Drawing.Size(69, 13); this.subMeshLinkLabel.TabIndex = 9; this.subMeshLinkLabel.TabStop = true; this.subMeshLinkLabel.Text = "What\'s This?"; this.subMeshLinkLabel.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.subMeshLinkLabel_LinkClicked); // // materialLabel // this.materialLabel.AutoSize = true; this.materialLabel.Location = new System.Drawing.Point(21, 504); this.materialLabel.Name = "materialLabel"; this.materialLabel.Size = new System.Drawing.Size(44, 13); this.materialLabel.TabIndex = 8; this.materialLabel.Text = "Material"; // // materialTextBox // this.materialTextBox.Location = new System.Drawing.Point(24, 530); this.materialTextBox.Name = "materialTextBox"; this.materialTextBox.Size = new System.Drawing.Size(188, 20); this.materialTextBox.TabIndex = 7; this.materialTextBox.TextChanged += new System.EventHandler(this.materialTextBox_TextChanged); // // hideButton // this.hideButton.Enabled = false; this.hideButton.Location = new System.Drawing.Point(134, 464); this.hideButton.Name = "hideButton"; this.hideButton.Size = new System.Drawing.Size(80, 30); this.hideButton.TabIndex = 6; this.hideButton.Text = "Hide"; this.hideButton.UseVisualStyleBackColor = true; this.hideButton.Click += new System.EventHandler(this.hideButton_Click); // // showButton // this.showButton.Enabled = false; this.showButton.Location = new System.Drawing.Point(25, 462); this.showButton.Name = "showButton"; this.showButton.Size = new System.Drawing.Size(80, 30); this.showButton.TabIndex = 5; this.showButton.Text = "Show"; this.showButton.UseVisualStyleBackColor = true; this.showButton.Click += new System.EventHandler(this.showButton_Click); // // subMeshTextBox // this.subMeshTextBox.Location = new System.Drawing.Point(24, 424); this.subMeshTextBox.Name = "subMeshTextBox"; this.subMeshTextBox.Size = new System.Drawing.Size(188, 20); this.subMeshTextBox.TabIndex = 4; this.subMeshTextBox.TextChanged += new System.EventHandler(this.subMeshTextBox_TextChanged); // // hideShowLabel // this.hideShowLabel.AutoSize = true; this.hideShowLabel.Location = new System.Drawing.Point(23, 392); this.hideShowLabel.Name = "hideShowLabel"; this.hideShowLabel.Size = new System.Drawing.Size(179, 13); this.hideShowLabel.TabIndex = 3; this.hideShowLabel.Text = "Hide/Show Sub Meshes Containing:"; // // hideAllButton // this.hideAllButton.Location = new System.Drawing.Point(132, 347); this.hideAllButton.Name = "hideAllButton"; this.hideAllButton.Size = new System.Drawing.Size(80, 30); this.hideAllButton.TabIndex = 2; this.hideAllButton.Text = "Hide All"; this.hideAllButton.UseVisualStyleBackColor = true; this.hideAllButton.Click += new System.EventHandler(this.hideAllButton_Click); // // showAllButton // this.showAllButton.Location = new System.Drawing.Point(24, 347); this.showAllButton.Name = "showAllButton"; this.showAllButton.Size = new System.Drawing.Size(80, 30); this.showAllButton.TabIndex = 1; this.showAllButton.Text = "Show All"; this.showAllButton.UseVisualStyleBackColor = true; this.showAllButton.Click += new System.EventHandler(this.showAllButton_Click); // // tabControl1 // this.tabControl1.Controls.Add(this.subMeshPage); this.tabControl1.Controls.Add(this.animPage); this.tabControl1.Controls.Add(this.bonesPage); this.tabControl1.Controls.Add(this.socketsPage); this.tabControl1.Controls.Add(this.lightingPage); this.tabControl1.Controls.Add(this.cameraPage); this.tabControl1.Location = new System.Drawing.Point(0, 66); this.tabControl1.Multiline = true; this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(245, 650); this.tabControl1.TabIndex = 4; // // ModelViewer // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1016, 741); this.Controls.Add(this.tabControl1); this.Controls.Add(this.toolStrip1); this.Controls.Add(this.statusStrip1); this.Controls.Add(this.menuStrip1); this.Controls.Add(this.axiomPictureBox); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MainMenuStrip = this.menuStrip1; this.Name = "ModelViewer"; this.Text = "ModelViewer"; this.Resize += new System.EventHandler(this.ModelViewer_Resize); this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.ModelViewer_FormClosing); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.axiomPictureBox)).EndInit(); this.bonesPage.ResumeLayout(false); this.bonesPage.PerformLayout(); this.showBonesGroupBox.ResumeLayout(false); this.showBonesGroupBox.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.boneAxisSizeTrackBar)).EndInit(); this.cameraPage.ResumeLayout(false); this.flowLayoutPanel1.ResumeLayout(false); this.cameraFocusHeightGroupBox.ResumeLayout(false); this.cameraFocusHeightGroupBox.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.cameraFocusHeightTrackbar)).EndInit(); this.cameraNearDistanceGroupBox.ResumeLayout(false); this.cameraNearDistanceGroupBox.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.cameraNearDistanceTrackBar)).EndInit(); this.showNormalsGroupBox.ResumeLayout(false); this.showNormalsGroupBox.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.normalsAxisSizeTrackBar)).EndInit(); this.lightingPage.ResumeLayout(false); this.lightingFlowLayoutPanel.ResumeLayout(false); this.ambientLightGroupBox.ResumeLayout(false); this.ambientLightGroupBox.PerformLayout(); this.directionalLightGroupBox.ResumeLayout(false); this.directionalLightGroupBox.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.lightZenithTrackBar)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.lightAzimuthTrackBar)).EndInit(); this.socketsPage.ResumeLayout(false); this.socketsPage.PerformLayout(); this.showSocketGroupBox.ResumeLayout(false); this.showSocketGroupBox.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.socketAxisSizeTrackBar)).EndInit(); this.animPage.ResumeLayout(false); this.animPage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.animationTrackBar)).EndInit(); this.subMeshPage.ResumeLayout(false); this.subMeshPage.PerformLayout(); this.tabControl1.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem viewToolStripMenuItem1; private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.PictureBox axiomPictureBox; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem wireFrameToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem displayTerrainToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem spinCameraToolStripMenuItem; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton spinCameraToolStripButton; private System.Windows.Forms.ToolStripMenuItem loadModelToolStripMenuItem; private System.Windows.Forms.ToolStripSplitButton mouseModeToolStripButton; private System.Windows.Forms.ToolStripMenuItem moveCameraToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem moveDirectionalLightToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem spinLightToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem showBoundingBoxToolStripMenuItem; private System.Windows.Forms.ColorDialog colorDialog1; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem helpToolStripHelpItem; private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem; private System.Windows.Forms.ToolStripStatusLabel fpsStatusValueLabel; private System.Windows.Forms.ToolStripMenuItem submitABugReportToolStripMenuItem; private System.Windows.Forms.ToolStripStatusLabel fpsStatusLabel; private System.Windows.Forms.ToolStripStatusLabel modelHeightLabel; private System.Windows.Forms.ToolStripStatusLabel modelHeightValueLabel; private System.Windows.Forms.ToolStripMenuItem designateRepositoryMenuItem; private System.Windows.Forms.ToolStripMenuItem launchReleaseNotesToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem showCollisionVolumesToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem displayBoneInformationToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem setMaximumFramesPerSecondToolStripMenuItem; private System.Windows.Forms.TabPage bonesPage; private System.Windows.Forms.LinkLabel bonesLinkLabel; private System.Windows.Forms.TreeView bonesTreeView; private System.Windows.Forms.TabPage cameraPage; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private System.Windows.Forms.Button cameraControlsButton; private System.Windows.Forms.GroupBox cameraFocusHeightGroupBox; private System.Windows.Forms.LinkLabel cameraControlsLinkLabel; private System.Windows.Forms.TrackBar cameraFocusHeightTrackbar; private System.Windows.Forms.Label label2; private System.Windows.Forms.GroupBox cameraNearDistanceGroupBox; private System.Windows.Forms.Label nearDistanceValueLabel; private System.Windows.Forms.LinkLabel whatsNearDistanceLabel; private System.Windows.Forms.TrackBar cameraNearDistanceTrackBar; private System.Windows.Forms.Label label3; private System.Windows.Forms.TabPage lightingPage; private System.Windows.Forms.FlowLayoutPanel lightingFlowLayoutPanel; private System.Windows.Forms.Button ambientLightButton; private System.Windows.Forms.GroupBox ambientLightGroupBox; private System.Windows.Forms.LinkLabel ambientLightLinkLabel; private System.Windows.Forms.Label ambientLightColorLabel; private System.Windows.Forms.Button ambientLightColorButton; private System.Windows.Forms.Button directionalLightButton; private System.Windows.Forms.GroupBox directionalLightGroupBox; private System.Windows.Forms.LinkLabel directionalLightLinkLabel; private System.Windows.Forms.Label label1; private System.Windows.Forms.TrackBar lightZenithTrackBar; private System.Windows.Forms.TrackBar lightAzimuthTrackBar; private System.Windows.Forms.Button specularColorButton; private System.Windows.Forms.Button diffuseColorButton; private System.Windows.Forms.Label specularColorLabel; private System.Windows.Forms.Label diffuseColorLabel; private System.Windows.Forms.TabPage socketsPage; private System.Windows.Forms.LinkLabel socketsLinkLabel; private System.Windows.Forms.Label parentBoneValueLabel; private System.Windows.Forms.Label parentBoneLabel; private System.Windows.Forms.CheckedListBox socketListBox; private System.Windows.Forms.TabPage animPage; private System.Windows.Forms.Label timeCurrentLabel; private System.Windows.Forms.Label timeEndLabel; private System.Windows.Forms.Label timeStartLabel; private System.Windows.Forms.TrackBar animationTrackBar; private System.Windows.Forms.LinkLabel animLinkLabel; private System.Windows.Forms.TextBox animationSpeedTextBox; private System.Windows.Forms.Label animationSpeedLabel; private System.Windows.Forms.CheckBox loopingCheckBox; private System.Windows.Forms.Button playStopButton; private System.Windows.Forms.ListBox animationListBox; private System.Windows.Forms.TabPage subMeshPage; private System.Windows.Forms.TreeView subMeshTreeView; private System.Windows.Forms.LinkLabel subMeshLinkLabel; private System.Windows.Forms.Label materialLabel; private System.Windows.Forms.TextBox materialTextBox; private System.Windows.Forms.Button hideButton; private System.Windows.Forms.Button showButton; private System.Windows.Forms.TextBox subMeshTextBox; private System.Windows.Forms.Label hideShowLabel; private System.Windows.Forms.Button hideAllButton; private System.Windows.Forms.Button showAllButton; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.ToolStripMenuItem bgColorToolStripMenuItem; private System.Windows.Forms.CheckBox showBonesCheckBox; private System.Windows.Forms.CheckBox showSocketsCheckBox; private System.Windows.Forms.Label boneAxisSizeLabel; private System.Windows.Forms.TrackBar boneAxisSizeTrackBar; private System.Windows.Forms.TrackBar socketAxisSizeTrackBar; private System.Windows.Forms.Label socketAxisSizeLabel; private System.Windows.Forms.GroupBox showSocketGroupBox; private System.Windows.Forms.GroupBox showBonesGroupBox; private System.Windows.Forms.ToolStripMenuItem showGroundPlaneToolStripMenuItem; private System.Windows.Forms.TrackBar normalsAxisSizeTrackBar; private System.Windows.Forms.ToolStripMenuItem materialSchemeToolStripMenuItem; private System.Windows.Forms.CheckBox showNormalsCheckBox; private System.Windows.Forms.Label normalsAxisSizeLabel; private System.Windows.Forms.GroupBox showNormalsGroupBox; private System.Windows.Forms.LinkLabel linkLabel1; } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Commons.Music.Midi { public class MidiMusic { #region static members public static MidiMusic Read (Stream stream) { var r = new SmfReader (); r.Read (stream); return r.Music; } #endregion List<MidiTrack> tracks = new List<MidiTrack> (); public MidiMusic () { Format = 1; } public short DeltaTimeSpec { get; set; } public byte Format { get; set; } public void AddTrack (MidiTrack track) { this.tracks.Add (track); } public IList<MidiTrack> Tracks { get { return tracks; } } public IEnumerable<MidiMessage> GetMetaEventsOfType (byte metaType) { if (Format != 0) return SmfTrackMerger.Merge (this).GetMetaEventsOfType (metaType); return GetMetaEventsOfType (tracks [0].Messages, metaType); } public static IEnumerable<MidiMessage> GetMetaEventsOfType (IEnumerable<MidiMessage> messages, byte metaType) { int v = 0; foreach (var m in messages) { v += m.DeltaTime; if (m.Event.EventType == MidiEvent.Meta && m.Event.Msb == metaType) yield return new MidiMessage (v, m.Event); } } public int GetTotalTicks () { if (Format != 0) return SmfTrackMerger.Merge (this).GetTotalTicks (); return Tracks [0].Messages.Sum (m => m.DeltaTime); } public int GetTotalPlayTimeMilliseconds () { if (Format != 0) return SmfTrackMerger.Merge (this).GetTotalPlayTimeMilliseconds (); return GetTotalPlayTimeMilliseconds (Tracks [0].Messages, DeltaTimeSpec); } public int GetTimePositionInMillisecondsForTick (int ticks) { if (Format != 0) return SmfTrackMerger.Merge (this).GetTimePositionInMillisecondsForTick (ticks); return GetPlayTimeMillisecondsAtTick (Tracks [0].Messages, ticks, DeltaTimeSpec); } public static int GetTotalPlayTimeMilliseconds (IList<MidiMessage> messages, int deltaTimeSpec) { return GetPlayTimeMillisecondsAtTick (messages, messages.Sum (m => m.DeltaTime), deltaTimeSpec); } public static int GetPlayTimeMillisecondsAtTick (IList<MidiMessage> messages, int ticks, int deltaTimeSpec) { if (deltaTimeSpec < 0) throw new NotSupportedException ("non-tick based DeltaTime"); else { int tempo = MidiMetaType.DefaultTempo; int t = 0; double v = 0; foreach (var m in messages) { var deltaTime = t + m.DeltaTime < ticks ? m.DeltaTime : ticks - t; v += (double) tempo / 1000 * deltaTime / deltaTimeSpec; if (deltaTime != m.DeltaTime) break; t += m.DeltaTime; if (m.Event.EventType == MidiEvent.Meta && m.Event.Msb == MidiMetaType.Tempo) tempo = MidiMetaType.GetTempo (m.Event.ExtraData, m.Event.ExtraDataOffset); } return (int) v; } } } public class MidiTrack { public MidiTrack () : this (new List<MidiMessage> ()) { } public MidiTrack (IList<MidiMessage> messages) { if (messages == null) throw new ArgumentNullException ("messages"); this.messages = messages as List<MidiMessage> ?? new List<MidiMessage> (messages); } List<MidiMessage> messages; [Obsolete ("No need to use this method, simply use Messages.Add")] public void AddMessage (MidiMessage msg) { messages.Add (msg); } public IList<MidiMessage> Messages { get { return messages; } } } public struct MidiMessage { public MidiMessage (int deltaTime, MidiEvent evt) { DeltaTime = deltaTime; Event = evt; } public readonly int DeltaTime; public readonly MidiEvent Event; public override string ToString () { return String.Format ("[dt{0}]{1}", DeltaTime, Event); } } public static class MidiCC { public const byte BankSelect = 0x00; public const byte Modulation = 0x01; public const byte Breath = 0x02; public const byte Foot = 0x04; public const byte PortamentoTime = 0x05; public const byte DteMsb = 0x06; public const byte Volume = 0x07; public const byte Balance = 0x08; public const byte Pan = 0x0A; public const byte Expression = 0x0B; public const byte EffectControl1 = 0x0C; public const byte EffectControl2 = 0x0D; public const byte General1 = 0x10; public const byte General2 = 0x11; public const byte General3 = 0x12; public const byte General4 = 0x13; public const byte BankSelectLsb = 0x20; public const byte ModulationLsb = 0x21; public const byte BreathLsb = 0x22; public const byte FootLsb = 0x24; public const byte PortamentoTimeLsb = 0x25; public const byte DteLsb = 0x26; public const byte VolumeLsb = 0x27; public const byte BalanceLsb = 0x28; public const byte PanLsb = 0x2A; public const byte ExpressionLsb = 0x2B; public const byte Effect1Lsb = 0x2C; public const byte Effect2Lsb = 0x2D; public const byte General1Lsb = 0x30; public const byte General2Lsb = 0x31; public const byte General3Lsb = 0x32; public const byte General4Lsb = 0x33; public const byte Hold = 0x40; public const byte PortamentoSwitch = 0x41; public const byte Sostenuto = 0x42; public const byte SoftPedal = 0x43; public const byte Legato = 0x44; public const byte Hold2 = 0x45; public const byte SoundController1 = 0x46; public const byte SoundController2 = 0x47; public const byte SoundController3 = 0x48; public const byte SoundController4 = 0x49; public const byte SoundController5 = 0x4A; public const byte SoundController6 = 0x4B; public const byte SoundController7 = 0x4C; public const byte SoundController8 = 0x4D; public const byte SoundController9 = 0x4E; public const byte SoundController10 = 0x4F; public const byte General5 = 0x50; public const byte General6 = 0x51; public const byte General7 = 0x52; public const byte General8 = 0x53; public const byte PortamentoControl = 0x54; public const byte Rsd = 0x5B; public const byte Effect1 = 0x5B; public const byte Tremolo = 0x5C; public const byte Effect2 = 0x5C; public const byte Csd = 0x5D; public const byte Effect3 = 0x5D; public const byte Celeste = 0x5E; public const byte Effect4 = 0x5E; public const byte Phaser = 0x5F; public const byte Effect5 = 0x5F; public const byte DteIncrement = 0x60; public const byte DteDecrement = 0x61; public const byte NrpnLsb = 0x62; public const byte NrpnMsb = 0x63; public const byte RpnLsb = 0x64; public const byte RpnMsb = 0x65; // Channel mode messages public const byte AllSoundOff = 0x78; public const byte ResetAllControllers = 0x79; public const byte LocalControl = 0x7A; public const byte AllNotesOff = 0x7B; public const byte OmniModeOff = 0x7C; public const byte OmniModeOn = 0x7D; public const byte PolyModeOnOff = 0x7E; public const byte PolyModeOn = 0x7F; } public static class MidiRpnType { public const short PitchBendSensitivity = 0; public const short FineTuning = 1; public const short CoarseTuning = 2; public const short TuningProgram = 3; public const short TuningBankSelect = 4; public const short ModulationDepth = 5; } public static class MidiMetaType { public const byte SequenceNumber = 0x00; public const byte Text = 0x01; public const byte Copyright = 0x02; public const byte TrackName = 0x03; public const byte InstrumentName = 0x04; public const byte Lyric = 0x05; public const byte Marker = 0x06; public const byte Cue = 0x07; public const byte ChannelPrefix = 0x20; public const byte EndOfTrack = 0x2F; public const byte Tempo = 0x51; public const byte SmpteOffset = 0x54; public const byte TimeSignature = 0x58; public const byte KeySignature = 0x59; public const byte SequencerSpecific = 0x7F; public const int DefaultTempo = 500000; [Obsolete ("Use another GetTempo overload with offset and length arguments instead.")] public static int GetTempo (byte [] data) => GetTempo (data, 0); public static int GetTempo (byte [] data, int offset) { if (data == null) throw new ArgumentNullException (nameof (data)); if (offset < 0 || offset + 2 >= data.Length) throw new ArgumentException ($"offset + 2 must be a valid size under data length of array size {data.Length}; {offset} is not."); return (data [offset] << 16) + (data [offset + 1] << 8) + data [offset + 2]; } [Obsolete ("Use another GetBpm() overload with offset argument instead")] public static double GetBpm (byte [] data) => GetBpm (data, 0); public static double GetBpm (byte [] data, int offset) { return 60000000.0 / GetTempo (data, offset); } } public struct MidiEvent { public const byte NoteOff = 0x80; public const byte NoteOn = 0x90; public const byte PAf = 0xA0; public const byte CC = 0xB0; public const byte Program = 0xC0; public const byte CAf = 0xD0; public const byte Pitch = 0xE0; public const byte SysEx1 = 0xF0; public const byte MtcQuarterFrame = 0xF1; public const byte SongPositionPointer = 0xF2; public const byte SongSelect = 0xF3; public const byte TuneRequest = 0xF6; public const byte SysEx2 = 0xF7; public const byte MidiClock = 0xF8; public const byte MidiTick = 0xF9; public const byte MidiStart = 0xFA; public const byte MidiContinue = 0xFB; public const byte MidiStop = 0xFC; public const byte ActiveSense = 0xFE; public const byte Reset = 0xFF; public const byte EndSysEx = 0xF7; public const byte Meta = 0xFF; public static IEnumerable<MidiEvent> Convert (byte[] bytes, int index, int size) { int i = index; int end = index + size; while (i < end) { if (bytes [i] == 0xF0) { yield return new MidiEvent (0xF0, 0, 0, bytes, index, size); i += size; } else { var z = MidiEvent.FixedDataSize (bytes [i]); if (end < i + z) throw new Exception (string.Format ( "Received data was incomplete to build MIDI status message for '{0:X}' status.", bytes [i])); yield return new MidiEvent (bytes [i], (byte) (z > 0 ? bytes [i + 1] : 0), (byte) (z > 1 ? bytes [i + 2] : 0), null, 0, 0); i += z + 1; } } } public MidiEvent (int value) { Value = value; #pragma warning disable 618 Data = null; #pragma warning restore ExtraData = null; ExtraDataOffset = 0; ExtraDataLength = 0; } [Obsolete ("Use another constructor overload with Span<byte> instead")] public MidiEvent (byte type, byte arg1, byte arg2, byte [] data) : this (type, arg1, arg2, data, 0, data != null ? data.Length : 0) { } public MidiEvent (byte type, byte arg1, byte arg2, byte [] extraData, int extraDataOffset, int extraDataLength) { Value = type + (arg1 << 8) + (arg2 << 16); #pragma warning disable 618 Data = extraData; #pragma warning restore ExtraData = extraData; ExtraDataOffset = extraDataOffset; ExtraDataLength = extraDataLength; } public readonly int Value; // This expects EndSysEx byte _inclusive_ for F0 message. [Obsolete ("Use ExtraData with ExtraDataOffset and ExtraDataLength instead.")] public readonly byte [] Data; public readonly byte [] ExtraData; public readonly int ExtraDataOffset; public readonly int ExtraDataLength; public byte StatusByte { get { return (byte) (Value & 0xFF); } } public byte EventType { get { switch (StatusByte) { case Meta: case SysEx1: case SysEx2: return StatusByte; default: return (byte) (Value & 0xF0); } } } public byte Msb { get { return (byte) ((Value & 0xFF00) >> 8); } } public byte Lsb { get { return (byte) ((Value & 0xFF0000) >> 16); } } public byte MetaType { get { return Msb; } } public byte Channel { get { return (byte) (Value & 0x0F); } } public static byte FixedDataSize (byte statusByte) { switch (statusByte & 0xF0) { case 0xF0: // and 0xF7, 0xFF switch (statusByte) { case MtcQuarterFrame: case SongSelect: return 1; case SongPositionPointer: return 2; default: return 0; // no fixed data } case Program: case CAf: return 1; default: return 2; } } public override string ToString () { return String.Format ("{0:X02}:{1:X02}:{2:X02}{3}", StatusByte, Msb, Lsb, ExtraData != null ? "[data:" + ExtraDataLength + "]" : ""); } } public class SmfWriter { Stream stream; public SmfWriter (Stream stream) { if (stream == null) throw new ArgumentNullException ("stream"); this.stream = stream; // default meta event writer. meta_event_writer = SmfWriterExtension.DefaultMetaEventWriter; } public bool DisableRunningStatus { get; set; } void WriteShort (short v) { stream.WriteByte ((byte) (v / 0x100)); stream.WriteByte ((byte) (v % 0x100)); } void WriteInt (int v) { stream.WriteByte ((byte) (v / 0x1000000)); stream.WriteByte ((byte) (v / 0x10000 & 0xFF)); stream.WriteByte ((byte) (v / 0x100 & 0xFF)); stream.WriteByte ((byte) (v % 0x100)); } public void WriteMusic (MidiMusic music) { WriteHeader (music.Format, (short) music.Tracks.Count, music.DeltaTimeSpec); foreach (var track in music.Tracks) WriteTrack (track); } public void WriteHeader (short format, short tracks, short deltaTimeSpec) { stream.Write (Encoding.UTF8.GetBytes ("MThd"), 0, 4); WriteShort (0); WriteShort (6); WriteShort (format); WriteShort (tracks); WriteShort (deltaTimeSpec); } Func<bool,MidiMessage,Stream,int> meta_event_writer; public Func<bool,MidiMessage,Stream,int> MetaEventWriter { get { return meta_event_writer; } set { if (value == null) throw new ArgumentNullException ("value"); meta_event_writer = value; } } public void WriteTrack (MidiTrack track) { stream.Write (Encoding.UTF8.GetBytes ("MTrk"), 0, 4); WriteInt (GetTrackDataSize (track)); byte running_status = 0; foreach (MidiMessage e in track.Messages) { Write7BitVariableInteger (e.DeltaTime); switch (e.Event.EventType) { case MidiEvent.Meta: meta_event_writer (false, e, stream); break; case MidiEvent.SysEx1: case MidiEvent.SysEx2: stream.WriteByte (e.Event.EventType); Write7BitVariableInteger (e.Event.ExtraDataLength); stream.Write (e.Event.ExtraData, e.Event.ExtraDataOffset, e.Event.ExtraDataLength); break; default: if (DisableRunningStatus || e.Event.StatusByte != running_status) stream.WriteByte (e.Event.StatusByte); int len = MidiEvent.FixedDataSize (e.Event.EventType); stream.WriteByte (e.Event.Msb); if (len > 1) stream.WriteByte (e.Event.Lsb); if (len > 2) throw new Exception ("Unexpected data size: " + len); break; } running_status = e.Event.StatusByte; } } int GetVariantLength (int value) { if (value < 0) throw new ArgumentOutOfRangeException (String.Format ("Length must be non-negative integer: {0}", value)); if (value == 0) return 1; int ret = 0; for (int x = value; x != 0; x >>= 7) ret++; return ret; } int GetTrackDataSize (MidiTrack track) { int size = 0; byte running_status = 0; foreach (MidiMessage e in track.Messages) { // delta time size += GetVariantLength (e.DeltaTime); // arguments switch (e.Event.EventType) { case MidiEvent.Meta: size += meta_event_writer (true, e, null); break; case MidiEvent.SysEx1: case MidiEvent.SysEx2: size++; size += GetVariantLength (e.Event.ExtraDataLength); size += e.Event.ExtraDataLength; break; default: // message type & channel if (DisableRunningStatus || running_status != e.Event.StatusByte) size++; size += MidiEvent.FixedDataSize (e.Event.EventType); break; } running_status = e.Event.StatusByte; } return size; } void Write7BitVariableInteger (int value) { Write7BitVariableInteger (value, false); } void Write7BitVariableInteger (int value, bool shifted) { if (value == 0) { stream.WriteByte ((byte) (shifted ? 0x80 : 0)); return; } if (value >= 0x80) Write7BitVariableInteger (value >> 7, true); stream.WriteByte ((byte) ((value & 0x7F) + (shifted ? 0x80 : 0))); } } public static class SmfWriterExtension { static readonly Func<bool, MidiMessage, Stream, int> default_meta_writer, vsq_meta_text_splitter; static SmfWriterExtension () { default_meta_writer = delegate (bool lengthMode, MidiMessage e, Stream stream) { if (lengthMode) { // [0x00] 0xFF metaType size ... (note that for more than one meta event it requires step count of 0). int repeatCount = e.Event.ExtraDataLength / 0x7F; if (repeatCount == 0) return 3 + e.Event.ExtraDataLength; int mod = e.Event.ExtraDataLength % 0x7F; return repeatCount * (4 + 0x7F) - 1 + (mod > 0 ? 4 + mod : 0); } int written = 0; int total = e.Event.ExtraDataLength; do { if (written > 0) stream.WriteByte (0); // step stream.WriteByte (0xFF); stream.WriteByte (e.Event.MetaType); int size = Math.Min (0x7F, total - written); stream.WriteByte ((byte) size); stream.Write (e.Event.ExtraData, e.Event.ExtraDataOffset + written, size); written += size; } while (written < total); return 0; }; vsq_meta_text_splitter = delegate (bool lengthMode, MidiMessage e, Stream stream) { // The split should not be applied to "Master Track" if (e.Event.ExtraDataLength < 0x80) { return default_meta_writer (lengthMode, e, stream); } if (lengthMode) { // { [0x00] 0xFF metaType DM:xxxx:... } * repeat + 0x00 0xFF metaType DM:xxxx:mod... // (note that for more than one meta event it requires step count of 0). int repeatCount = e.Event.ExtraDataLength / 0x77; if (repeatCount == 0) return 11 + e.Event.ExtraDataLength; int mod = e.Event.ExtraDataLength % 0x77; return repeatCount * (12 + 0x77) - 1 + (mod > 0 ? 12 + mod : 0); } int written = 0; int total = e.Event.ExtraDataLength; int idx = 0; do { if (written > 0) stream.WriteByte (0); // step stream.WriteByte (0xFF); stream.WriteByte (e.Event.MetaType); int size = Math.Min (0x77, total - written); stream.WriteByte ((byte) (size + 8)); stream.Write (Encoding.UTF8.GetBytes (String.Format ("DM:{0:D04}:", idx++)), 0, 8); stream.Write (e.Event.ExtraData, e.Event.ExtraDataOffset + written, size); written += size; } while (written < total); return 0; }; } public static Func<bool, MidiMessage, Stream, int> DefaultMetaEventWriter { get { return default_meta_writer; } } public static Func<bool, MidiMessage, Stream, int> VsqMetaTextSplitter { get { return vsq_meta_text_splitter; } } } public class SmfReader { Stream stream; MidiMusic data; public MidiMusic Music { get { return data; } } public void Read (Stream stream) { if (stream == null) throw new ArgumentNullException (nameof (stream)); this.stream = stream; data = new MidiMusic (); try { DoParse (); } finally { this.stream = null; } } void DoParse () { if ( ReadByte () != 'M' || ReadByte () != 'T' || ReadByte () != 'h' || ReadByte () != 'd') throw ParseError ("MThd is expected"); if (ReadInt32 () != 6) throw ParseError ("Unexpected data size (should be 6)"); data.Format = (byte) ReadInt16 (); int tracks = ReadInt16 (); data.DeltaTimeSpec = ReadInt16 (); try { for (int i = 0; i < tracks; i++) data.Tracks.Add (ReadTrack ()); } catch (FormatException ex) { throw ParseError ("Unexpected data error", ex); } } MidiTrack ReadTrack () { var tr = new MidiTrack (); if ( ReadByte () != 'M' || ReadByte () != 'T' || ReadByte () != 'r' || ReadByte () != 'k') throw ParseError ("MTrk is expected"); int trackSize = ReadInt32 (); current_track_size = 0; int total = 0; while (current_track_size < trackSize) { int delta = ReadVariableLength (); tr.Messages.Add (ReadMessage (delta)); total += delta; } if (current_track_size != trackSize) throw ParseError ("Size information mismatch"); return tr; } int current_track_size; byte running_status; MidiMessage ReadMessage (int deltaTime) { byte b = PeekByte (); running_status = b < 0x80 ? running_status : ReadByte (); int len; switch (running_status) { case MidiEvent.SysEx1: case MidiEvent.SysEx2: case MidiEvent.Meta: byte metaType = running_status == MidiEvent.Meta ? ReadByte () : (byte) 0; len = ReadVariableLength (); byte [] args = new byte [len]; if (len > 0) ReadBytes (args); return new MidiMessage (deltaTime, new MidiEvent (running_status, metaType, 0, args, 0, args.Length)); default: int value = running_status; value += ReadByte () << 8; if (MidiEvent.FixedDataSize (running_status) == 2) value += ReadByte () << 16; return new MidiMessage (deltaTime, new MidiEvent (value)); } } void ReadBytes (byte [] args) { current_track_size += args.Length; int start = 0; if (peek_byte >= 0) { args [0] = (byte) peek_byte; peek_byte = -1; start = 1; } int len = stream.Read (args, start, args.Length - start); try { if (len < args.Length - start) throw ParseError (String.Format ("The stream is insufficient to read {0} bytes specified in the SMF message. Only {1} bytes read.", args.Length, len)); } finally { stream_position += len; } } int ReadVariableLength () { int val = 0; for (int i = 0; i < 4; i++) { byte b = ReadByte (); val = (val << 7) + b; if (b < 0x80) return val; val -= 0x80; } throw ParseError ("Delta time specification exceeds the 4-byte limitation."); } int peek_byte = -1; int stream_position; byte PeekByte () { if (peek_byte < 0) peek_byte = stream.ReadByte (); if (peek_byte < 0) throw ParseError ("Insufficient stream. Failed to read a byte."); return (byte) peek_byte; } byte ReadByte () { try { current_track_size++; if (peek_byte >= 0) { byte b = (byte) peek_byte; peek_byte = -1; return b; } int ret = stream.ReadByte (); if (ret < 0) throw ParseError ("Insufficient stream. Failed to read a byte."); return (byte) ret; } finally { stream_position++; } } short ReadInt16 () { return (short) ((ReadByte () << 8) + ReadByte ()); } int ReadInt32 () { return (((ReadByte () << 8) + ReadByte () << 8) + ReadByte () << 8) + ReadByte (); } Exception ParseError (string msg) { return ParseError (msg, null); } Exception ParseError (string msg, Exception innerException) { throw new SmfParserException (String.Format (msg + "(at {0})", stream_position), innerException); } } public class SmfParserException : Exception { public SmfParserException () : this ("SMF parser error") {} public SmfParserException (string message) : base (message) {} public SmfParserException (string message, Exception innerException) : base (message, innerException) {} } public class SmfTrackMerger { public static MidiMusic Merge (MidiMusic source) { return new SmfTrackMerger (source).GetMergedMessages (); } SmfTrackMerger (MidiMusic source) { this.source = source; } MidiMusic source; // FIXME: it should rather be implemented to iterate all // tracks with index to messages, pick the track which contains // the nearest event and push the events into the merged queue. // It's simpler, and costs less by removing sort operation // over thousands of events. MidiMusic GetMergedMessages () { if (source.Format == 0) return source; IList<MidiMessage> l = new List<MidiMessage> (); foreach (var track in source.Tracks) { int delta = 0; foreach (var mev in track.Messages) { delta += mev.DeltaTime; l.Add (new MidiMessage (delta, mev.Event)); } } if (l.Count == 0) return new MidiMusic () { DeltaTimeSpec = source.DeltaTimeSpec }; // empty (why did you need to sort your song file?) // Usual Sort() over simple list of MIDI events does not work as expected. // For example, it does not always preserve event // orders on the same channels when the delta time // of event B after event A is 0. It could be sorted // either as A->B or B->A. // // To resolve this issue, we have to sort "chunk" // of events, not all single events themselves, so // that order of events in the same chunk is preserved // i.e. [AB] at 48 and [CDE] at 0 should be sorted as // [CDE] [AB]. var idxl = new List<int> (l.Count); idxl.Add (0); int prev = 0; for (int i = 0; i < l.Count; i++) { if (l [i].DeltaTime != prev) { idxl.Add (i); prev = l [i].DeltaTime; } } idxl.Sort (delegate (int i1, int i2) { return l [i1].DeltaTime - l [i2].DeltaTime; }); // now build a new event list based on the sorted blocks. var l2 = new List<MidiMessage> (l.Count); int idx; for (int i = 0; i < idxl.Count; i++) for (idx = idxl [i], prev = l [idx].DeltaTime; idx < l.Count && l [idx].DeltaTime == prev; idx++) l2.Add (l [idx]); l = l2; // now messages should be sorted correctly. var waitToNext = l [0].DeltaTime; for (int i = 0; i < l.Count - 1; i++) { if (l [i].Event.Value != 0) { // if non-dummy var tmp = l [i + 1].DeltaTime - l [i].DeltaTime; l [i] = new MidiMessage (waitToNext, l [i].Event); waitToNext = tmp; } } l [l.Count - 1] = new MidiMessage (waitToNext, l [l.Count - 1].Event); var m = new MidiMusic (); m.DeltaTimeSpec = source.DeltaTimeSpec; m.Format = 0; m.Tracks.Add (new MidiTrack (l)); return m; } } public class SmfTrackSplitter { public static MidiMusic Split (IList<MidiMessage> source, short deltaTimeSpec) { return new SmfTrackSplitter (source, deltaTimeSpec).Split (); } SmfTrackSplitter (IList<MidiMessage> source, short deltaTimeSpec) { if (source == null) throw new ArgumentNullException ("source"); this.source = source; delta_time_spec = deltaTimeSpec; var mtr = new SplitTrack (-1); tracks.Add (-1, mtr); } IList<MidiMessage> source; short delta_time_spec; Dictionary<int,SplitTrack> tracks = new Dictionary<int,SplitTrack> (); class SplitTrack { public SplitTrack (int trackID) { TrackID = trackID; Track = new MidiTrack (); } public int TrackID; public int TotalDeltaTime; public MidiTrack Track; public void AddMessage (int deltaInsertAt, MidiMessage e) { e = new MidiMessage (deltaInsertAt - TotalDeltaTime, e.Event); Track.Messages.Add (e); TotalDeltaTime = deltaInsertAt; } } SplitTrack GetTrack (int track) { SplitTrack t; if (!tracks.TryGetValue (track, out t)) { t = new SplitTrack (track); tracks [track] = t; } return t; } // Override it to customize track dispatcher. It would be // useful to split note messages out from non-note ones, // to ease data reading. public virtual int GetTrackID (MidiMessage e) { switch (e.Event.EventType) { case MidiEvent.Meta: case MidiEvent.SysEx1: case MidiEvent.SysEx2: return -1; default: return e.Event.Channel; } } public MidiMusic Split () { int totalDeltaTime = 0; foreach (var e in source) { totalDeltaTime += e.DeltaTime; int id = GetTrackID (e); GetTrack (id).AddMessage (totalDeltaTime, e); } var m = new MidiMusic (); m.DeltaTimeSpec = delta_time_spec; foreach (var t in tracks.Values) m.Tracks.Add (t.Track); return m; } } }
// // CGContextPDF.cs: Implements the managed CGContextPDF // // Authors: Mono Team // // Copyright 2009-2010 Novell, Inc // Copyright 2011, 2012 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Drawing; using System.Runtime.InteropServices; using MonoMac.ObjCRuntime; using MonoMac.Foundation; using MonoMac.CoreFoundation; namespace MonoMac.CoreGraphics { public class CGPDFPageInfo { static IntPtr kCGPDFContextMediaBox; static IntPtr kCGPDFContextCropBox; static IntPtr kCGPDFContextBleedBox; static IntPtr kCGPDFContextTrimBox; static IntPtr kCGPDFContextArtBox; static CGPDFPageInfo () { IntPtr h = Dlfcn.dlopen (Constants.CoreGraphicsLibrary, 0); try { kCGPDFContextMediaBox = Dlfcn.GetIndirect (h, "kCGPDFContextMediaBox"); kCGPDFContextCropBox = Dlfcn.GetIndirect (h, "kCGPDFContextCropBox"); kCGPDFContextBleedBox = Dlfcn.GetIndirect (h, "kCGPDFContextBleedBox"); kCGPDFContextTrimBox = Dlfcn.GetIndirect (h, "kCGPDFContextTrimBox"); kCGPDFContextArtBox = Dlfcn.GetIndirect (h, "kCGPDFContextArtBox"); } finally { Dlfcn.dlclose (h); } } public RectangleF? MediaBox { get; set; } public RectangleF? CropBox { get; set; } public RectangleF? BleedBox { get; set; } public RectangleF? TrimBox { get; set; } public RectangleF? ArtBox { get; set; } static void Add (NSMutableDictionary dict, IntPtr key, RectangleF? val) { if (!val.HasValue) return; NSData data; unsafe { RectangleF f = val.Value; RectangleF *pf = &f; data = NSData.FromBytes ((IntPtr) pf, 16); } dict.LowlevelSetObject (data, key); } internal virtual NSMutableDictionary ToDictionary () { var ret = new NSMutableDictionary (); Add (ret, kCGPDFContextMediaBox, MediaBox); Add (ret, kCGPDFContextCropBox, CropBox); Add (ret, kCGPDFContextBleedBox, BleedBox); Add (ret, kCGPDFContextTrimBox, TrimBox); Add (ret, kCGPDFContextArtBox, ArtBox); return ret; } } public class CGPDFInfo : CGPDFPageInfo { static IntPtr kCGPDFContextTitle; static IntPtr kCGPDFContextAuthor; static IntPtr kCGPDFContextSubject; static IntPtr kCGPDFContextKeywords; static IntPtr kCGPDFContextCreator; static IntPtr kCGPDFContextOwnerPassword; static IntPtr kCGPDFContextUserPassword; static IntPtr kCGPDFContextEncryptionKeyLength; static IntPtr kCGPDFContextAllowsPrinting; static IntPtr kCGPDFContextAllowsCopying; #if false static IntPtr kCGPDFContextOutputIntent; static IntPtr kCGPDFXOutputIntentSubtype; static IntPtr kCGPDFXOutputConditionIdentifier; static IntPtr kCGPDFXOutputCondition; static IntPtr kCGPDFXRegistryName; static IntPtr kCGPDFXInfo; static IntPtr kCGPDFXDestinationOutputProfile; static IntPtr kCGPDFContextOutputIntents; #endif static CGPDFInfo () { IntPtr h = Dlfcn.dlopen (Constants.CoreGraphicsLibrary, 0); try { kCGPDFContextTitle = Dlfcn.GetIndirect (h, "kCGPDFContextTitle"); kCGPDFContextAuthor = Dlfcn.GetIndirect (h, "kCGPDFContextAuthor"); kCGPDFContextSubject = Dlfcn.GetIndirect (h, "kCGPDFContextSubject"); kCGPDFContextKeywords = Dlfcn.GetIndirect (h, "kCGPDFContextKeywords"); kCGPDFContextCreator = Dlfcn.GetIndirect (h, "kCGPDFContextCreator"); kCGPDFContextOwnerPassword = Dlfcn.GetIndirect (h, "kCGPDFContextOwnerPassword"); kCGPDFContextUserPassword = Dlfcn.GetIndirect (h, "kCGPDFContextUserPassword"); kCGPDFContextEncryptionKeyLength = Dlfcn.GetIndirect (h, "kCGPDFContextEncryptionKeyLength"); kCGPDFContextAllowsPrinting = Dlfcn.GetIndirect (h, "kCGPDFContextAllowsPrinting"); kCGPDFContextAllowsCopying = Dlfcn.GetIndirect (h, "kCGPDFContextAllowsCopying"); #if false kCGPDFContextOutputIntent = Dlfcn.GetIndirect (h, "kCGPDFContextOutputIntent"); kCGPDFXOutputIntentSubtype = Dlfcn.GetIndirect (h, "kCGPDFXOutputIntentSubtype"); kCGPDFXOutputConditionIdentifier = Dlfcn.GetIndirect (h, "kCGPDFXOutputConditionIdentifier"); kCGPDFXOutputCondition = Dlfcn.GetIndirect (h, "kCGPDFXOutputCondition"); kCGPDFXRegistryName = Dlfcn.GetIndirect (h, "kCGPDFXRegistryName"); kCGPDFXInfo = Dlfcn.GetIndirect (h, "kCGPDFXInfo"); kCGPDFXDestinationOutputProfile = Dlfcn.GetIndirect (h, "kCGPDFXDestinationOutputProfile"); kCGPDFContextOutputIntents = Dlfcn.GetIndirect (h, "kCGPDFContextOutputIntents"); #endif } finally { Dlfcn.dlclose (h); } } public string Title { get; set; } public string Author { get; set; } public string Subject { get; set; } public string [] Keywords { get; set; } public string Creator { get; set; } public string OwnerPassword { get; set; } public string UserPassword { get; set; } public int? EncryptionKeyLength { get; set; } public bool? AllowsPrinting { get; set; } public bool? AllowsCopying { get; set; } //public NSDictionary OutputIntent { get; set; } internal override NSMutableDictionary ToDictionary () { var ret = base.ToDictionary (); if (Title != null) ret.LowlevelSetObject ((NSString) Title, kCGPDFContextTitle); if (Author != null) ret.LowlevelSetObject ((NSString) Author, kCGPDFContextAuthor); if (Subject != null) ret.LowlevelSetObject ((NSString) Subject, kCGPDFContextSubject); if (Keywords != null && Keywords.Length > 0){ if (Keywords.Length == 1) ret.LowlevelSetObject ((NSString) Keywords [0], kCGPDFContextKeywords); else ret.LowlevelSetObject (NSArray.FromStrings (Keywords), kCGPDFContextKeywords); } if (Creator != null) ret.LowlevelSetObject ((NSString) Creator, kCGPDFContextCreator); if (OwnerPassword != null) ret.LowlevelSetObject ((NSString) OwnerPassword, kCGPDFContextOwnerPassword); if (UserPassword != null) ret.LowlevelSetObject ((NSString) UserPassword, kCGPDFContextUserPassword); if (EncryptionKeyLength.HasValue) ret.LowlevelSetObject (NSNumber.FromInt32 (EncryptionKeyLength.Value), kCGPDFContextEncryptionKeyLength); if (AllowsPrinting.HasValue && AllowsPrinting.Value == false) ret.LowlevelSetObject (CFBoolean.False.Handle, kCGPDFContextAllowsPrinting); if (AllowsCopying.HasValue && AllowsCopying.Value == false) ret.LowlevelSetObject (CFBoolean.False.Handle, kCGPDFContextAllowsCopying); return ret; } } public class CGContextPDF : CGContext { bool closed; [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGPDFContextCreateWithURL (IntPtr url, ref RectangleF rect, IntPtr dictionary); [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGPDFContextCreateWithURL (IntPtr url, IntPtr rect, IntPtr dictionary); public CGContextPDF (NSUrl url, RectangleF mediaBox, CGPDFInfo info) { if (url == null) throw new ArgumentNullException ("url"); handle = CGPDFContextCreateWithURL (url.Handle, ref mediaBox, info == null ? IntPtr.Zero : info.ToDictionary ().Handle); } public CGContextPDF (NSUrl url, RectangleF mediaBox) { if (url == null) throw new ArgumentNullException ("url"); handle = CGPDFContextCreateWithURL (url.Handle, ref mediaBox, IntPtr.Zero); } public CGContextPDF (NSUrl url, CGPDFInfo info) { if (url == null) throw new ArgumentNullException ("url"); handle = CGPDFContextCreateWithURL (url.Handle, IntPtr.Zero, info == null ? IntPtr.Zero : info.ToDictionary ().Handle); } public CGContextPDF (NSUrl url) { if (url == null) throw new ArgumentNullException ("url"); handle = CGPDFContextCreateWithURL (url.Handle, IntPtr.Zero, IntPtr.Zero); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGPDFContextClose(IntPtr handle); public void Close () { if (closed) return; CGPDFContextClose (handle); closed = true; } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGPDFContextBeginPage (IntPtr handle, IntPtr dict); public void BeginPage (CGPDFPageInfo info) { CGPDFContextBeginPage (handle, info == null ? IntPtr.Zero : info.ToDictionary ().Handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGPDFContextEndPage (IntPtr handle); public void EndPage () { CGPDFContextEndPage (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGPDFContextAddDocumentMetadata (IntPtr handle, IntPtr nsDataHandle); public void AddDocumentMetadata (NSData data) { if (data == null) return; CGPDFContextAddDocumentMetadata (handle, data.Handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGPDFContextSetURLForRect (IntPtr handle, IntPtr urlh, RectangleF rect); public void SetUrl (NSUrl url, RectangleF region) { if (url == null) throw new ArgumentNullException ("url"); CGPDFContextSetURLForRect (handle, url.Handle, region); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGPDFContextAddDestinationAtPoint (IntPtr handle, IntPtr cfstring, PointF point); public void AddDestination (string name, PointF point) { if (name == null) throw new ArgumentNullException ("name"); CGPDFContextAddDestinationAtPoint (handle, new NSString (name).Handle, point); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGPDFContextSetDestinationForRect (IntPtr handle, IntPtr cfstr, RectangleF rect); public void SetDestination (string name, RectangleF rect) { if (name == null) throw new ArgumentNullException ("name"); CGPDFContextSetDestinationForRect (handle, new NSString (name).Handle, rect); } protected override void Dispose (bool disposing) { if (disposing) Close (); base.Dispose (disposing); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using MigAz.Azure.Interface; using MigAz.Azure.Core.Interface; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MigAz.Azure.Arm; using MigAz.Azure.Core; using MigAz.Azure.Core.ArmTemplate; namespace MigAz.Azure.MigrationTarget { public class VirtualMachine : Core.MigrationTarget { private AvailabilitySet _TargetAvailabilitySet = null; private Arm.VMSize _TargetSize; private List<NetworkInterface> _NetworkInterfaces = new List<NetworkInterface>(); private List<Disk> _DataDisks = new List<Disk>(); private Dictionary<string, string> _PlanAttributes; #region Constructors private VirtualMachine() : base(ArmConst.MicrosoftCompute, ArmConst.VirtualMachines) { } public VirtualMachine(Asm.VirtualMachine virtualMachine, TargetSettings targetSettings) : base(ArmConst.MicrosoftCompute, ArmConst.VirtualMachines) { this.Source = virtualMachine; this.SetTargetName(virtualMachine.RoleName, targetSettings); this.OSVirtualHardDisk = new Disk(virtualMachine.OSVirtualHardDisk, this, targetSettings); this.OSVirtualHardDiskOS = virtualMachine.OSVirtualHardDiskOS; if (targetSettings.DefaultTargetDiskType == ArmDiskType.ClassicDisk) this.OSVirtualHardDisk.TargetStorage = SeekTargetStorageAccount(virtualMachine.AzureSubscription.AsmTargetStorageAccounts, virtualMachine.OSVirtualHardDisk.StorageAccountName); foreach (Asm.Disk asmDataDisk in virtualMachine.DataDisks) { Disk targetDataDisk = new Disk(asmDataDisk, this, targetSettings); EnsureDataDiskTargetLunIsNotNull(ref targetDataDisk); if (targetSettings.DefaultTargetDiskType == ArmDiskType.ClassicDisk) targetDataDisk.TargetStorage = SeekTargetStorageAccount(virtualMachine.AzureSubscription.AsmTargetStorageAccounts, asmDataDisk.StorageAccountName); this.DataDisks.Add(targetDataDisk); } foreach (Asm.NetworkInterface asmNetworkInterface in virtualMachine.NetworkInterfaces) { NetworkInterface migrationNetworkInterface = new NetworkInterface(virtualMachine, asmNetworkInterface, virtualMachine.AzureSubscription.AsmTargetVirtualNetworks, virtualMachine.AzureSubscription.AsmTargetNetworkSecurityGroups, targetSettings); migrationNetworkInterface.ParentVirtualMachine = this; this.NetworkInterfaces.Add(migrationNetworkInterface); } #region Seek ARM Target Size // Get ARM Based Location (that matches location of Source ASM VM Arm.Location armLocation = virtualMachine.AzureSubscription.GetAzureARMLocation(virtualMachine.Location); if (armLocation != null) { this.TargetSize = armLocation.SeekVmSize(virtualMachine.RoleSize.Name); if (this.TargetSize == null) { // if not found, defer to alternate matching options Dictionary<string, string> VMSizeTable = new Dictionary<string, string>(); VMSizeTable.Add("ExtraSmall", "Standard_A0"); VMSizeTable.Add("Small", "Standard_A1"); VMSizeTable.Add("Medium", "Standard_A2"); VMSizeTable.Add("Large", "Standard_A3"); VMSizeTable.Add("ExtraLarge", "Standard_A4"); VMSizeTable.Add("A5", "Standard_A5"); VMSizeTable.Add("A6", "Standard_A6"); VMSizeTable.Add("A7", "Standard_A7"); VMSizeTable.Add("A8", "Standard_A8"); VMSizeTable.Add("A9", "Standard_A9"); VMSizeTable.Add("A10", "Standard_A10"); VMSizeTable.Add("A11", "Standard_A11"); if (VMSizeTable.ContainsKey(virtualMachine.RoleSize.Name)) { this.TargetSize = armLocation.SeekVmSize(VMSizeTable[virtualMachine.RoleSize.Name]); } } } #endregion } public VirtualMachine(Arm.VirtualMachine virtualMachine, TargetSettings targetSettings) : base(ArmConst.MicrosoftCompute, ArmConst.VirtualMachines) { this.Source = virtualMachine; this.SetTargetName(virtualMachine.Name, targetSettings); this.TargetSize = virtualMachine.VmSize; this.OSVirtualHardDiskOS = virtualMachine.OSVirtualHardDiskOS; if (virtualMachine.OSVirtualHardDisk != null && virtualMachine.OSVirtualHardDisk.GetType() == typeof(Azure.Arm.ManagedDisk)) { Azure.Arm.ManagedDisk sourceManagedDisk = (Azure.Arm.ManagedDisk)virtualMachine.OSVirtualHardDisk; foreach (Disk targetDisk in virtualMachine.AzureSubscription.ArmTargetManagedDisks) { if ((targetDisk.SourceDisk != null) && (targetDisk.SourceDisk.GetType() == typeof(Azure.Arm.ManagedDisk))) { Azure.Arm.ManagedDisk targetDiskSourceDisk = (Azure.Arm.ManagedDisk)targetDisk.SourceDisk; if (String.Compare(targetDiskSourceDisk.Name, sourceManagedDisk.Name, true) == 0) { this.OSVirtualHardDisk = targetDisk; targetDisk.ParentVirtualMachine = this; targetDisk.HostCaching = sourceManagedDisk.HostCaching; break; } } } } else { if (virtualMachine.OSVirtualHardDisk != null) { this.OSVirtualHardDisk = new Disk(virtualMachine.OSVirtualHardDisk, this, targetSettings); } } if (virtualMachine.OSVirtualHardDisk != null && virtualMachine.OSVirtualHardDisk.GetType() == typeof(Arm.ClassicDisk)) { Arm.ClassicDisk armDisk = (Arm.ClassicDisk)virtualMachine.OSVirtualHardDisk; if (targetSettings.DefaultTargetDiskType == ArmDiskType.ClassicDisk) this.OSVirtualHardDisk.TargetStorage = SeekTargetStorageAccount(virtualMachine.AzureSubscription.ArmTargetStorageAccounts, armDisk.StorageAccountName); } foreach (IArmDisk dataDisk in virtualMachine.DataDisks) { if (dataDisk.GetType() == typeof(Azure.Arm.ManagedDisk)) { Azure.Arm.ManagedDisk sourceManagedDisk = (Azure.Arm.ManagedDisk)dataDisk; MigrationTarget.Disk targetDataDisk = null; foreach (Disk targetDisk in virtualMachine.AzureSubscription.ArmTargetManagedDisks) { if ((targetDisk.SourceDisk != null) && (targetDisk.SourceDisk.GetType() == typeof(Azure.Arm.ManagedDisk))) { Azure.Arm.ManagedDisk targetDiskSourceDisk = (Azure.Arm.ManagedDisk)targetDisk.SourceDisk; if (String.Compare(targetDiskSourceDisk.Name, sourceManagedDisk.Name, true) == 0) { targetDataDisk = targetDisk; break; } } } if (targetDataDisk != null) { EnsureDataDiskTargetLunIsNotNull(ref targetDataDisk); targetDataDisk.ParentVirtualMachine = this; targetDataDisk.Lun = sourceManagedDisk.Lun; targetDataDisk.HostCaching = sourceManagedDisk.HostCaching; this.DataDisks.Add(targetDataDisk); } } else if(dataDisk.GetType() == typeof(Arm.ClassicDisk)) { Disk targetDataDisk = new Disk(dataDisk, this, targetSettings); Arm.ClassicDisk armDisk = (Arm.ClassicDisk)dataDisk; if (targetSettings.DefaultTargetDiskType == ArmDiskType.ClassicDisk) targetDataDisk.TargetStorage = SeekTargetStorageAccount(virtualMachine.AzureSubscription.ArmTargetStorageAccounts, armDisk.StorageAccountName); EnsureDataDiskTargetLunIsNotNull(ref targetDataDisk); this.DataDisks.Add(targetDataDisk); } } foreach (Arm.NetworkInterface armNetworkInterface in virtualMachine.NetworkInterfaces) { foreach (NetworkInterface targetNetworkInterface in virtualMachine.AzureSubscription.ArmTargetNetworkInterfaces) { if ((targetNetworkInterface.SourceNetworkInterface != null) && (targetNetworkInterface.SourceNetworkInterface.GetType() == typeof(Azure.Arm.NetworkInterface))) { Azure.Arm.NetworkInterface targetNetworkInterfaceSourceInterface = (Azure.Arm.NetworkInterface)targetNetworkInterface.SourceNetworkInterface; if (String.Compare(targetNetworkInterfaceSourceInterface.Name, armNetworkInterface.Name, true) == 0) { this.NetworkInterfaces.Add(targetNetworkInterface); targetNetworkInterface.ParentVirtualMachine = this; break; } } } } if (virtualMachine.HasPlan) { _PlanAttributes = new Dictionary<string, string>(); foreach (JProperty planAttribute in virtualMachine.ResourceToken["plan"]) { _PlanAttributes.Add(planAttribute.Name, planAttribute.Value.ToString()); } } } #endregion private void EnsureDataDiskTargetLunIsNotNull(ref Disk targetDataDisk) { if (!targetDataDisk.Lun.HasValue) { // Every Data Disk should have a Lun Index already assigned from the ASM XML. In the event it does not have a value, we are going to // change the LUN from Null to -1 to indicate the disks is a data disk, but the LUN could not be determined. Given that -1 is not an // allowed LUN Index, we'll use -1 in the tool to identify that this Disk is a Data Disk, is missing LUN index, require user to specify index. targetDataDisk.Lun = -1; } } private StorageAccount SeekTargetStorageAccount(List<StorageAccount> storageAccounts, string sourceAccountName) { foreach (StorageAccount targetStorageAccount in storageAccounts) { if (targetStorageAccount.SourceName == sourceAccountName) return targetStorageAccount; } return null; } public Disk OSVirtualHardDisk { get; set; } public List<Disk> DataDisks { get { return _DataDisks; } } public IVirtualMachine Source { get; set; } public List<NetworkInterface> NetworkInterfaces { get { return _NetworkInterfaces; } } public NetworkInterface PrimaryNetworkInterface { get { foreach (NetworkInterface networkInterface in this.NetworkInterfaces) { if (networkInterface.IsPrimary) return networkInterface; } return null; } } public Arm.VMSize TargetSize { get { return _TargetSize; } set { _TargetSize = value; } } public Dictionary<string, string> PlanAttributes { get { return _PlanAttributes; } set { _PlanAttributes = value; } } public string SourceName { get { if (this.Source == null) return String.Empty; else return this.Source.ToString(); } } public string OSVirtualHardDiskOS { get; set; } public AvailabilitySet TargetAvailabilitySet { get { return _TargetAvailabilitySet; } set { if (value != _TargetAvailabilitySet) { if (_TargetAvailabilitySet != null) { _TargetAvailabilitySet.TargetVirtualMachines.Remove(this); } _TargetAvailabilitySet = value; if (_TargetAvailabilitySet != null) { if (!_TargetAvailabilitySet.TargetVirtualMachines.Contains(this)) _TargetAvailabilitySet.TargetVirtualMachines.Add(this); } } } } public bool IsManagedDisks { get { if (this.OSVirtualHardDisk != null && !this.OSVirtualHardDisk.IsManagedDisk) return false; foreach (Azure.MigrationTarget.Disk dataDisk in this.DataDisks) { if (!dataDisk.IsManagedDisk) return false; } return true; } } public bool IsUnmanagedDisks { get { if (this.OSVirtualHardDisk != null && !this.OSVirtualHardDisk.IsUnmanagedDisk) return false; foreach (Azure.MigrationTarget.Disk dataDisk in this.DataDisks) { if (!dataDisk.IsUnmanagedDisk) return false; } return true; } } public override string ImageKey { get { return "VirtualMachine"; } } public override string FriendlyObjectName { get { return "Virtual Machine"; } } public override void SetTargetName(string targetName, TargetSettings targetSettings) { this.TargetName = targetName.Trim().Replace(" ", String.Empty); this.TargetNameResult = this.TargetName + targetSettings.VirtualMachineSuffix; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // <OWNER>[....]</OWNER> // // // PasswordDerivedBytes.cs // namespace System.Security.Cryptography { using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Globalization; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] public class PasswordDeriveBytes : DeriveBytes { private int _extraCount; private int _prefix; private int _iterations; private byte[] _baseValue; private byte[] _extra; private byte[] _salt; private string _hashName; private byte[] _password; private HashAlgorithm _hash; private CspParameters _cspParams; #if !MONO [System.Security.SecurityCritical] // auto-generated private SafeProvHandle _safeProvHandle = null; private SafeProvHandle ProvHandle { [System.Security.SecurityCritical] // auto-generated get { if (_safeProvHandle == null) { lock (this) { if (_safeProvHandle == null) { SafeProvHandle safeProvHandle = Utils.AcquireProvHandle(_cspParams); System.Threading.Thread.MemoryBarrier(); _safeProvHandle = safeProvHandle; } } } return _safeProvHandle; } } #endif // // public constructors // public PasswordDeriveBytes (String strPassword, byte[] rgbSalt) : this (strPassword, rgbSalt, new CspParameters()) {} public PasswordDeriveBytes (byte[] password, byte[] salt) : this (password, salt, new CspParameters()) {} public PasswordDeriveBytes (string strPassword, byte[] rgbSalt, string strHashName, int iterations) : this (strPassword, rgbSalt, strHashName, iterations, new CspParameters()) {} public PasswordDeriveBytes (byte[] password, byte[] salt, string hashName, int iterations) : this (password, salt, hashName, iterations, new CspParameters()) {} public PasswordDeriveBytes (string strPassword, byte[] rgbSalt, CspParameters cspParams) : this (strPassword, rgbSalt, "SHA1", 100, cspParams) {} public PasswordDeriveBytes (byte[] password, byte[] salt, CspParameters cspParams) : this (password, salt, "SHA1", 100, cspParams) {} public PasswordDeriveBytes (string strPassword, byte[] rgbSalt, String strHashName, int iterations, CspParameters cspParams) : this ((new UTF8Encoding(false)).GetBytes(strPassword), rgbSalt, strHashName, iterations, cspParams) {} // This method needs to be safe critical, because in debug builds the C# compiler will include null // initialization of the _safeProvHandle field in the method. Since SafeProvHandle is critical, a // transparent reference triggers an error using PasswordDeriveBytes. [SecuritySafeCritical] public PasswordDeriveBytes (byte[] password, byte[] salt, String hashName, int iterations, CspParameters cspParams) { this.IterationCount = iterations; this.Salt = salt; this.HashName = hashName; _password = password; _cspParams = cspParams; } // // public properties // public String HashName { get { return _hashName; } set { if (_baseValue != null) throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_ValuesFixed", "HashName")); _hashName = value; _hash = (HashAlgorithm) CryptoConfig.CreateFromName(_hashName); } } public int IterationCount { get { return _iterations; } set { if (value <= 0) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); Contract.EndContractBlock(); if (_baseValue != null) throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_ValuesFixed", "IterationCount")); _iterations = value; } } public byte[] Salt { get { if (_salt == null) return null; return (byte[]) _salt.Clone(); } set { if (_baseValue != null) throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_ValuesFixed", "Salt")); if (value == null) _salt = null; else _salt = (byte[]) value.Clone(); } } // // public methods // [System.Security.SecuritySafeCritical] // auto-generated [Obsolete("Rfc2898DeriveBytes replaces PasswordDeriveBytes for deriving key material from a password and is preferred in new applications.")] // disable csharp compiler warning #0809: obsolete member overrides non-obsolete member #pragma warning disable 0809 public override byte[] GetBytes(int cb) { #if MONO if (cb < 1) throw new IndexOutOfRangeException ("cb"); #endif int ib = 0; byte[] rgb; byte[] rgbOut = new byte[cb]; if (_baseValue == null) { ComputeBaseValue(); } else if (_extra != null) { ib = _extra.Length - _extraCount; if (ib >= cb) { Buffer.InternalBlockCopy(_extra, _extraCount, rgbOut, 0, cb); if (ib > cb) _extraCount += cb; else _extra = null; return rgbOut; } else { // // Note: The second parameter should really be _extraCount instead // However, changing this would constitute a breaking change compared // to what has shipped in V1.x. // Buffer.InternalBlockCopy(_extra, ib, rgbOut, 0, ib); _extra = null; } } rgb = ComputeBytes(cb-ib); Buffer.InternalBlockCopy(rgb, 0, rgbOut, ib, cb-ib); if (rgb.Length + ib > cb) { _extra = rgb; _extraCount = cb-ib; } return rgbOut; } #pragma warning restore 0809 public override void Reset() { _prefix = 0; _extra = null; _baseValue = null; } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { if (_hash != null) { _hash.Dispose(); } if (_baseValue != null) { Array.Clear(_baseValue, 0, _baseValue.Length); } if (_extra != null) { Array.Clear(_extra, 0, _extra.Length); } if (_password != null) { Array.Clear(_password, 0, _password.Length); } if (_salt != null) { Array.Clear(_salt, 0, _salt.Length); } } } [System.Security.SecuritySafeCritical] // auto-generated public byte[] CryptDeriveKey(string algname, string alghashname, int keySize, byte[] rgbIV) { if (keySize < 0) throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeySize")); #if MONO throw new NotSupportedException ("CspParameters are not supported by Mono"); #else int algidhash = X509Utils.NameOrOidToAlgId(alghashname, OidGroup.HashAlgorithm); if (algidhash == 0) throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_InvalidAlgorithm")); int algid = X509Utils.NameOrOidToAlgId(algname, OidGroup.AllGroups); if (algid == 0) throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_InvalidAlgorithm")); // Validate the rgbIV array if (rgbIV == null) throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_InvalidIV")); byte[] key = null; DeriveKey(ProvHandle, algid, algidhash, _password, _password.Length, keySize << 16, rgbIV, rgbIV.Length, JitHelpers.GetObjectHandleOnStack(ref key)); return key; #endif } // // private methods // #if !MONO [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] private static extern void DeriveKey(SafeProvHandle hProv, int algid, int algidHash, byte[] password, int cbPassword, int dwFlags, byte[] IV, int cbIV, ObjectHandleOnStack retKey); #endif private byte[] ComputeBaseValue() { _hash.Initialize(); _hash.TransformBlock(_password, 0, _password.Length, _password, 0); if (_salt != null) _hash.TransformBlock(_salt, 0, _salt.Length, _salt, 0); _hash.TransformFinalBlock(EmptyArray<Byte>.Value, 0, 0); _baseValue = _hash.Hash; _hash.Initialize(); for (int i=1; i<(_iterations-1); i++) { _hash.ComputeHash(_baseValue); _baseValue = _hash.Hash; } return _baseValue; } [System.Security.SecurityCritical] // auto-generated private byte[] ComputeBytes(int cb) { int cbHash; int ib = 0; byte[] rgb; _hash.Initialize(); cbHash = _hash.HashSize / 8; rgb = new byte[((cb+cbHash-1)/cbHash)*cbHash]; using (CryptoStream cs = new CryptoStream(Stream.Null, _hash, CryptoStreamMode.Write)) { HashPrefix(cs); cs.Write(_baseValue, 0, _baseValue.Length); cs.Close(); } Buffer.InternalBlockCopy(_hash.Hash, 0, rgb, ib, cbHash); ib += cbHash; while (cb > ib) { _hash.Initialize(); using (CryptoStream cs = new CryptoStream(Stream.Null, _hash, CryptoStreamMode.Write)) { HashPrefix(cs); cs.Write(_baseValue, 0, _baseValue.Length); cs.Close(); } Buffer.InternalBlockCopy(_hash.Hash, 0, rgb, ib, cbHash); ib += cbHash; } return rgb; } void HashPrefix(CryptoStream cs) { int cb = 0; byte[] rgb = {(byte)'0', (byte)'0', (byte)'0'}; if (_prefix > 999) throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_TooManyBytes")); if (_prefix >= 100) { rgb[0] += (byte) (_prefix /100); cb += 1; } if (_prefix >= 10) { rgb[cb] += (byte) ((_prefix % 100) / 10); cb += 1; } if (_prefix > 0) { rgb[cb] += (byte) (_prefix % 10); cb += 1; cs.Write(rgb, 0, cb); } _prefix += 1; } } }
// ==++== // // Copyright(c) Microsoft Corporation. All rights reserved. // // ==--== // <OWNER>[....]</OWNER> // namespace System.Reflection { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Diagnostics.Tracing; using System.Globalization; using System.Runtime; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; #if FEATURE_REMOTING using System.Runtime.Remoting.Metadata; #endif //FEATURE_REMOTING using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.Threading; using MemberListType = System.RuntimeType.MemberListType; using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; using System.Runtime.CompilerServices; [Serializable] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_ConstructorInfo))] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] #pragma warning restore 618 [System.Runtime.InteropServices.ComVisible(true)] public abstract class ConstructorInfo : MethodBase, _ConstructorInfo { #region Static Members [System.Runtime.InteropServices.ComVisible(true)] public readonly static String ConstructorName = ".ctor"; [System.Runtime.InteropServices.ComVisible(true)] public readonly static String TypeConstructorName = ".cctor"; #endregion #region Constructor protected ConstructorInfo() { } #endregion #if !FEATURE_CORECLR public static bool operator ==(ConstructorInfo left, ConstructorInfo right) { if (ReferenceEquals(left, right)) return true; if ((object)left == null || (object)right == null || left is RuntimeConstructorInfo || right is RuntimeConstructorInfo) { return false; } return left.Equals(right); } public static bool operator !=(ConstructorInfo left, ConstructorInfo right) { return !(left == right); } #endif // !FEATURE_CORECLR #if FEATURE_NETCORE || !FEATURE_CORECLR public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } #endif //FEATURE_NETCORE || !FEATURE_CORECLR #region Internal Members internal virtual Type GetReturnType() { throw new NotImplementedException(); } #endregion #region MemberInfo Overrides [System.Runtime.InteropServices.ComVisible(true)] public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Constructor; } } #endregion #region Public Abstract\Virtual Members public abstract Object Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture); #endregion #region Public Members [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public Object Invoke(Object[] parameters) { // Theoretically we should set up a LookForMyCaller stack mark here and pass that along. // But to maintain backward compatibility we can't switch to calling an // internal overload that takes a stack mark. // Fortunately the stack walker skips all the reflection invocation frames including this one. // So this method will never be returned by the stack walker as the caller. // See SystemDomain::CallersMethodCallbackWithStackMark in AppDomain.cpp. return Invoke(BindingFlags.Default, null, parameters, null); } #endregion #region COM Interop Support Type _ConstructorInfo.GetType() { return base.GetType(); } Object _ConstructorInfo.Invoke_2(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { return Invoke(obj, invokeAttr, binder, parameters, culture); } Object _ConstructorInfo.Invoke_3(Object obj, Object[] parameters) { return Invoke(obj, parameters); } Object _ConstructorInfo.Invoke_4(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { return Invoke(invokeAttr, binder, parameters, culture); } Object _ConstructorInfo.Invoke_5(Object[] parameters) { return Invoke(parameters); } void _ConstructorInfo.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _ConstructorInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _ConstructorInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } // If you implement this method, make sure to include _ConstructorInfo.Invoke in VM\DangerousAPIs.h and // include _ConstructorInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp. void _ConstructorInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } #endregion } [Serializable] internal sealed class RuntimeConstructorInfo : ConstructorInfo, ISerializable, IRuntimeMethodInfo { #region Private Data Members private volatile RuntimeType m_declaringType; private RuntimeTypeCache m_reflectedTypeCache; private string m_toString; private ParameterInfo[] m_parameters = null; // Created lazily when GetParameters() is called. #pragma warning disable 169 private object _empty1; // These empties are used to ensure that RuntimeConstructorInfo and RuntimeMethodInfo are have a layout which is sufficiently similar private object _empty2; private object _empty3; #pragma warning restore 169 private IntPtr m_handle; private MethodAttributes m_methodAttributes; private BindingFlags m_bindingFlags; private volatile Signature m_signature; private INVOCATION_FLAGS m_invocationFlags; #if FEATURE_APPX private bool IsNonW8PFrameworkAPI() { if (DeclaringType.IsArray && IsPublic && !IsStatic) return false; RuntimeAssembly rtAssembly = GetRuntimeAssembly(); if (rtAssembly.IsFrameworkAssembly()) { int ctorToken = rtAssembly.InvocableAttributeCtorToken; if (System.Reflection.MetadataToken.IsNullToken(ctorToken) || !CustomAttribute.IsAttributeDefined(GetRuntimeModule(), MetadataToken, ctorToken)) return true; } if (GetRuntimeType().IsNonW8PFrameworkAPI()) return true; return false; } internal override bool IsDynamicallyInvokable { get { return !AppDomain.ProfileAPICheck || !IsNonW8PFrameworkAPI(); } } #endif // FEATURE_APPX internal INVOCATION_FLAGS InvocationFlags { [System.Security.SecuritySafeCritical] get { if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0) { INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_IS_CTOR; // this is a given Type declaringType = DeclaringType; // // first take care of all the NO_INVOKE cases. if ( declaringType == typeof(void) || (declaringType != null && declaringType.ContainsGenericParameters) || ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) || ((Attributes & MethodAttributes.RequireSecObject) == MethodAttributes.RequireSecObject)) { // We don't need other flags if this method cannot be invoked invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE; } else if (IsStatic || declaringType != null && declaringType.IsAbstract) { invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_CTOR_INVOKE; } else { // this should be an invocable method, determine the other flags that participate in invocation invocationFlags |= RuntimeMethodHandle.GetSecurityFlags(this); if ( (invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) == 0 && ((Attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public || (declaringType != null && declaringType.NeedsReflectionSecurityCheck)) ) { // If method is non-public, or declaring type is not visible invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY; } // Check for attempt to create a delegate class, we demand unmanaged // code permission for this since it's hard to validate the target address. if (typeof(Delegate).IsAssignableFrom(DeclaringType)) invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR; } #if FEATURE_APPX if (AppDomain.ProfileAPICheck && IsNonW8PFrameworkAPI()) invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API; #endif // FEATURE_APPX m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED; } return m_invocationFlags; } } #endregion #region Constructor [System.Security.SecurityCritical] // auto-generated internal RuntimeConstructorInfo( RuntimeMethodHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags) { Contract.Ensures(methodAttributes == RuntimeMethodHandle.GetAttributes(handle)); m_bindingFlags = bindingFlags; m_reflectedTypeCache = reflectedTypeCache; m_declaringType = declaringType; m_handle = handle.Value; m_methodAttributes = methodAttributes; } #endregion #if FEATURE_REMOTING #region Legacy Remoting Cache // The size of CachedData is accounted for by BaseObjectWithCachedData in object.h. // This member is currently being used by Remoting for caching remoting data. If you // need to cache data here, talk to the Remoting team to work out a mechanism, so that // both caching systems can happily work together. private RemotingMethodCachedData m_cachedData; internal RemotingMethodCachedData RemotingCache { get { // This grabs an internal copy of m_cachedData and uses // that instead of looking at m_cachedData directly because // the cache may get cleared asynchronously. This prevents // us from having to take a lock. RemotingMethodCachedData cache = m_cachedData; if (cache == null) { cache = new RemotingMethodCachedData(this); RemotingMethodCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null); if (ret != null) cache = ret; } return cache; } } #endregion #endif //FEATURE_REMOTING #region NonPublic Methods RuntimeMethodHandleInternal IRuntimeMethodInfo.Value { [System.Security.SecuritySafeCritical] get { return new RuntimeMethodHandleInternal(m_handle); } } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif internal override bool CacheEquals(object o) { RuntimeConstructorInfo m = o as RuntimeConstructorInfo; if ((object)m == null) return false; return m.m_handle == m_handle; } private Signature Signature { get { if (m_signature == null) m_signature = new Signature(this, m_declaringType); return m_signature; } } private RuntimeType ReflectedTypeInternal { get { return m_reflectedTypeCache.GetRuntimeType(); } } private void CheckConsistency(Object target) { if (target == null && IsStatic) return; if (!m_declaringType.IsInstanceOfType(target)) { if (target == null) throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatMethReqTarg")); throw new TargetException(Environment.GetResourceString("RFLCT.Targ_ITargMismatch")); } } internal BindingFlags BindingFlags { get { return m_bindingFlags; } } // Differs from MethodHandle in that it will return a valid handle even for reflection only loaded types internal RuntimeMethodHandle GetMethodHandle() { return new RuntimeMethodHandle(this); } internal bool IsOverloaded { get { return m_reflectedTypeCache.GetConstructorList(MemberListType.CaseSensitive, Name).Length > 1; } } #endregion #region Object Overrides public override String ToString() { // "Void" really doesn't make sense here. But we'll keep it for compat reasons. if (m_toString == null) m_toString = "Void " + FormatNameAndSig(); return m_toString; } #endregion #region ICustomAttributeProvider public override Object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); } [System.Security.SecuritySafeCritical] // auto-generated public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); return CustomAttribute.IsDefined(this, attributeRuntimeType); } public override IList<CustomAttributeData> GetCustomAttributesData() { return CustomAttributeData.GetCustomAttributesInternal(this); } #endregion #region MemberInfo Overrides public override String Name { [System.Security.SecuritySafeCritical] // auto-generated get { return RuntimeMethodHandle.GetName(this); } } [System.Security.SecuritySafeCritical] internal override String GetFullNameForEtw() { return RuntimeMethodHandle.GetName(this); } [System.Runtime.InteropServices.ComVisible(true)] public override MemberTypes MemberType { get { return MemberTypes.Constructor; } } public override Type DeclaringType { get { return m_reflectedTypeCache.IsGlobal ? null : m_declaringType; } } public override Type ReflectedType { get { return m_reflectedTypeCache.IsGlobal ? null : ReflectedTypeInternal; } } public override int MetadataToken { [System.Security.SecuritySafeCritical] // auto-generated get { return RuntimeMethodHandle.GetMethodDef(this); } } public override Module Module { get { return GetRuntimeModule(); } } internal RuntimeType GetRuntimeType() { return m_declaringType; } internal RuntimeModule GetRuntimeModule() { return RuntimeTypeHandle.GetModule(m_declaringType); } internal RuntimeAssembly GetRuntimeAssembly() { return GetRuntimeModule().GetRuntimeAssembly(); } #endregion #region MethodBase Overrides // This seems to always returns System.Void. internal override Type GetReturnType() { return Signature.ReturnType; } [System.Security.SecuritySafeCritical] // auto-generated internal override ParameterInfo[] GetParametersNoCopy() { if (m_parameters == null) m_parameters = RuntimeParameterInfo.GetParameters(this, this, Signature); return m_parameters; } [Pure] public override ParameterInfo[] GetParameters() { ParameterInfo[] parameters = GetParametersNoCopy(); if (parameters.Length == 0) return parameters; ParameterInfo[] ret = new ParameterInfo[parameters.Length]; Array.Copy(parameters, ret, parameters.Length); return ret; } public override MethodImplAttributes GetMethodImplementationFlags() { return RuntimeMethodHandle.GetImplAttributes(this); } public override RuntimeMethodHandle MethodHandle { get { Type declaringType = DeclaringType; if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly")); return new RuntimeMethodHandle(this); } } public override MethodAttributes Attributes { get { return m_methodAttributes; } } public override CallingConventions CallingConvention { get { return Signature.CallingConvention; } } internal static void CheckCanCreateInstance(Type declaringType, bool isVarArg) { if (declaringType == null) throw new ArgumentNullException("declaringType"); Contract.EndContractBlock(); // ctor is ReflectOnly if (declaringType is ReflectionOnlyType) throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyInvoke")); // ctor is declared on interface class else if (declaringType.IsInterface) throw new MemberAccessException( String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Acc_CreateInterfaceEx"), declaringType)); // ctor is on an abstract class else if (declaringType.IsAbstract) throw new MemberAccessException( String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Acc_CreateAbstEx"), declaringType)); // ctor is on a class that contains stack pointers else if (declaringType.GetRootElementType() == typeof(ArgIterator)) throw new NotSupportedException(); // ctor is vararg else if (isVarArg) throw new NotSupportedException(); // ctor is generic or on a generic class else if (declaringType.ContainsGenericParameters) { #if FEATURE_LEGACYNETCF if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) throw new ArgumentException( String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Acc_CreateGenericEx"), declaringType)); else #endif throw new MemberAccessException( String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Acc_CreateGenericEx"), declaringType)); } // ctor is declared on System.Void else if (declaringType == typeof(void)) throw new MemberAccessException(Environment.GetResourceString("Access_Void")); } internal void ThrowNoInvokeException() { CheckCanCreateInstance(DeclaringType, (CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs); // ctor is .cctor if ((Attributes & MethodAttributes.Static) == MethodAttributes.Static) throw new MemberAccessException(Environment.GetResourceString("Acc_NotClassInit")); throw new TargetException(); } [System.Security.SecuritySafeCritical] // auto-generated [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public override Object Invoke( Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { INVOCATION_FLAGS invocationFlags = InvocationFlags; if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0) ThrowNoInvokeException(); // check basic method consistency. This call will throw if there are problems in the target/method relationship CheckConsistency(obj); #if FEATURE_APPX if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark); if (caller != null && !caller.IsSafeForReflection()) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName)); } #endif if (obj != null) { #if FEATURE_CORECLR // For unverifiable code, we require the caller to be critical. // Adding the INVOCATION_FLAGS_NEED_SECURITY flag makes that check happen invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY; #else // FEATURE_CORECLR new SecurityPermission(SecurityPermissionFlag.SkipVerification).Demand(); #endif // FEATURE_CORECLR } if ((invocationFlags &(INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0) { #if !FEATURE_CORECLR if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD) != 0) CodeAccessPermission.Demand(PermissionType.ReflectionMemberAccess); if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0) #endif // !FEATURE_CORECLR RuntimeMethodHandle.PerformSecurityCheck(obj, this, m_declaringType, (uint)m_invocationFlags); } Signature sig = Signature; // get the signature int formalCount = sig.Arguments.Length; int actualCount =(parameters != null) ? parameters.Length : 0; if (formalCount != actualCount) throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt")); // if we are here we passed all the previous checks. Time to look at the arguments if (actualCount > 0) { Object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig); Object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, sig, false); // copy out. This should be made only if ByRef are present. for (int index = 0; index < arguments.Length; index++) parameters[index] = arguments[index]; return retValue; } #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.ConstructorInfoInvoke(GetRuntimeType().GetFullNameForEtw(), GetFullNameForEtw()); } #endif return RuntimeMethodHandle.InvokeMethod(obj, null, sig, false); } [System.Security.SecuritySafeCritical] // overrides SC member #pragma warning disable 618 [ReflectionPermissionAttribute(SecurityAction.Demand, Flags = ReflectionPermissionFlag.MemberAccess)] #pragma warning restore 618 public override MethodBody GetMethodBody() { MethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal); if (mb != null) mb.m_methodBase = this; return mb; } public override bool IsSecurityCritical { get { return RuntimeMethodHandle.IsSecurityCritical(this); } } public override bool IsSecuritySafeCritical { get { return RuntimeMethodHandle.IsSecuritySafeCritical(this); } } public override bool IsSecurityTransparent { get { return RuntimeMethodHandle.IsSecurityTransparent(this); } } public override bool ContainsGenericParameters { get { return (DeclaringType != null && DeclaringType.ContainsGenericParameters); } } #endregion #region ConstructorInfo Overrides [System.Security.SecuritySafeCritical] // auto-generated [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public override Object Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { INVOCATION_FLAGS invocationFlags = InvocationFlags; // get the declaring TypeHandle early for consistent exceptions in IntrospectionOnly context RuntimeTypeHandle declaringTypeHandle = m_declaringType.TypeHandle; if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS | INVOCATION_FLAGS.INVOCATION_FLAGS_NO_CTOR_INVOKE)) != 0) ThrowNoInvokeException(); #if FEATURE_APPX if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark); if (caller != null && !caller.IsSafeForReflection()) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName)); } #endif if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY | INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR)) != 0) { #if !FEATURE_CORECLR if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD) != 0) CodeAccessPermission.Demand(PermissionType.ReflectionMemberAccess); if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0) #endif // !FEATURE_CORECLR RuntimeMethodHandle.PerformSecurityCheck(null, this, m_declaringType, (uint)(m_invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_CONSTRUCTOR_INVOKE)); #if !FEATURE_CORECLR if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR) != 0) new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); #endif // !FEATURE_CORECLR } // get the signature Signature sig = Signature; int formalCount = sig.Arguments.Length; int actualCount =(parameters != null) ? parameters.Length : 0; if (formalCount != actualCount) throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt")); // We don't need to explicitly invoke the class constructor here, // JIT/NGen will insert the call to .cctor in the instance ctor. // if we are here we passed all the previous checks. Time to look at the arguments if (actualCount > 0) { Object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig); Object retValue = RuntimeMethodHandle.InvokeMethod(null, arguments, sig, true); // copy out. This should be made only if ByRef are present. for (int index = 0; index < arguments.Length; index++) parameters[index] = arguments[index]; return retValue; } return RuntimeMethodHandle.InvokeMethod(null, null, sig, true); } #endregion #region ISerializable Implementation [System.Security.SecurityCritical] // auto-generated public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException("info"); Contract.EndContractBlock(); MemberInfoSerializationHolder.GetSerializationInfo( info, Name, ReflectedTypeInternal, ToString(), SerializationToString(), MemberTypes.Constructor, null); } internal string SerializationToString() { // We don't need the return type for constructors. return FormatNameAndSig(true); } internal void SerializationInvoke(Object target, SerializationInfo info, StreamingContext context) { RuntimeMethodHandle.SerializationInvoke(this, target, info, ref context); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void CompareEqualUInt32() { var test = new SimpleBinaryOpTest__CompareEqualUInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareEqualUInt32 { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(UInt32); private const int Op2ElementCount = VectorSize / sizeof(UInt32); private const int RetElementCount = VectorSize / sizeof(UInt32); private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt32[] _data2 = new UInt32[Op2ElementCount]; private static Vector256<UInt32> _clsVar1; private static Vector256<UInt32> _clsVar2; private Vector256<UInt32> _fld1; private Vector256<UInt32> _fld2; private SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32> _dataTable; static SimpleBinaryOpTest__CompareEqualUInt32() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__CompareEqualUInt32() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32>(_data1, _data2, new UInt32[RetElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.CompareEqual( Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.CompareEqual( Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.CompareEqual( Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.CompareEqual( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr); var result = Avx2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)); var result = Avx2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)); var result = Avx2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__CompareEqualUInt32(); var result = Avx2.CompareEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.CompareEqual(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<UInt32> left, Vector256<UInt32> right, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "") { if (result[0] != ((left[0] == right[0]) ? unchecked((uint)(-1)) : 0)) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((left[i] == right[i]) ? unchecked((uint)(-1)) : 0)) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.CompareEqual)}<UInt32>(Vector256<UInt32>, Vector256<UInt32>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; using Umbraco.Cms.Core.Mapping; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Models.PublishedContent; using Umbraco.Cms.Core.PublishedCache; using Umbraco.Cms.Core.Scoping; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Web.Common.DependencyInjection; using Umbraco.Extensions; namespace Umbraco.Cms.Core.Security { /// <summary> /// A custom user store that uses Umbraco member data /// </summary> public class MemberUserStore : UmbracoUserStore<MemberIdentityUser, UmbracoIdentityRole>, IMemberUserStore { private const string GenericIdentityErrorCode = "IdentityErrorUserStore"; private readonly IMemberService _memberService; private readonly IUmbracoMapper _mapper; private readonly IScopeProvider _scopeProvider; private readonly IPublishedSnapshotAccessor _publishedSnapshotAccessor; private readonly IExternalLoginWithKeyService _externalLoginService; private readonly ITwoFactorLoginService _twoFactorLoginService; /// <summary> /// Initializes a new instance of the <see cref="MemberUserStore"/> class for the members identity store /// </summary> /// <param name="memberService">The member service</param> /// <param name="mapper">The mapper for properties</param> /// <param name="scopeProvider">The scope provider</param> /// <param name="describer">The error describer</param> /// <param name="publishedSnapshotAccessor">The published snapshot accessor</param> /// <param name="externalLoginService">The external login service</param> /// <param name="twoFactorLoginService">The two factor login service</param> [ActivatorUtilitiesConstructor] public MemberUserStore( IMemberService memberService, IUmbracoMapper mapper, IScopeProvider scopeProvider, IdentityErrorDescriber describer, IPublishedSnapshotAccessor publishedSnapshotAccessor, IExternalLoginWithKeyService externalLoginService, ITwoFactorLoginService twoFactorLoginService ) : base(describer) { _memberService = memberService ?? throw new ArgumentNullException(nameof(memberService)); _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); _scopeProvider = scopeProvider ?? throw new ArgumentNullException(nameof(scopeProvider)); _publishedSnapshotAccessor = publishedSnapshotAccessor; _externalLoginService = externalLoginService; _twoFactorLoginService = twoFactorLoginService; } [Obsolete("Use ctor with IExternalLoginWithKeyService and ITwoFactorLoginService param")] public MemberUserStore( IMemberService memberService, IUmbracoMapper mapper, IScopeProvider scopeProvider, IdentityErrorDescriber describer, IPublishedSnapshotAccessor publishedSnapshotAccessor, IExternalLoginService externalLoginService) : this(memberService, mapper, scopeProvider, describer, publishedSnapshotAccessor, StaticServiceProvider.Instance.GetRequiredService<IExternalLoginWithKeyService>(), StaticServiceProvider.Instance.GetRequiredService<ITwoFactorLoginService>()) { } [Obsolete("Use ctor with IExternalLoginWithKeyService and ITwoFactorLoginService param")] public MemberUserStore( IMemberService memberService, IUmbracoMapper mapper, IScopeProvider scopeProvider, IdentityErrorDescriber describer, IPublishedSnapshotAccessor publishedSnapshotAccessor) : this(memberService, mapper, scopeProvider, describer, publishedSnapshotAccessor, StaticServiceProvider.Instance.GetRequiredService<IExternalLoginWithKeyService>(), StaticServiceProvider.Instance.GetRequiredService<ITwoFactorLoginService>()) { } /// <inheritdoc /> public override Task<IdentityResult> CreateAsync(MemberIdentityUser user, CancellationToken cancellationToken = default) { try { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } using IScope scope = _scopeProvider.CreateScope(autoComplete: true); // create member IMember memberEntity = _memberService.CreateMember( user.UserName, user.Email, user.Name.IsNullOrWhiteSpace() ? user.UserName : user.Name, user.MemberTypeAlias.IsNullOrWhiteSpace() ? Constants.Security.DefaultMemberTypeAlias : user.MemberTypeAlias); UpdateMemberProperties(memberEntity, user); // create the member _memberService.Save(memberEntity); //We need to add roles now that the member has an Id. It do not work implicit in UpdateMemberProperties _memberService.AssignRoles(new[] { memberEntity.Id }, user.Roles.Select(x => x.RoleId).ToArray()); if (!memberEntity.HasIdentity) { throw new DataException("Could not create the member, check logs for details"); } // re-assign id user.Id = UserIdToString(memberEntity.Id); user.Key = memberEntity.Key; // we have to remember whether Logins property is dirty, since the UpdateMemberProperties will reset it. var isLoginsPropertyDirty = user.IsPropertyDirty(nameof(MemberIdentityUser.Logins)); var isTokensPropertyDirty = user.IsPropertyDirty(nameof(MemberIdentityUser.LoginTokens)); if (isLoginsPropertyDirty) { _externalLoginService.Save( memberEntity.Key, user.Logins.Select(x => new ExternalLogin( x.LoginProvider, x.ProviderKey, x.UserData))); } if (isTokensPropertyDirty) { _externalLoginService.Save( memberEntity.Key, user.LoginTokens.Select(x => new ExternalLoginToken( x.LoginProvider, x.Name, x.Value))); } return Task.FromResult(IdentityResult.Success); } catch (Exception ex) { return Task.FromResult(IdentityResult.Failed(new IdentityError { Code = GenericIdentityErrorCode, Description = ex.Message })); } } /// <inheritdoc /> public override Task<IdentityResult> UpdateAsync(MemberIdentityUser user, CancellationToken cancellationToken = default) { try { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } if (!int.TryParse(user.Id, NumberStyles.Integer, CultureInfo.InvariantCulture, out var asInt)) { //TODO: should this be thrown, or an identity result? throw new InvalidOperationException("The user id must be an integer to work with the Umbraco"); } using IScope scope = _scopeProvider.CreateScope(autoComplete: true); IMember found = _memberService.GetById(asInt); if (found != null) { // we have to remember whether Logins property is dirty, since the UpdateMemberProperties will reset it. var isLoginsPropertyDirty = user.IsPropertyDirty(nameof(MemberIdentityUser.Logins)); var isTokensPropertyDirty = user.IsPropertyDirty(nameof(MemberIdentityUser.LoginTokens)); MemberDataChangeType memberChangeType = UpdateMemberProperties(found, user); if (memberChangeType == MemberDataChangeType.FullSave) { _memberService.Save(found); } else if (memberChangeType == MemberDataChangeType.LoginOnly) { // If the member is only logging in, just issue that command without // any write locks so we are creating a bottleneck. _memberService.SetLastLogin(found.Username, DateTime.Now); } if (isLoginsPropertyDirty) { _externalLoginService.Save( found.Key, user.Logins.Select(x => new ExternalLogin( x.LoginProvider, x.ProviderKey, x.UserData))); } if (isTokensPropertyDirty) { _externalLoginService.Save( found.Key, user.LoginTokens.Select(x => new ExternalLoginToken( x.LoginProvider, x.Name, x.Value))); } } return Task.FromResult(IdentityResult.Success); } catch (Exception ex) { return Task.FromResult(IdentityResult.Failed(new IdentityError { Code = GenericIdentityErrorCode, Description = ex.Message })); } } /// <inheritdoc /> public override Task<IdentityResult> DeleteAsync(MemberIdentityUser user, CancellationToken cancellationToken = default) { try { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } IMember found = _memberService.GetById(UserIdToInt(user.Id)); if (found != null) { _memberService.Delete(found); } _externalLoginService.DeleteUserLogins(user.Key); return Task.FromResult(IdentityResult.Success); } catch (Exception ex) { return Task.FromResult(IdentityResult.Failed(new IdentityError { Code = GenericIdentityErrorCode, Description = ex.Message })); } } /// <inheritdoc /> protected override Task<MemberIdentityUser> FindUserAsync(string userId, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (string.IsNullOrWhiteSpace(userId)) { throw new ArgumentNullException(nameof(userId)); } IMember user = Guid.TryParse(userId, out var key) ? _memberService.GetByKey(key) : _memberService.GetById(UserIdToInt(userId)); if (user == null) { return Task.FromResult((MemberIdentityUser)null); } return Task.FromResult(AssignLoginsCallback(_mapper.Map<MemberIdentityUser>(user))); } /// <inheritdoc /> public override Task<MemberIdentityUser> FindByNameAsync(string userName, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); IMember user = _memberService.GetByUsername(userName); if (user == null) { return Task.FromResult((MemberIdentityUser)null); } MemberIdentityUser result = AssignLoginsCallback(_mapper.Map<MemberIdentityUser>(user)); return Task.FromResult(result); } /// <inheritdoc /> public override Task<MemberIdentityUser> FindByEmailAsync(string email, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); IMember member = _memberService.GetByEmail(email); MemberIdentityUser result = member == null ? null : _mapper.Map<MemberIdentityUser>(member); return Task.FromResult(AssignLoginsCallback(result)); } /// <inheritdoc /> public override Task AddLoginAsync(MemberIdentityUser user, UserLoginInfo login, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } if (login == null) { throw new ArgumentNullException(nameof(login)); } if (string.IsNullOrWhiteSpace(login.LoginProvider)) { throw new ArgumentNullException(nameof(login.LoginProvider)); } if (string.IsNullOrWhiteSpace(login.ProviderKey)) { throw new ArgumentNullException(nameof(login.ProviderKey)); } ICollection<IIdentityUserLogin> logins = user.Logins; var instance = new IdentityUserLogin( login.LoginProvider, login.ProviderKey, user.Id.ToString()); IdentityUserLogin userLogin = instance; logins.Add(userLogin); return Task.CompletedTask; } /// <inheritdoc /> public override Task RemoveLoginAsync(MemberIdentityUser user, string loginProvider, string providerKey, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } if (string.IsNullOrWhiteSpace(loginProvider)) { throw new ArgumentNullException(nameof(loginProvider)); } if (string.IsNullOrWhiteSpace(providerKey)) { throw new ArgumentNullException(nameof(providerKey)); } IIdentityUserLogin userLogin = user.Logins.SingleOrDefault(l => l.LoginProvider == loginProvider && l.ProviderKey == providerKey); if (userLogin != null) { user.Logins.Remove(userLogin); } return Task.CompletedTask; } /// <inheritdoc /> public override Task<IList<UserLoginInfo>> GetLoginsAsync(MemberIdentityUser user, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } return Task.FromResult((IList<UserLoginInfo>)user.Logins.Select(l => new UserLoginInfo(l.LoginProvider, l.ProviderKey, l.LoginProvider)).ToList()); } /// <inheritdoc /> protected override async Task<IdentityUserLogin<string>> FindUserLoginAsync(string userId, string loginProvider, string providerKey, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (string.IsNullOrWhiteSpace(loginProvider)) { throw new ArgumentNullException(nameof(loginProvider)); } if (string.IsNullOrWhiteSpace(providerKey)) { throw new ArgumentNullException(nameof(providerKey)); } MemberIdentityUser user = await FindUserAsync(userId, cancellationToken); if (user == null) { return await Task.FromResult((IdentityUserLogin<string>)null); } IList<UserLoginInfo> logins = await GetLoginsAsync(user, cancellationToken); UserLoginInfo found = logins.FirstOrDefault(x => x.ProviderKey == providerKey && x.LoginProvider == loginProvider); if (found == null) { return await Task.FromResult((IdentityUserLogin<string>)null); } return new IdentityUserLogin<string> { LoginProvider = found.LoginProvider, ProviderKey = found.ProviderKey, // TODO: We don't store this value so it will be null ProviderDisplayName = found.ProviderDisplayName, UserId = user.Id }; } /// <inheritdoc /> protected override Task<IdentityUserLogin<string>> FindUserLoginAsync(string loginProvider, string providerKey, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (string.IsNullOrWhiteSpace(loginProvider)) { throw new ArgumentNullException(nameof(loginProvider)); } if (string.IsNullOrWhiteSpace(providerKey)) { throw new ArgumentNullException(nameof(providerKey)); } var logins = _externalLoginService.Find(loginProvider, providerKey).ToList(); if (logins.Count == 0) { return Task.FromResult((IdentityUserLogin<string>)null); } IIdentityUserLogin found = logins[0]; return Task.FromResult(new IdentityUserLogin<string> { LoginProvider = found.LoginProvider, ProviderKey = found.ProviderKey, // TODO: We don't store this value so it will be null ProviderDisplayName = null, UserId = found.UserId }); } /// <summary> /// Gets a list of role names the specified user belongs to. /// </summary> /// <remarks> /// This lazy loads the roles for the member /// </remarks> public override Task<IList<string>> GetRolesAsync(MemberIdentityUser user, CancellationToken cancellationToken = default) { EnsureRoles(user); return base.GetRolesAsync(user, cancellationToken); } private void EnsureRoles(MemberIdentityUser user) { if (user.Roles.Count == 0) { // if there are no roles, they either haven't been loaded since we don't eagerly // load for members, or they just have no roles. IEnumerable<string> currentRoles = _memberService.GetAllRoles(user.UserName); ICollection<IdentityUserRole<string>> roles = currentRoles.Select(role => new IdentityUserRole<string> { RoleId = role, UserId = user.Id }).ToList(); user.Roles = roles; } } /// <summary> /// Returns true if a user is in the role /// </summary> public override Task<bool> IsInRoleAsync(MemberIdentityUser user, string roleName, CancellationToken cancellationToken = default) { EnsureRoles(user); return base.IsInRoleAsync(user, roleName, cancellationToken); } /// <summary> /// Lists all users of a given role. /// </summary> public override Task<IList<MemberIdentityUser>> GetUsersInRoleAsync(string roleName, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (string.IsNullOrWhiteSpace(roleName)) { throw new ArgumentNullException(nameof(roleName)); } IEnumerable<IMember> members = _memberService.GetMembersByMemberType(roleName); IList<MemberIdentityUser> membersIdentityUsers = members.Select(x => _mapper.Map<MemberIdentityUser>(x)).ToList(); return Task.FromResult(membersIdentityUsers); } /// <inheritdoc/> protected override Task<UmbracoIdentityRole> FindRoleAsync(string roleName, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(roleName)) { throw new ArgumentNullException(nameof(roleName)); } IMemberGroup group = _memberService.GetAllRoles().SingleOrDefault(x => x.Name == roleName); if (group == null) { return Task.FromResult((UmbracoIdentityRole)null); } return Task.FromResult(new UmbracoIdentityRole(group.Name) { //TODO: what should the alias be? Id = group.Id.ToString() }); } /// <inheritdoc/> protected override async Task<IdentityUserRole<string>> FindUserRoleAsync(string userId, string roleId, CancellationToken cancellationToken) { MemberIdentityUser user = await FindUserAsync(userId, cancellationToken); if (user == null) { return null; } IdentityUserRole<string> found = user.Roles.FirstOrDefault(x => x.RoleId.InvariantEquals(roleId)); return found; } /// <summary> /// Overridden to support Umbraco's own data storage requirements /// </summary> /// <remarks> /// The base class's implementation of this calls into FindTokenAsync and AddUserTokenAsync, both methods will only work with ORMs that are change /// tracking ORMs like EFCore. /// </remarks> /// <inheritdoc /> public override Task SetTokenAsync(MemberIdentityUser user, string loginProvider, string name, string value, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } IIdentityUserToken token = user.LoginTokens.FirstOrDefault(x => x.LoginProvider.InvariantEquals(loginProvider) && x.Name.InvariantEquals(name)); if (token == null) { user.LoginTokens.Add(new IdentityUserToken(loginProvider, name, value, user.Id)); } else { token.Value = value; } return Task.CompletedTask; } private MemberIdentityUser AssignLoginsCallback(MemberIdentityUser user) { if (user != null) { user.SetLoginsCallback(new Lazy<IEnumerable<IIdentityUserLogin>>(() => _externalLoginService.GetExternalLogins(user.Key))); user.SetTokensCallback(new Lazy<IEnumerable<IIdentityUserToken>>(() => _externalLoginService.GetExternalLoginTokens(user.Key))); } return user; } private MemberDataChangeType UpdateMemberProperties(IMember member, MemberIdentityUser identityUser) { MemberDataChangeType changeType = MemberDataChangeType.None; // don't assign anything if nothing has changed as this will trigger the track changes of the model if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.LastLoginDateUtc)) || (member.LastLoginDate != default && identityUser.LastLoginDateUtc.HasValue == false) || (identityUser.LastLoginDateUtc.HasValue && member.LastLoginDate.ToUniversalTime() != identityUser.LastLoginDateUtc.Value)) { changeType = MemberDataChangeType.LoginOnly; // if the LastLoginDate is being set to MinValue, don't convert it ToLocalTime DateTime dt = identityUser.LastLoginDateUtc == DateTime.MinValue ? DateTime.MinValue : identityUser.LastLoginDateUtc.Value.ToLocalTime(); member.LastLoginDate = dt; } if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.LastPasswordChangeDateUtc)) || (member.LastPasswordChangeDate != default && identityUser.LastPasswordChangeDateUtc.HasValue == false) || (identityUser.LastPasswordChangeDateUtc.HasValue && member.LastPasswordChangeDate.ToUniversalTime() != identityUser.LastPasswordChangeDateUtc.Value)) { changeType = MemberDataChangeType.FullSave; member.LastPasswordChangeDate = identityUser.LastPasswordChangeDateUtc.Value.ToLocalTime(); } if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.Comments)) && member.Comments != identityUser.Comments && identityUser.Comments.IsNullOrWhiteSpace() == false) { changeType = MemberDataChangeType.FullSave; member.Comments = identityUser.Comments; } if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.EmailConfirmed)) || (member.EmailConfirmedDate.HasValue && member.EmailConfirmedDate.Value != default && identityUser.EmailConfirmed == false) || ((member.EmailConfirmedDate.HasValue == false || member.EmailConfirmedDate.Value == default) && identityUser.EmailConfirmed)) { changeType = MemberDataChangeType.FullSave; member.EmailConfirmedDate = identityUser.EmailConfirmed ? (DateTime?)DateTime.Now : null; } if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.Name)) && member.Name != identityUser.Name && identityUser.Name.IsNullOrWhiteSpace() == false) { changeType = MemberDataChangeType.FullSave; member.Name = identityUser.Name; } if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.Email)) && member.Email != identityUser.Email && identityUser.Email.IsNullOrWhiteSpace() == false) { changeType = MemberDataChangeType.FullSave; member.Email = identityUser.Email; } if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.AccessFailedCount)) && member.FailedPasswordAttempts != identityUser.AccessFailedCount) { changeType = MemberDataChangeType.FullSave; member.FailedPasswordAttempts = identityUser.AccessFailedCount; } if (member.IsLockedOut != identityUser.IsLockedOut) { changeType = MemberDataChangeType.FullSave; member.IsLockedOut = identityUser.IsLockedOut; if (member.IsLockedOut) { // need to set the last lockout date member.LastLockoutDate = DateTime.Now; } } if (member.IsApproved != identityUser.IsApproved) { changeType = MemberDataChangeType.FullSave; member.IsApproved = identityUser.IsApproved; } if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.UserName)) && member.Username != identityUser.UserName && identityUser.UserName.IsNullOrWhiteSpace() == false) { changeType = MemberDataChangeType.FullSave; member.Username = identityUser.UserName; } if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.PasswordHash)) && member.RawPasswordValue != identityUser.PasswordHash && identityUser.PasswordHash.IsNullOrWhiteSpace() == false) { changeType = MemberDataChangeType.FullSave; member.RawPasswordValue = identityUser.PasswordHash; member.PasswordConfiguration = identityUser.PasswordConfig; } if (member.PasswordConfiguration != identityUser.PasswordConfig) { changeType = MemberDataChangeType.FullSave; member.PasswordConfiguration = identityUser.PasswordConfig; } if (member.SecurityStamp != identityUser.SecurityStamp) { changeType = MemberDataChangeType.FullSave; member.SecurityStamp = identityUser.SecurityStamp; } if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.Roles))) { changeType = MemberDataChangeType.FullSave; var identityUserRoles = identityUser.Roles.Select(x => x.RoleId).ToArray(); _memberService.ReplaceRoles(new[] { member.Id }, identityUserRoles); } // reset all changes identityUser.ResetDirtyProperties(false); return changeType; } public IPublishedContent GetPublishedMember(MemberIdentityUser user) { if (user == null) { return null; } IMember member = _memberService.GetByKey(user.Key); if (member == null) { return null; } var publishedSnapshot = _publishedSnapshotAccessor.GetRequiredPublishedSnapshot(); return publishedSnapshot.Members.Get(member); } private enum MemberDataChangeType { None, LoginOnly, FullSave } /// <summary> /// Overridden to support Umbraco's own data storage requirements /// </summary> /// <remarks> /// The base class's implementation of this calls into FindTokenAsync, RemoveUserTokenAsync and AddUserTokenAsync, both methods will only work with ORMs that are change /// tracking ORMs like EFCore. /// </remarks> /// <inheritdoc /> public override Task<string> GetTokenAsync(MemberIdentityUser user, string loginProvider, string name, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } IIdentityUserToken token = user.LoginTokens.FirstOrDefault(x => x.LoginProvider.InvariantEquals(loginProvider) && x.Name.InvariantEquals(name)); return Task.FromResult(token?.Value); } /// <inheritdoc /> public override async Task<bool> GetTwoFactorEnabledAsync(MemberIdentityUser user, CancellationToken cancellationToken = default(CancellationToken)) { return await _twoFactorLoginService.IsTwoFactorEnabledAsync(user.Key); } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public class ScalarTypeRepresentation : ValueTypeRepresentation { // // Constructor Methods // public ScalarTypeRepresentation( AssemblyRepresentation owner , BuiltInTypes builtinType , Attributes flags , GenericContext genericContext , uint size ) : base( owner, builtinType, flags, genericContext ) { this.Size = size; } //--// // // Helper Methods // public Type ConvertToRuntimeType() { switch(m_builtinType) { case TypeRepresentation.BuiltInTypes.VOID : return typeof(void ); case TypeRepresentation.BuiltInTypes.BOOLEAN: return typeof(System.Boolean); case TypeRepresentation.BuiltInTypes.CHAR : return typeof(System.Char ); case TypeRepresentation.BuiltInTypes.I1 : return typeof(System.SByte ); case TypeRepresentation.BuiltInTypes.U1 : return typeof(System.Byte ); case TypeRepresentation.BuiltInTypes.I2 : return typeof(System.Int16 ); case TypeRepresentation.BuiltInTypes.U2 : return typeof(System.UInt16 ); case TypeRepresentation.BuiltInTypes.I4 : return typeof(System.Int32 ); case TypeRepresentation.BuiltInTypes.U4 : return typeof(System.UInt32 ); case TypeRepresentation.BuiltInTypes.I8 : return typeof(System.Int64 ); case TypeRepresentation.BuiltInTypes.U8 : return typeof(System.UInt64 ); case TypeRepresentation.BuiltInTypes.R4 : return typeof(System.Single ); case TypeRepresentation.BuiltInTypes.R8 : return typeof(System.Double ); case TypeRepresentation.BuiltInTypes.I : return typeof(System.IntPtr ); case TypeRepresentation.BuiltInTypes.U : return typeof(System.UIntPtr); } return null; } //--// public override GCInfo.Kind ClassifyAsPointer() { switch(m_builtinType) { case BuiltInTypes.I: case BuiltInTypes.U: return GCInfo.Kind.Potential; default: return GCInfo.Kind.NotAPointer; } } //--// protected override void SetShapeCategory( TypeSystem typeSystem ) { m_vTable.ShapeCategory = VTable.Shape.Scalar; } //--// protected override TypeRepresentation AllocateInstantiation( InstantiationContext ic ) { return this; } //--// internal override void InvalidateLayout() { // A scalar has always a valid layout. } //--// // // Access Methods // public override uint SizeOfHoldingVariable { get { return this.Size; } } public override bool CanPointToMemory { get { switch(m_builtinType) { case BuiltInTypes.I: case BuiltInTypes.U: return true; } return false; } } public override bool IsNumeric { get { return true; } } public override bool IsSigned { get { switch(m_builtinType) { case BuiltInTypes.I1: case BuiltInTypes.I2: case BuiltInTypes.I4: case BuiltInTypes.I8: case BuiltInTypes.R4: case BuiltInTypes.R8: case BuiltInTypes.I : return true; } return false; } } public override bool IsInteger { get { switch(m_builtinType) { case BuiltInTypes.BOOLEAN: case BuiltInTypes.CHAR : case BuiltInTypes.I1 : case BuiltInTypes.U1 : case BuiltInTypes.I2 : case BuiltInTypes.U2 : case BuiltInTypes.I4 : case BuiltInTypes.U4 : case BuiltInTypes.I8 : case BuiltInTypes.U8 : case BuiltInTypes.I : case BuiltInTypes.U : return true; } return false; } } public override bool IsFloatingPoint { get { switch(m_builtinType) { case BuiltInTypes.R4: case BuiltInTypes.R8: return true; } return false; } } //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "ScalarTypeRepresentation(" ); PrettyToString( sb, true, false ); sb.Append( ")" ); return sb.ToString(); } } }
#region license // Sqloogle // Copyright 2013-2017 Dale Newman // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using Sqloogle.Libs.DBDiff.Schema.Attributes; using Sqloogle.Libs.DBDiff.Schema.Model; namespace Sqloogle.Libs.DBDiff.Schema.SqlServer2005.Model { public class Table : SQLServerSchemaBase, IComparable<Table>, ITable<Table> { private Columns<Table> columns; private int dependenciesCount; private List<ISchemaBase> dependencis; private Boolean? hasFileStream; public Table(ISchemaBase parent) : base(parent, Enums.ObjectType.Table) { dependenciesCount = -1; columns = new Columns<Table>(this); Constraints = new SchemaList<Constraint, Table>(this, ((Database) parent).AllObjects); Options = new SchemaList<TableOption, Table>(this); Triggers = new SchemaList<Trigger, Table>(this, ((Database) parent).AllObjects); CLRTriggers = new SchemaList<CLRTrigger, Table>(this, ((Database) parent).AllObjects); Indexes = new SchemaList<Index, Table>(this, ((Database) parent).AllObjects); Partitions = new SchemaList<TablePartition, Table>(this, ((Database) parent).AllObjects); FullTextIndex = new SchemaList<FullTextIndex, Table>(this); } public string CompressType { get; set; } public string FileGroupText { get; set; } public Boolean HasChangeDataCapture { get; set; } public Boolean HasChangeTrackingTrackColumn { get; set; } public Boolean HasChangeTracking { get; set; } public string FileGroupStream { get; set; } public Boolean HasClusteredIndex { get; set; } public string FileGroup { get; set; } public Table OriginalTable { get; set; } [ShowItem("Constraints")] public SchemaList<Constraint, Table> Constraints { get; private set; } [ShowItem("Indexes", "Index")] public SchemaList<Index, Table> Indexes { get; private set; } [ShowItem("CLR Triggers")] public SchemaList<CLRTrigger, Table> CLRTriggers { get; private set; } [ShowItem("Triggers")] public SchemaList<Trigger, Table> Triggers { get; private set; } public SchemaList<FullTextIndex, Table> FullTextIndex { get; private set; } public SchemaList<TablePartition, Table> Partitions { get; set; } public SchemaList<TableOption, Table> Options { get; set; } /// <summary> /// Indica si la tabla tiene alguna columna que sea Identity. /// </summary> public Boolean HasIdentityColumn { get { foreach (Column col in Columns) { if (col.IsIdentity) return true; } return false; } } public Boolean HasFileStream { get { if (hasFileStream == null) { hasFileStream = false; foreach (Column col in Columns) { if (col.IsFileStream) hasFileStream = true; } } return hasFileStream.Value; } } public Boolean HasBlobColumn { get { foreach (Column col in Columns) { if (col.IsBLOB) return true; } return false; } } /// <summary> /// Indica la cantidad de Constraints dependientes de otra tabla (FK) que tiene /// la tabla. /// </summary> public override int DependenciesCount { get { if (dependenciesCount == -1) dependenciesCount = ((Database) Parent).Dependencies.DependenciesCount(Id, Enums.ObjectType.Constraint); return dependenciesCount; } } #region IComparable<Table> Members /// <summary> /// Compara en primer orden por la operacion /// (Primero van los Drops, luego los Create y finalesmente los Alter). /// Si la operacion es la misma, ordena por cantidad de tablas dependientes. /// </summary> public int CompareTo(Table other) { if (other == null) throw new ArgumentNullException("other"); if (Status == other.Status) return DependenciesCount.CompareTo(other.DependenciesCount); return other.Status.CompareTo(Status); } #endregion #region ITable<Table> Members /// <summary> /// Coleccion de campos de la tabla. /// </summary> [ShowItem("Columns", "Column")] public Columns<Table> Columns { get { return columns; } set { columns = value; } } #endregion /// <summary> /// Clona el objeto Table en una nueva instancia. /// </summary> public override ISchemaBase Clone(ISchemaBase objectParent) { var table = new Table(objectParent) { Owner = Owner, Name = Name, Id = Id, Guid = Guid, Status = Status, FileGroup = FileGroup, FileGroupText = FileGroupText, FileGroupStream = FileGroupStream, HasClusteredIndex = HasClusteredIndex, HasChangeTracking = HasChangeTracking, HasChangeTrackingTrackColumn = HasChangeTrackingTrackColumn, HasChangeDataCapture = HasChangeDataCapture, dependenciesCount = DependenciesCount }; table.Columns = Columns.Clone(table); table.Options = Options.Clone(table); table.CompressType = CompressType; table.Triggers = Triggers.Clone(table); table.Indexes = Indexes.Clone(table); table.Partitions = Partitions.Clone(table); return table; } public override string ToSql() { return ToSql(true); } /// <summary> /// Devuelve el schema de la tabla en formato SQL. /// </summary> public string ToSql(Boolean showFK) { Database database = null; ISchemaBase current = this; while (database == null && current.Parent != null) { database = current.Parent as Database; current = current.Parent; } var isAzure10 = database.Info.Version == DatabaseInfo.VersionTypeEnum.SQLServerAzure10; string sql = ""; string sqlPK = ""; string sqlUC = ""; string sqlFK = ""; if (columns.Count > 0) { sql += "CREATE TABLE " + FullName + "\r\n(\r\n"; sql += columns.ToSql(); if (Constraints.Count > 0) { sql += ",\r\n"; Constraints.ForEach(item => { if (item.Type == Constraint.ConstraintType.PrimaryKey) sqlPK += "\t" + item.ToSql() + ",\r\n"; if (item.Type == Constraint.ConstraintType.Unique) sqlUC += "\t" + item.ToSql() + ",\r\n"; if (showFK) if (item.Type == Constraint.ConstraintType.ForeignKey) sqlFK += "\t" + item.ToSql() + ",\r\n"; }); sql += sqlPK + sqlUC + sqlFK; sql = sql.Substring(0, sql.Length - 3) + "\r\n"; } else { sql += "\r\n"; if (!String.IsNullOrEmpty(CompressType)) sql += "WITH (DATA_COMPRESSION = " + CompressType + ")\r\n"; } sql += ")"; if (!isAzure10) { if (!String.IsNullOrEmpty(FileGroup)) sql += " ON [" + FileGroup + "]"; if (!String.IsNullOrEmpty(FileGroupText)) { if (HasBlobColumn) sql += " TEXTIMAGE_ON [" + FileGroupText + "]"; } if ((!String.IsNullOrEmpty(FileGroupStream)) && (HasFileStream)) sql += " FILESTREAM_ON [" + FileGroupStream + "]"; } sql += "\r\n"; sql += "GO\r\n"; Constraints.ForEach(item => { if (item.Type == Constraint.ConstraintType.Check) sql += item.ToSqlAdd() + "\r\n"; }); if (HasChangeTracking) sql += ToSqlChangeTracking(); sql += Indexes.ToSql(); sql += FullTextIndex.ToSql(); sql += Options.ToSql(); sql += Triggers.ToSql(); } return sql; } private string ToSqlChangeTracking() { string sql; if (HasChangeTracking) { sql = "ALTER TABLE " + FullName + " ENABLE CHANGE_TRACKING"; if (HasChangeTrackingTrackColumn) sql += " WITH(TRACK_COLUMNS_UPDATED = ON)"; } else sql = "ALTER TABLE " + FullName + " DISABLE CHANGE_TRACKING"; return sql + "\r\nGO\r\n"; } public override string ToSqlAdd() { return ToSql(); } public override string ToSqlDrop() { return "DROP TABLE " + FullName + "\r\nGO\r\n"; } /* private SQLScriptList BuildSQLFileGroup() { var listDiff = new SQLScriptList(); Boolean found = false; Index clustered = Indexes.Find(item => item.Type == Index.IndexTypeEnum.Clustered); if (clustered == null) { foreach (Constraint cons in Constraints) { if (cons.Index.Type == Index.IndexTypeEnum.Clustered) { listDiff.Add(cons.ToSqlDrop(FileGroup), dependenciesCount, Enums.ScripActionType.DropConstraint); listDiff.Add(cons.ToSqlAdd(), dependenciesCount, Enums.ScripActionType.AddConstraint); found = true; } } if (!found) { Status = Enums.ObjectStatusType.RebuildStatus; listDiff = ToSqlDiff(); } } else { listDiff.Add(clustered.ToSqlDrop(FileGroup), dependenciesCount, Enums.ScripActionType.DropIndex); listDiff.Add(clustered.ToSqlAdd(), dependenciesCount, Enums.ScripActionType.AddIndex); } return listDiff; } */ /// <summary> /// Devuelve el schema de diferencias de la tabla en formato SQL. /// </summary> public override SQLScriptList ToSqlDiff() { var listDiff = new SQLScriptList(); if (Status != Enums.ObjectStatusType.OriginalStatus) { if (((Database) Parent).Options.Ignore.FilterTable) RootParent.ActionMessage.Add(this); } if (Status == Enums.ObjectStatusType.DropStatus) { if (((Database) Parent).Options.Ignore.FilterTable) { listDiff.Add(ToSqlDrop(), dependenciesCount, Enums.ScripActionType.DropTable); listDiff.AddRange(ToSQLDropFKBelow()); } } if (Status == Enums.ObjectStatusType.CreateStatus) { string sql = ""; Constraints.ForEach(item => { if (item.Type == Constraint.ConstraintType.ForeignKey) sql += item.ToSqlAdd() + "\r\n"; }); listDiff.Add(ToSql(false), dependenciesCount, Enums.ScripActionType.AddTable); listDiff.Add(sql, dependenciesCount, Enums.ScripActionType.AddConstraintFK); } if (HasState(Enums.ObjectStatusType.RebuildDependenciesStatus)) { GenerateDependencis(); listDiff.AddRange(ToSQLDropDependencis()); listDiff.AddRange(columns.ToSqlDiff()); listDiff.AddRange(ToSQLCreateDependencis()); listDiff.AddRange(Constraints.ToSqlDiff()); listDiff.AddRange(Indexes.ToSqlDiff()); listDiff.AddRange(Options.ToSqlDiff()); listDiff.AddRange(Triggers.ToSqlDiff()); listDiff.AddRange(CLRTriggers.ToSqlDiff()); listDiff.AddRange(FullTextIndex.ToSqlDiff()); } if (HasState(Enums.ObjectStatusType.AlterStatus)) { listDiff.AddRange(columns.ToSqlDiff()); listDiff.AddRange(Constraints.ToSqlDiff()); listDiff.AddRange(Indexes.ToSqlDiff()); listDiff.AddRange(Options.ToSqlDiff()); listDiff.AddRange(Triggers.ToSqlDiff()); listDiff.AddRange(CLRTriggers.ToSqlDiff()); listDiff.AddRange(FullTextIndex.ToSqlDiff()); } if (HasState(Enums.ObjectStatusType.RebuildStatus)) { GenerateDependencis(); listDiff.AddRange(ToSQLRebuild()); listDiff.AddRange(columns.ToSqlDiff()); listDiff.AddRange(Constraints.ToSqlDiff()); listDiff.AddRange(Indexes.ToSqlDiff()); listDiff.AddRange(Options.ToSqlDiff()); //Como recrea la tabla, solo pone los nuevos triggers, por eso va ToSQL y no ToSQLDiff listDiff.Add(Triggers.ToSql(), dependenciesCount, Enums.ScripActionType.AddTrigger); listDiff.Add(CLRTriggers.ToSql(), dependenciesCount, Enums.ScripActionType.AddTrigger); listDiff.AddRange(FullTextIndex.ToSqlDiff()); } if (HasState(Enums.ObjectStatusType.DisabledStatus)) { listDiff.Add(ToSqlChangeTracking(), 0, Enums.ScripActionType.AlterTableChangeTracking); } return listDiff; } private string ToSQLTableRebuild() { string sql = ""; string tempTable = "Temp" + Name; string listColumns = ""; string listValues = ""; Boolean IsIdentityNew = false; foreach (Column column in Columns) { if ((column.Status != Enums.ObjectStatusType.DropStatus) && !((column.Status == Enums.ObjectStatusType.CreateStatus) && column.IsNullable)) { if ((!column.IsComputed) && (!column.Type.ToLower().Equals("timestamp"))) { /*Si la nueva columna a agregar es XML, no se inserta ese campo y debe ir a la coleccion de Warnings*/ /*Si la nueva columna a agregar es Identity, tampoco se debe insertar explicitamente*/ if ( !((column.Status == Enums.ObjectStatusType.CreateStatus) && ((column.Type.ToLower().Equals("xml") || (column.IsIdentity))))) { listColumns += "[" + column.Name + "],"; if (column.HasToForceValue) { if (column.HasState(Enums.ObjectStatusType.UpdateStatus)) listValues += "ISNULL([" + column.Name + "]," + column.DefaultForceValue + "),"; else listValues += column.DefaultForceValue + ","; } else listValues += "[" + column.Name + "],"; } else { if (column.IsIdentity) IsIdentityNew = true; } } } } if (!String.IsNullOrEmpty(listColumns)) { listColumns = listColumns.Substring(0, listColumns.Length - 1); listValues = listValues.Substring(0, listValues.Length - 1); sql += ToSQLTemp(tempTable) + "\r\n"; if ((HasIdentityColumn) && (!IsIdentityNew)) sql += "SET IDENTITY_INSERT [" + Owner + "].[" + tempTable + "] ON\r\n"; sql += "INSERT INTO [" + Owner + "].[" + tempTable + "] (" + listColumns + ")" + " SELECT " + listValues + " FROM " + FullName + "\r\n"; if ((HasIdentityColumn) && (!IsIdentityNew)) sql += "SET IDENTITY_INSERT [" + Owner + "].[" + tempTable + "] OFF\r\nGO\r\n\r\n"; sql += "DROP TABLE " + FullName + "\r\nGO\r\n"; if (HasFileStream) { Constraints.ForEach(item => { if ((item.Type == Constraint.ConstraintType.Unique) && (item.Status != Enums.ObjectStatusType.DropStatus)) { sql += "EXEC sp_rename N'[" + Owner + "].[Temp_XX_" + item.Name + "]',N'" + item.Name + "', 'OBJECT'\r\nGO\r\n"; } }); } sql += "EXEC sp_rename N'[" + Owner + "].[" + tempTable + "]',N'" + Name + "', 'OBJECT'\r\nGO\r\n\r\n"; sql += OriginalTable.Options.ToSql(); } else sql = ""; return sql; } private SQLScriptList ToSQLRebuild() { var listDiff = new SQLScriptList(); listDiff.AddRange(ToSQLDropDependencis()); listDiff.Add(ToSQLTableRebuild(), dependenciesCount, Enums.ScripActionType.RebuildTable); listDiff.AddRange(ToSQLCreateDependencis()); return listDiff; } private string ToSQLTemp(String TableName) { string sql = ""; sql += "CREATE TABLE [" + Owner + "].[" + TableName + "]\r\n(\r\n"; Columns.Sort(); for (int index = 0; index < Columns.Count; index++) { if (Columns[index].Status != Enums.ObjectStatusType.DropStatus) { sql += "\t" + Columns[index].ToSql(true); if (index != Columns.Count - 1) sql += ","; sql += "\r\n"; } } if (HasFileStream) { sql = sql.Substring(0, sql.Length - 2); sql += ",\r\n"; Constraints.ForEach(item => { if ((item.Type == Constraint.ConstraintType.Unique) && (item.Status != Enums.ObjectStatusType.DropStatus)) { item.Name = "Temp_XX_" + item.Name; sql += "\t" + item.ToSql() + ",\r\n"; item.SetWasInsertInDiffList(Enums.ScripActionType.AddConstraint); item.Name = item.Name.Substring(8, item.Name.Length - 8); } }); sql = sql.Substring(0, sql.Length - 3) + "\r\n"; } else { sql += "\r\n"; if (!String.IsNullOrEmpty(CompressType)) sql += "WITH (DATA_COMPRESSION = " + CompressType + ")\r\n"; } sql += ")"; if (!String.IsNullOrEmpty(FileGroup)) sql += " ON [" + FileGroup + "]"; if (!String.IsNullOrEmpty(FileGroupText)) { if (HasBlobColumn) sql += " TEXTIMAGE_ON [" + FileGroupText + "]"; } if ((!String.IsNullOrEmpty(FileGroupStream)) && (HasFileStream)) sql += " FILESTREAM_ON [" + FileGroupStream + "]"; sql += "\r\n"; sql += "GO\r\n"; return sql; } private void GenerateDependencis() { List<ISchemaBase> myDependencis; /*Si el estado es AlterRebuildDependeciesStatus, busca las dependencias solamente en las columnas que fueron modificadas*/ if (Status == Enums.ObjectStatusType.RebuildDependenciesStatus) { myDependencis = new List<ISchemaBase>(); for (int ic = 0; ic < Columns.Count; ic++) { if ((Columns[ic].Status == Enums.ObjectStatusType.RebuildDependenciesStatus) || (Columns[ic].Status == Enums.ObjectStatusType.AlterStatus)) myDependencis.AddRange(((Database) Parent).Dependencies.Find(Id, 0, Columns[ic].DataUserTypeId)); } /*Si no encuentra ninguna, toma todas las de la tabla*/ if (myDependencis.Count == 0) myDependencis.AddRange(((Database) Parent).Dependencies.Find(Id)); } else myDependencis = ((Database) Parent).Dependencies.Find(Id); dependencis = new List<ISchemaBase>(); for (int j = 0; j < myDependencis.Count; j++) { ISchemaBase item = null; if (myDependencis[j].ObjectType == Enums.ObjectType.Index) item = Indexes[myDependencis[j].FullName]; if (myDependencis[j].ObjectType == Enums.ObjectType.Constraint) item = ((Database) Parent).Tables[myDependencis[j].Parent.FullName].Constraints[ myDependencis[j].FullName]; if (myDependencis[j].ObjectType == Enums.ObjectType.Default) item = columns[myDependencis[j].FullName].DefaultConstraint; if (myDependencis[j].ObjectType == Enums.ObjectType.View) item = ((Database) Parent).Views[myDependencis[j].FullName]; if (myDependencis[j].ObjectType == Enums.ObjectType.Function) item = ((Database) Parent).Functions[myDependencis[j].FullName]; if (item != null) dependencis.Add(item); } } /// <summary> /// Genera una lista de FK que deben ser eliminadas previamente a la eliminacion de la tablas. /// Esto pasa porque para poder eliminar una tabla, hay que eliminar antes todas las constraints asociadas. /// </summary> private SQLScriptList ToSQLDropFKBelow() { var listDiff = new SQLScriptList(); Constraints.ForEach(constraint => { if ((constraint.Type == Constraint.ConstraintType.ForeignKey) && (((Table) constraint.Parent).DependenciesCount <= DependenciesCount)) { /*Si la FK pertenece a la misma tabla, no se debe explicitar el DROP CONSTRAINT antes de hacer el DROP TABLE*/ if (constraint.Parent.Id != constraint.RelationalTableId) { listDiff.Add(constraint.Drop()); } } }); return listDiff; } /// <summary> /// Genera una lista de script de DROPS de todas los constraints dependientes de la tabla. /// Se usa cuando se quiere reconstruir una tabla y todos sus objectos dependientes. /// </summary> private SQLScriptList ToSQLDropDependencis() { bool addDependencie = true; var listDiff = new SQLScriptList(); //Se buscan todas las table constraints. for (int index = 0; index < dependencis.Count; index++) { if ((dependencis[index].Status == Enums.ObjectStatusType.OriginalStatus) || (dependencis[index].Status == Enums.ObjectStatusType.DropStatus)) { addDependencie = true; if (dependencis[index].ObjectType == Enums.ObjectType.Constraint) { if ((((Constraint) dependencis[index]).Type == Constraint.ConstraintType.Unique) && ((HasFileStream) || (OriginalTable.HasFileStream))) addDependencie = false; if ((((Constraint) dependencis[index]).Type != Constraint.ConstraintType.ForeignKey) && (dependencis[index].Status == Enums.ObjectStatusType.DropStatus)) addDependencie = false; } if (addDependencie) listDiff.Add(dependencis[index].Drop()); } } //Se buscan todas las columns constraints. columns.ForEach(column => { if (column.DefaultConstraint != null) { if (((column.DefaultConstraint.Status == Enums.ObjectStatusType.OriginalStatus) || (column.DefaultConstraint.Status == Enums.ObjectStatusType.DropStatus) || (column.DefaultConstraint.Status == Enums.ObjectStatusType.AlterStatus)) && (column.Status != Enums.ObjectStatusType.CreateStatus)) listDiff.Add(column.DefaultConstraint.Drop()); } }); return listDiff; } private SQLScriptList ToSQLCreateDependencis() { bool addDependencie = true; var listDiff = new SQLScriptList(); //Las constraints de deben recorrer en el orden inverso. for (int index = dependencis.Count - 1; index >= 0; index--) { if ((dependencis[index].Status == Enums.ObjectStatusType.OriginalStatus) && (dependencis[index].Parent.Status != Enums.ObjectStatusType.DropStatus)) { addDependencie = true; if (dependencis[index].ObjectType == Enums.ObjectType.Constraint) { if ((((Constraint) dependencis[index]).Type == Constraint.ConstraintType.Unique) && (HasFileStream)) addDependencie = false; } if (addDependencie) listDiff.Add(dependencis[index].Create()); } } //Se buscan todas las columns constraints. for (int index = columns.Count - 1; index >= 0; index--) { if (columns[index].DefaultConstraint != null) { if ((columns[index].DefaultConstraint.CanCreate) && (columns.Parent.Status != Enums.ObjectStatusType.RebuildStatus)) listDiff.Add(columns[index].DefaultConstraint.Create()); } } return listDiff; } /// <summary> /// Compara dos tablas y devuelve true si son iguales, caso contrario, devuelve false. /// </summary> public static Boolean CompareFileGroup(Table origen, Table destino) { if (destino == null) throw new ArgumentNullException("destino"); if (origen == null) throw new ArgumentNullException("origen"); if ((!String.IsNullOrEmpty(destino.FileGroup) && (!String.IsNullOrEmpty(origen.FileGroup)))) if (!destino.FileGroup.Equals(origen.FileGroup)) return false; return true; } /// <summary> /// Compara dos tablas y devuelve true si son iguales, caso contrario, devuelve false. /// </summary> public static Boolean CompareFileGroupText(Table origen, Table destino) { if (destino == null) throw new ArgumentNullException("destino"); if (origen == null) throw new ArgumentNullException("origen"); if ((!String.IsNullOrEmpty(destino.FileGroupText) && (!String.IsNullOrEmpty(origen.FileGroupText)))) if (!destino.FileGroupText.Equals(origen.FileGroupText)) return false; return true; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Internal.Resources { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// Azure resources can be locked to prevent other users in your /// organization from deleting or modifying resources. /// </summary> public partial class ManagementLockClient : ServiceClient<ManagementLockClient>, IManagementLockClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Gets Azure subscription credentials. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// The ID of the target subscription. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// The API version to use for the operation. /// </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 IManagementLocksOperations. /// </summary> public virtual IManagementLocksOperations ManagementLocks { get; private set; } /// <summary> /// Initializes a new instance of the ManagementLockClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected ManagementLockClient(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the ManagementLockClient 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 ManagementLockClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the ManagementLockClient 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> protected ManagementLockClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the ManagementLockClient 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> protected ManagementLockClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the ManagementLockClient class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public ManagementLockClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the ManagementLockClient class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </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> public ManagementLockClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the ManagementLockClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public ManagementLockClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the ManagementLockClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </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> public ManagementLockClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.ManagementLocks = new ManagementLocksOperations(this); this.BaseUri = new Uri("https://management.azure.com"); this.ApiVersion = "2016-09-01"; this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
/************************************************************************* * Vortex OpenSplice * * This software and documentation are Copyright 2006 to TO_YEAR ADLINK * Technology Limited, its affiliated companies and licensors. 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. * */ /************************************************************************ * LOGICAL_NAME: WaitSetSubscriber.cs * FUNCTION: OpenSplice Tutorial example code. * MODULE: Tutorial for the C# programming language. * DATE September 2010. ************************************************************************ * * This file contains the implementation for the 'WaitSetSubscriber' executable. * ***/ using System; using System.Threading; using System.IO; using DDS; using DDS.OpenSplice; using WaitSetData; using DDSAPIHelper; namespace WaitSetSubscriber { class WaitSetSubscriber { static void Main(string[] args) { DDSEntityManager mgr = new DDSEntityManager("WaitSet"); String partitionName = "WaitSet example"; // create Domain Participant mgr.createParticipant(partitionName); // create Type MsgTypeSupport msgTS = new MsgTypeSupport(); mgr.registerType(msgTS); // create Topic mgr.createTopic("WaitSetData_Msg"); // create Subscriber mgr.createSubscriber(); // create DataReader mgr.createReader(false); // Read Events IDataReader dreader = mgr.getReader(); MsgDataReader WaitSetReader = dreader as MsgDataReader; // Create a WaitSet WaitSet w = new WaitSet(); // Create a ReadCondition IReadCondition readCond = WaitSetReader.CreateReadCondition(SampleStateKind.NotRead, ViewStateKind.New, InstanceStateKind.Alive); ErrorHandler.checkHandle(readCond, "DataReader.CreateReadCondition"); // Create a QueryCondition String[] queryStr = { "Hello again" }; Console.WriteLine("=== [WaitSetDataSubscriber] Query : message = \"Hello again"); IQueryCondition queryCond = WaitSetReader.CreateQueryCondition("message=%0", queryStr); ErrorHandler.checkHandle(queryCond, "DataReader.CreateQueryCondition"); // Obtain a StatusCondition IStatusCondition statusCond; statusCond = dreader.StatusCondition; statusCond.SetEnabledStatuses(StatusKind.LivelinessChanged); ErrorHandler.checkHandle(statusCond, "DataReader.StatusCondition"); GuardCondition escape; escape = new GuardCondition(); ReturnCode result; result = w.AttachCondition(statusCond); ErrorHandler.checkStatus(result, "WaitSet.AttachCondition (status)"); result = w.AttachCondition(readCond); ErrorHandler.checkStatus(result, "WaitSet.AttachCondition (read)"); result = w.AttachCondition(queryCond); ErrorHandler.checkStatus(result, "WaitSet.AttachCondition (query)"); result = w.AttachCondition(escape); ErrorHandler.checkStatus(result, "WaitSet.AttachCondition (guard)"); /* Initialize and pre-allocate the GuardList used to obtain the triggered Conditions. */ ICondition[] guardList = new ICondition[4]; DDS.SampleInfo[] infoSeq = null; Msg[] msgSeq = null; bool escaped = false; int prevCount = 0; int count = 0; Console.WriteLine("=== [WaitSetDataSubscriber] Ready ..."); while (!escaped && count < 20 ) { /** * Wait until data will be available */ Duration wait_timeout = new Duration(Duration.InfiniteSec, Duration.InfiniteNanoSec); result = w.Wait(ref guardList, wait_timeout); ErrorHandler.checkStatus(result, "WaitSet.Wait"); /* Walk over all guards to display information */ foreach (ICondition guard in guardList) { if (guard == readCond) { result = WaitSetReader.ReadWithCondition(ref msgSeq, ref infoSeq, Length.Unlimited, readCond); ErrorHandler.checkStatus(result, "WaitSetReader.ReadWithCondition"); foreach (Msg msg in msgSeq) { Console.WriteLine(" --- New message received --- "); Console.WriteLine(" userID : {0}", msg.userID); Console.WriteLine(" Message : \"{0}", msg.message); } result = WaitSetReader.ReturnLoan(ref msgSeq, ref infoSeq); ErrorHandler.checkStatus(result, "WaitSet.ReturnLoan"); } else if (guard == queryCond) { result = WaitSetReader.TakeWithCondition(ref msgSeq, ref infoSeq, Length.Unlimited, queryCond); ErrorHandler.checkStatus(result, "WaitSetReader.TakeWithCondition"); foreach (Msg msg in msgSeq) { Console.WriteLine(" --- New message received with QueryCondition --- "); Console.WriteLine(" userID : {0}", msg.userID); Console.WriteLine(" Message : \" {0}", msg.message); } result = WaitSetReader.ReturnLoan(ref msgSeq, ref infoSeq); ErrorHandler.checkStatus(result, "WaitSet.ReturnLoan"); } else if (guard == statusCond) { LivelinessChangedStatus livelinessStatus = new LivelinessChangedStatus(); result = WaitSetReader.GetLivelinessChangedStatus(ref livelinessStatus); ErrorHandler.checkStatus(result, "DataReader.getLivelinessChangedStatus"); if (livelinessStatus.AliveCount < prevCount) { Console.WriteLine("!!! A WaitSetDataWriter lost its liveliness"); Console.WriteLine("Triggering escape condition."); ReturnCode status = escape.SetTriggerValue(true); } else { Console.WriteLine("!!! A WaitSetDataWriter joined"); } prevCount = livelinessStatus.AliveCount; } else if (guard == escape) { Console.WriteLine("WaitSetSubscriber has terminated."); escaped = true; ReturnCode status = escape.SetTriggerValue(false); } else { // Unknown Condition } } ++count; } // Detach all Conditions from the WaitSet result = w.DetachCondition(escape); ErrorHandler.checkStatus(result, "WaitSet.DetachCondition (escape)"); result = w.DetachCondition(readCond); ErrorHandler.checkStatus(result, "WaitSet.DetachCondition (readCond)"); result = w.DetachCondition(queryCond); ErrorHandler.checkStatus(result, "WaitSet.DetachCondition (queryCond)"); result = w.DetachCondition(statusCond); ErrorHandler.checkStatus(result, "WaitSet.DetachCondition (statusCond)"); Console.WriteLine("=== [Subscriber] Closed"); // clean up WaitSetReader.DeleteReadCondition(readCond); WaitSetReader.DeleteReadCondition(queryCond); mgr.getSubscriber().DeleteDataReader(WaitSetReader); mgr.deleteSubscriber(); mgr.deleteTopic(); mgr.deleteParticipant(); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace docdbwebservice.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
#pragma warning disable 1591 using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Text; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; namespace AjaxControlToolkit { // 1) It performs the hookup between an Extender (server) control and the behavior it instantiates // 2) It manages interacting with the ScriptManager to get the right scripts loaded // 3) It adds some debugging features like ValidationScript and ScriptPath [Themeable(true)] [ClientScriptResource(null, Constants.BaseScriptName)] public abstract class ExtenderControlBase : ExtenderControl, IControlResolver { private Dictionary<string, Control> _findControlHelperCache = new Dictionary<string, Control>(); private string _clientState; private bool _enableClientState; private bool _loadedClientStateValues; // Called when the ExtenderControlBase fails to locate a control referenced by a TargetControlID. // In this event, user code is given an opportunity to find the control. public event ResolveControlEventHandler ResolveControlID; [DefaultValue(true)] public bool Enabled { get { return GetPropertyValue("Enabled", true); } set { SetPropertyValue("Enabled", value); } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string ClientState { get { return _clientState; } set { _clientState = value; } } [ExtenderControlProperty()] [ClientPropertyName("id")] public string BehaviorID { get { string id = GetPropertyValue("BehaviorID", ""); return (string.IsNullOrEmpty(id) ? ClientID : id); } set { SetPropertyValue("BehaviorID", value); } } private string GetClientStateFieldID() { return string.Format(CultureInfo.InvariantCulture, "{0}_ClientState", ID); } // On Init we load target properties values and process data-binding handlers. protected override void OnInit(EventArgs e) { if(EnableClientState) { CreateClientStateField(); } Page.PreLoad += new EventHandler(Page_PreLoad); base.OnInit(e); } void Page_PreLoad(object sender, EventArgs e) { // Needs to happen sometime after ASP.NET populates the control // values from the postback but sometime before Load so that // the values will be available to controls then. PreLoad is // therefore the obvious choice. LoadClientStateValues(); } private HiddenField CreateClientStateField() { // add a hidden field so we'll pick up the value HiddenField field = new HiddenField(); field.ID = GetClientStateFieldID(); Controls.Add(field); ClientStateFieldID = field.ID; return field; } // Loads the values for each of the TargetProperties classes coming back from a postback. private void LoadClientStateValues() { if(EnableClientState && !string.IsNullOrEmpty(ClientStateFieldID)) { HiddenField hiddenField = (HiddenField)NamingContainer.FindControl(ClientStateFieldID); if((hiddenField != null) && !string.IsNullOrEmpty(hiddenField.Value)) { ClientState = hiddenField.Value; } } if(null != ClientStateValuesLoaded) { ClientStateValuesLoaded(this, EventArgs.Empty); } _loadedClientStateValues = true; } protected event EventHandler ClientStateValuesLoaded; // Save any values in the TargetProperties objects out to client state so they are available // on the client side. private void SaveClientStateValues() { if(EnableClientState) { HiddenField hiddenField = null; // if we don't have a value here, this properties // object may have been created dynamically in code // so we create the field on demand. // if(string.IsNullOrEmpty(ClientStateFieldID)) { hiddenField = CreateClientStateField(); } else { hiddenField = (HiddenField)NamingContainer.FindControl(ClientStateFieldID); } if(hiddenField != null) { hiddenField.Value = ClientState; } } } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [ExtenderControlProperty()] [IDReferenceProperty(typeof(HiddenField))] [DefaultValue("")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string ClientStateFieldID { get { return GetPropertyValue("ClientStateFieldID", ""); } set { SetPropertyValue("ClientStateFieldID", value); } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool EnableClientState { get { return _enableClientState; } set { _enableClientState = value; } } // The type of the client component - e.g. "ConfirmButtonBehavior" protected virtual string ClientControlType { get { ClientScriptResourceAttribute attr = (ClientScriptResourceAttribute)TypeDescriptor.GetAttributes(this)[typeof(ClientScriptResourceAttribute)]; return attr.ComponentType; } } public Control ResolveControl(string controlId) { return FindControl(controlId); } public override Control FindControl(string id) { // Use FindControlHelper so that more complete searching and OnResolveControlID will be used return FindControlHelper(id); } protected Control TargetControl { get { return FindControlHelper(TargetControlID); } } // This helper automates locating a control by ID. // It calls FindControl on the NamingContainer, then the Page. If that fails, it fires the resolve event. protected Control FindControlHelper(string id) { Control c = null; if(_findControlHelperCache.ContainsKey(id)) { c = _findControlHelperCache[id]; } else { c = base.FindControl(id); // Use "base." to avoid calling self in an infinite loop Control nc = NamingContainer; while((null == c) && (null != nc)) { c = nc.FindControl(id); nc = nc.NamingContainer; } if(null == c) { // Note: props MAY be null, but we're firing the event anyway to let the user // do the best they can ResolveControlEventArgs args = new ResolveControlEventArgs(id); OnResolveControlID(args); c = args.Control; } if(null != c) { _findControlHelperCache[id] = c; } } return c; } // Fired when the extender can not locate it's target control. This may happen if the // target control is in a different naming container. // By handling this event, user code can locate the target and return it via the ResolveControlEventArgs.Control property. protected virtual void OnResolveControlID(ResolveControlEventArgs e) { if(ResolveControlID != null) { ResolveControlID(this, e); } } protected override IEnumerable<ScriptDescriptor> GetScriptDescriptors(Control targetControl) { if(!Enabled || !targetControl.Visible) return null; EnsureValid(); ScriptBehaviorDescriptor descriptor = new ScriptBehaviorDescriptor(ClientControlType, targetControl.ClientID); // render the attributes for this element RenderScriptAttributes(descriptor); // render profile bindings //RenderProfileBindings(descriptor); // render any child scripts we need to. RenderInnerScript(descriptor); return new List<ScriptDescriptor>(new ScriptDescriptor[] { descriptor }); } // Called during rendering to give derived classes a chance to validate their properties public virtual void EnsureValid() { CheckIfValid(true); } protected virtual bool CheckIfValid(bool throwException) { bool valid = true; foreach(PropertyDescriptor prop in TypeDescriptor.GetProperties(this)) { // If the property is tagged with RequiredPropertyAttribute, but doesn't have a value, throw an exception if((null != prop.Attributes[typeof(RequiredPropertyAttribute)]) && ((null == prop.GetValue(this)) || !prop.ShouldSerializeValue(this))) { valid = false; if(throwException) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "{0} missing required {1} property value for {2}.", GetType().ToString(), prop.Name, ID), prop.Name); } } } return valid; } // Walks each of the properties in the TargetProperties object and renders script for them. protected virtual void RenderScriptAttributes(ScriptBehaviorDescriptor descriptor) { try { ComponentDescriber.DescribeComponent(this, new ScriptComponentDescriptorWrapper(descriptor), this.Page, this); } finally { } } // Allows generation of markup within the behavior declaration in XML script protected virtual void RenderInnerScript(ScriptBehaviorDescriptor descriptor) { } protected override IEnumerable<ScriptReference> GetScriptReferences() { if(!Enabled) return null; return ToolkitResourceManager.GetControlScriptReferences(GetType()); } protected V GetPropertyValue<V>(string propertyName, V nullValue) { if(ViewState[propertyName] == null) { return nullValue; } return (V)ViewState[propertyName]; } protected void SetPropertyValue<V>(string propertyName, V value) { ViewState[propertyName] = value; } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); RegisterLocalization(); if(Enabled && TargetControl.Visible) { SaveClientStateValues(); } } void RegisterLocalization() { var localeKey = new Localization().GetLocaleKey(); if(String.IsNullOrEmpty(localeKey)) return; var script = String.Format(@"Sys.Extended.UI.Localization.SetLocale(""{0}"");", localeKey); Page.ClientScript.RegisterStartupScript(GetType(), "f93b988bab7e44ffbcff635ee599ade2", script, true); } protected override void OnLoad(EventArgs e) { if(!_loadedClientStateValues) { LoadClientStateValues(); } base.OnLoad(e); ToolkitResourceManager.RegisterCssReferences(this); } } } #pragma warning restore 1591
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using OpenMetaverse; using OpenSim.Region.Framework.Interfaces; using System; using System.Collections.Generic; namespace OpenSim.Region.CoreModules.Framework.InterfaceCommander { /// <summary> /// A single function call encapsulated in a class which enforces arguments when passing around as Object[]'s. /// Used for console commands and script API generation /// </summary> public class Command : ICommand { //private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private List<CommandArgument> m_args = new List<CommandArgument>(); private Action<object[]> m_command; private string m_help; private CommandIntentions m_intentions; private string m_name; //A permission type system could implement this and know what a command intends on doing. public Command(string name, CommandIntentions intention, Action<Object[]> command, string help) { m_name = name; m_command = command; m_help = help; m_intentions = intention; } #region ICommand Members public Dictionary<string, string> Arguments { get { Dictionary<string, string> tmp = new Dictionary<string, string>(); foreach (CommandArgument arg in m_args) { tmp.Add(arg.Name, arg.ArgumentType); } return tmp; } } public string Help { get { return m_help; } } public CommandIntentions Intentions { get { return m_intentions; } } public string Name { get { return m_name; } } public void AddArgument(string name, string helptext, string type) { m_args.Add(new CommandArgument(name, helptext, type)); } public void Run(Object[] args) { Object[] cleanArgs = new Object[m_args.Count]; if (args.Length < cleanArgs.Length) { Console.WriteLine("ERROR: Missing " + (cleanArgs.Length - args.Length) + " argument(s)"); ShowConsoleHelp(); return; } if (args.Length > cleanArgs.Length) { Console.WriteLine("ERROR: Too many arguments for this command. Type '<module> <command> help' for help."); return; } int i = 0; foreach (Object arg in args) { if (string.IsNullOrEmpty(arg.ToString())) { Console.WriteLine("ERROR: Empty arguments are not allowed"); return; } try { switch (m_args[i].ArgumentType) { case "String": m_args[i].ArgumentValue = arg.ToString(); break; case "Integer": m_args[i].ArgumentValue = Int32.Parse(arg.ToString()); break; case "Double": m_args[i].ArgumentValue = Double.Parse(arg.ToString(), OpenSim.Framework.Culture.NumberFormatInfo); break; case "Boolean": m_args[i].ArgumentValue = Boolean.Parse(arg.ToString()); break; case "UUID": m_args[i].ArgumentValue = UUID.Parse(arg.ToString()); break; default: Console.WriteLine("ERROR: Unknown desired type for argument " + m_args[i].Name + " on command " + m_name); break; } } catch (FormatException) { Console.WriteLine("ERROR: Argument number " + (i + 1) + " (" + m_args[i].Name + ") must be a valid " + m_args[i].ArgumentType.ToLower() + "."); return; } cleanArgs[i] = m_args[i].ArgumentValue; i++; } m_command.Invoke(cleanArgs); } public string ShortHelp() { string help = m_name; foreach (CommandArgument arg in m_args) { help += " <" + arg.Name + ">"; } return help; } public void ShowConsoleHelp() { Console.WriteLine("== " + Name + " =="); Console.WriteLine(m_help); Console.WriteLine("= Parameters ="); foreach (CommandArgument arg in m_args) { Console.WriteLine("* " + arg.Name + " (" + arg.ArgumentType + ")"); Console.WriteLine("\t" + arg.HelpText); } } #endregion ICommand Members } /// <summary> /// A single command argument, contains name, type and at runtime, value. /// </summary> public class CommandArgument { private string m_help; private string m_name; private string m_type; private Object m_val; public CommandArgument(string name, string help, string type) { m_name = name; m_help = help; m_type = type; } public string ArgumentType { get { return m_type; } } public Object ArgumentValue { get { return m_val; } set { m_val = value; } } public string HelpText { get { return m_help; } } public string Name { get { return m_name; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AlignRightByte27() { var test = new ImmBinaryOpTest__AlignRightByte27(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmBinaryOpTest__AlignRightByte27 { private struct TestStruct { public Vector256<Byte> _fld1; public Vector256<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__AlignRightByte27 testClass) { var result = Avx2.AlignRight(_fld1, _fld2, 27); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector256<Byte> _clsVar1; private static Vector256<Byte> _clsVar2; private Vector256<Byte> _fld1; private Vector256<Byte> _fld2; private SimpleBinaryOpTest__DataTable<Byte, Byte, Byte> _dataTable; static ImmBinaryOpTest__AlignRightByte27() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); } public ImmBinaryOpTest__AlignRightByte27() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new SimpleBinaryOpTest__DataTable<Byte, Byte, Byte>(_data1, _data2, new Byte[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.AlignRight( Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr), 27 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.AlignRight( Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr)), 27 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.AlignRight( Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr)), 27 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.AlignRight), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr), (byte)27 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.AlignRight), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr)), (byte)27 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.AlignRight), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr)), (byte)27 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.AlignRight( _clsVar1, _clsVar2, 27 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr); var result = Avx2.AlignRight(left, right, 27); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr)); var result = Avx2.AlignRight(left, right, 27); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr)); var result = Avx2.AlignRight(left, right, 27); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__AlignRightByte27(); var result = Avx2.AlignRight(test._fld1, test._fld2, 27); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.AlignRight(_fld1, _fld2, 27); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.AlignRight(test._fld1, test._fld2, 27); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Byte> left, Vector256<Byte> right, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != left[11]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((result[i] != ((i < 16) ? ((i < 5) ? left[i + 11] : 0) : ((i < 21) ? left[i + 11] : 0)))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.AlignRight)}<Byte>(Vector256<Byte>.27, Vector256<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Bond.Comm.Service { using System; using System.Collections.Generic; using System.Reflection; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Bond.Comm; public class ServiceHost { private readonly object dispatchTableLock; private readonly Dictionary<string, ServiceMethodInfo> dispatchTable; private readonly Logger logger; public ServiceHost(Logger logger) { dispatchTableLock = new object(); dispatchTable = new Dictionary<string, ServiceMethodInfo>(); this.logger = logger; } private static void Update(RequestMetrics requestMetrics, string serviceName, string methodName, Stopwatch serviceTime) { requestMetrics.service_name = serviceName ?? string.Empty; requestMetrics.method_name = methodName ?? string.Empty; requestMetrics.service_method_time_millis = serviceTime?.Elapsed.TotalMilliseconds ?? 0; } public bool IsRegistered(string serviceMethodName) { lock (dispatchTableLock) { return dispatchTable.ContainsKey(serviceMethodName); } } public void ValidateServiceMethods(IEnumerable<ServiceMethodInfo> serviceMethods) { Type returnParameter; foreach (var serviceMethod in serviceMethods) { switch (serviceMethod.CallbackType) { case ServiceCallbackType.RequestResponse: returnParameter = serviceMethod.Callback.GetMethodInfo().ReturnType; if (returnParameter != typeof(Task<IMessage>)) { throw new ArgumentException($"{serviceMethod.MethodName} registered as " + $"{serviceMethod.CallbackType} but callback not implemented as such."); } break; case ServiceCallbackType.Event: returnParameter = serviceMethod.Callback.GetMethodInfo().ReturnType; if (returnParameter != typeof(Task)) { throw new ArgumentException($"{serviceMethod.MethodName} registered as " + $"{serviceMethod.CallbackType} but callback not implemented as such."); } break; default: throw new ArgumentException($"{serviceMethod.MethodName} registered as invalid type " + $"{serviceMethod.CallbackType}."); } } } public void Register<T>(T service) where T : IService { var methodNames = new SortedSet<string>(); ValidateServiceMethods(service.Methods); lock (dispatchTableLock) { // Service methods are registerd as a unit - either register all or none. // This code could have been greedy to do both check and register in a single loop, // plus a nested loop to clean up / rollback in case of a method already registered. // Now services registration is expected to be infrequent and very light weight event, // so we decided in favor of looping twice over the same collection to avoid nested loop // for clean up. foreach (var serviceMethod in service.Methods) { if (dispatchTable.ContainsKey(serviceMethod.MethodName)) { throw new ArgumentException($"{serviceMethod.MethodName} already registered"); } } foreach (var serviceMethod in service.Methods) { dispatchTable.Add(serviceMethod.MethodName, serviceMethod); methodNames.Add($"[{serviceMethod.MethodName}]"); } } logger.Site().Information("Registered {0} with methods: {1}", typeof(T).Name, string.Join(", ", methodNames)); } public void Deregister<T>(T service) where T : IService { lock (dispatchTableLock) { foreach (var serviceMethod in service.Methods) { dispatchTable.Remove(serviceMethod.MethodName); } } logger.Site().Information("Deregistered {0}.", typeof(T).Name); } public async Task<IMessage> DispatchRequest(string serviceName, string methodName, ReceiveContext context, IMessage message) { string qualifiedName = serviceName + "." + methodName; Stopwatch serviceTime = null; logger.Site().Information("Got request [{0}] from {1}.", qualifiedName, context.Connection); try { ServiceMethodInfo methodInfo; lock (dispatchTableLock) { if (!dispatchTable.TryGetValue(qualifiedName, out methodInfo)) { var errorMessage = "Got request for unknown method [" + qualifiedName + "]."; logger.Site().Error(errorMessage); var error = new Error { message = errorMessage, error_code = (int) ErrorCode.METHOD_NOT_FOUND }; return Message.FromError(error); } } if (methodInfo.CallbackType != ServiceCallbackType.RequestResponse) { var errorMessage = "Method [" + qualifiedName + "] invoked as if it were " + ServiceCallbackType.RequestResponse + ", but it was registered as " + methodInfo.CallbackType + "."; logger.Site().Error(errorMessage); var error = new Error { message = errorMessage, error_code = (int) ErrorCode.INVALID_INVOCATION }; return Message.FromError(error); } IMessage result; try { serviceTime = Stopwatch.StartNew(); // Cast to appropriate return type which we validated when registering the service result = await (Task<IMessage>) methodInfo.Callback(message, context, CancellationToken.None); serviceTime.Stop(); } catch (Exception ex) { logger.Site() .Error(ex, "Failed to complete method [{0}]. With exception: {1}", qualifiedName, ex.Message); result = Message.FromError( Errors.MakeInternalServerError(ex, context.RequestMetrics.request_id, includeDetails: false)); } return result; } finally { Update(context.RequestMetrics, serviceName, methodName, serviceTime); } } public async Task DispatchEvent(string serviceName, string methodName, ReceiveContext context, IMessage message) { string qualifiedName = serviceName + "." + methodName; Stopwatch serviceTime = null; logger.Site().Information("Got event [{0}] from {1}.", qualifiedName, context.Connection); try { ServiceMethodInfo methodInfo; lock (dispatchTableLock) { if (!dispatchTable.TryGetValue(qualifiedName, out methodInfo)) { logger.Site().Error("Got request for unknown method [{0}].", qualifiedName); return; } } if (methodInfo.CallbackType != ServiceCallbackType.Event) { logger.Site().Error("Method [{0}] invoked as if it were {1}, but it was registered as {2}.", qualifiedName, ServiceCallbackType.Event, methodInfo.CallbackType); return; } try { serviceTime = Stopwatch.StartNew(); await methodInfo.Callback(message, context, CancellationToken.None); } catch (Exception ex) { logger.Site() .Error(ex, "Failed to complete method [{0}]. With exception: {1}", qualifiedName, ex.Message); } } finally { Update(context.RequestMetrics, serviceName, methodName, serviceTime); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void HorizontalAddInt32() { var test = new HorizontalBinaryOpTest__HorizontalAddInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class HorizontalBinaryOpTest__HorizontalAddInt32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int32> _fld1; public Vector128<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(HorizontalBinaryOpTest__HorizontalAddInt32 testClass) { var result = Ssse3.HorizontalAdd(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(HorizontalBinaryOpTest__HorizontalAddInt32 testClass) { fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = Ssse3.HorizontalAdd( Sse2.LoadVector128((Int32*)(pFld1)), Sse2.LoadVector128((Int32*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector128<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector128<Int32> _fld1; private Vector128<Int32> _fld2; private DataTable _dataTable; static HorizontalBinaryOpTest__HorizontalAddInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public HorizontalBinaryOpTest__HorizontalAddInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Ssse3.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Ssse3.HorizontalAdd( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Ssse3.HorizontalAdd( Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Ssse3.HorizontalAdd( Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Ssse3).GetMethod(nameof(Ssse3.HorizontalAdd), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Ssse3).GetMethod(nameof(Ssse3.HorizontalAdd), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Ssse3).GetMethod(nameof(Ssse3.HorizontalAdd), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Ssse3.HorizontalAdd( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int32>* pClsVar1 = &_clsVar1) fixed (Vector128<Int32>* pClsVar2 = &_clsVar2) { var result = Ssse3.HorizontalAdd( Sse2.LoadVector128((Int32*)(pClsVar1)), Sse2.LoadVector128((Int32*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = Ssse3.HorizontalAdd(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Ssse3.HorizontalAdd(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Ssse3.HorizontalAdd(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new HorizontalBinaryOpTest__HorizontalAddInt32(); var result = Ssse3.HorizontalAdd(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new HorizontalBinaryOpTest__HorizontalAddInt32(); fixed (Vector128<Int32>* pFld1 = &test._fld1) fixed (Vector128<Int32>* pFld2 = &test._fld2) { var result = Ssse3.HorizontalAdd( Sse2.LoadVector128((Int32*)(pFld1)), Sse2.LoadVector128((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Ssse3.HorizontalAdd(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = Ssse3.HorizontalAdd( Sse2.LoadVector128((Int32*)(pFld1)), Sse2.LoadVector128((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Ssse3.HorizontalAdd(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Ssse3.HorizontalAdd( Sse2.LoadVector128((Int32*)(&test._fld1)), Sse2.LoadVector128((Int32*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int32> op1, Vector128<Int32> op2, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var outer = 0; outer < (LargestVectorSize / 16); outer++) { for (var inner = 0; inner < (8 / sizeof(Int32)); inner++) { var i1 = (outer * (16 / sizeof(Int32))) + inner; var i2 = i1 + (8 / sizeof(Int32)); var i3 = (outer * (16 / sizeof(Int32))) + (inner * 2); if (result[i1] != (int)(left[i3] + left[i3 + 1])) { succeeded = false; break; } if (result[i2] != (int)(right[i3] + right[i3 + 1])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Ssse3)}.{nameof(Ssse3.HorizontalAdd)}<Int32>(Vector128<Int32>, Vector128<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
namespace ZetaHtmlEditControl.UI.EditControlDerives { using System; using System.ComponentModel; using System.Drawing; using System.IO; using System.Windows.Forms; using Code.Configuration; using Code.PInvoke; using EditControlBases; using Helper; /// <summary> /// Edit control, primarily designed to work in conjunction /// with the ZetaHelpdesk application. /// </summary> /// <remarks> /// Oleg Shilo 22.05.2013, all code related to: /// - EmbeddImages /// - FontSize /// - FontName /// - PrintPreview /// - Print /// </remarks> public partial class HtmlEditControl : CoreHtmlEditControl { private HtmlEditControlConfiguration _configuration = new HtmlEditControlConfiguration(); private bool _everLoadedTextModules; private bool _firstCreate = true; private int _objectID = 1; private TextModuleInfo[] _textModules; private bool _textModulesFilled; private Timer _timerTextChange = new Timer(); private string _tmpCacheTextChange = string.Empty; private string _tmpFolderPath = string.Empty; public HtmlEditControl() { InitializeComponent(); AllowWebBrowserDrop = false; Navigate(@"about:blank"); _tmpFolderPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(_tmpFolderPath); _timerTextChange.Tick += timerTextChange_Tick; _timerTextChange.Interval = 200; _timerTextChange.Start(); // -- constructHtmlEditControlKeyboard(); Configure(Configuration); } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int TextChangeCheckInterval { get { return _timerTextChange.Interval; } set { if (value < 1000) //1 min { _timerTextChange.Interval = value; } } } public bool HasTextModules { get { checkGetTextModules(); return _textModules != null && _textModules.Length > 0; } } public HtmlEditControlConfiguration Configuration { get { return _configuration; } } protected override void DestroyHandle() { if (_timerTextChange != null) { _timerTextChange.Stop(); _timerTextChange.Dispose(); _timerTextChange = null; } if (!string.IsNullOrEmpty(_tmpFolderPath)) { if (Directory.Exists(_tmpFolderPath)) { Directory.Delete(_tmpFolderPath, true); } _tmpFolderPath = null; } base.DestroyHandle(); } public void Configure(HtmlEditControlConfiguration configuration) { if (configuration == null) throw new ArgumentNullException(@"configuration"); _configuration = configuration; _everLoadedTextModules = false; // Reset to force reload. updateUI(); } protected override void OnGotFocus(EventArgs e) { base.OnGotFocus(e); if (Document != null) { if (Document.Body != null) { Document.Body.Focus(); } } } protected override void OnNavigated(WebBrowserNavigatedEventArgs e) { base.OnNavigated(e); if (_firstCreate) { _firstCreate = false; // 2012-08-28, Uwe Keim: Enable gray shortcut texts. contextMenuStrip.Renderer = new MyToolStripRender(); } } private void timerTextChange_Tick( object sender, EventArgs e) { if (!IsDisposed) // Uwe Keim 2006-03-17. { var s = DocumentText ?? string.Empty; if (_tmpCacheTextChange != s) { _tmpCacheTextChange = s; var h = TextChanged; if (h != null) h(this, new EventArgs()); } } } public new event EventHandler TextChanged; private void contextMenuStrip_Opening(object sender, CancelEventArgs e) { updateUI(); } private void updateUI() { if (Document != null && Document.DomDocument != null) { boldToolStripMenuItem.Enabled = CanBold; italicToolStripMenuItem.Enabled = CanItalic; cutToolStripMenuItem.Enabled = CanCut; copyToolStripMenuItem.Enabled = CanCopy; pasteAsTextToolStripMenuItem.Enabled = CanPaste; pasteToolStripMenuItem.Enabled = CanPaste; pasteFromMsWordToolStripItem.Enabled = CanPaste; deleteToolStripMenuItem.Enabled = CanDelete; indentToolStripMenuItem.Enabled = CanIndent; justifyCenterToolStripMenuItem.Enabled = CanJustifyCenter; justifyLeftToolStripMenuItem.Enabled = CanJustifyLeft; justifyRightToolStripMenuItem.Enabled = CanJustifyRight; numberedListToolStripMenuItem.Enabled = CanOrderedList; outdentToolStripMenuItem.Enabled = CanOutdent; bullettedListToolStripMenuItem.Enabled = CanBullettedList; foreColorToolStripMenuItem.Enabled = CanForeColor; backColorToolStripMenuItem.Enabled = CanBackColor; hyperLinkToolStripMenuItem.Enabled = CanInsertHyperlink; htmlToolStripMenuItem.Enabled = CanShowSource; removeFormattingToolStripMenuItem.Enabled = CanRemoveFormatting; // -- // Table menu. insertNewTableToolStripMenuItem.Enabled = CanInsertTable; insertRowBeforeCurrentRowToolStripMenuItem.Enabled = CanInsertTableRow; insertColumnBeforeCurrentColumnToolStripMenuItem.Enabled = CanInsertTableColumn; addRowAfterTheLastTableRowToolStripMenuItem.Enabled = CanAddTableRow; addColumnAfterTheLastTableColumnToolStripMenuItem.Enabled = CanAddTableColumn; tablePropertiesToolStripMenuItem.Enabled = CanTableProperties; rowPropertiesToolStripMenuItem.Enabled = CanTableRowProperties; columnPropertiesToolStripMenuItem.Enabled = CanTableColumnProperties; cellPropertiesToolStripMenuItem.Enabled = CanTableCellProperties; deleteRowToolStripMenuItem.Enabled = CanTableDeleteRow; deleteColumnToolStripMenuItem.Enabled = CanTableDeleteColumn; deleteTableToolStripMenuItem.Enabled = CanTableDeleteTable; // -- textModulesToolStripMenuItem.Visible = HasTextModules; textModulesSeparator.Visible = HasTextModules; } } private void boldToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteBold(); } private void italicToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteItalic(); } private void pasteToolStripMenuItem_Click(object sender, EventArgs e) { ExecutePaste(); } private void pasteAsTextToolStripMenuItem_Click(object sender, EventArgs e) { ExecutePasteAsText(); } private void htmlToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteShowSource(); } private void hyperLinkToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteInsertHyperlink(); } private void indentToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteIndent(); } private void justifyCenterToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteJustifyCenter(); } private void justifyLeftToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteJustifyLeft(); } private void justifyRightToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteJustifyRight(); } private void numberedListToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteNumberedList(); } private void outdentToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteOutdent(); } private void bullettedListToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteBullettedList(); } private void copyToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteCopy(); } private void cutToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteCut(); } private void deleteToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteDelete(); } private void foreColorNoneToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteSetForeColorNone(); } private void foreColor01ToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteSetForeColor01(); } private void foreColor02ToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteSetForeColor02(); } private void foreColor03ToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteSetForeColor03(); } private void foreColor04ToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteSetForeColor04(); } private void foreColor05ToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteSetForeColor05(); } private void foreColor06ToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteSetForeColor06(); } private void foreColor07ToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteSetForeColor07(); } private void foreColor08ToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteSetForeColor08(); } private void foreColor09ToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteSetForeColor09(); } private void foreColor10ToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteSetForeColor10(); } private void backColorNoneToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteSetBackColorNone(); } private void backColor01ToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteSetBackColor01(); } private void backColor02ToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteSetBackColor02(); } private void backColor03ToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteSetBackColor03(); } private void backColor04ToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteSetBackColor04(); } private void backColor05ToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteSetBackColor05(); } private void insertNewTableToolStripMenuItem_Click( object sender, EventArgs e) { ExecuteInsertTable(); } private void insertRowBeforeCurrentRowToolStripMenuItem_Click( object sender, EventArgs e) { ExecuteInsertTableRow(); } private void insertColumnBeforeCurrentColumnToolStripMenuItem_Click( object sender, EventArgs e) { ExecuteInsertTableColumn(); } private void addRowAfterTheLastTableRowToolStripMenuItem_Click( object sender, EventArgs e) { ExecuteTableAddTableRow(); } private void addColumnAfterTheLastTableColumnToolStripMenuItem_Click( object sender, EventArgs e) { ExecuteTableAddTableColumn(); } private void tablePropertiesToolStripMenuItem_Click( object sender, EventArgs e) { ExecuteTableProperties(); } private void rowPropertiesToolStripMenuItem_Click( object sender, EventArgs e) { ExecuteTableRowProperties(); } private void columnPropertiesToolStripMenuItem_Click( object sender, EventArgs e) { ExecuteTableColumnProperties(); } private void cellPropertiesToolStripMenuItem_Click( object sender, EventArgs e) { ExecuteTableCellProperties(); } private void deleteRowToolStripMenuItem_Click( object sender, EventArgs e) { ExecuteTableDeleteRow(); } private void deleteColumnToolStripMenuItem_Click( object sender, EventArgs e) { ExecuteTableDeleteColumn(); } private void deleteTableToolStripMenuItem_Click( object sender, EventArgs e) { ExecuteTableDeleteTable(); } protected override void OnUpdateUI() { var h = UINeedsUpdate; if (h != null) h(this, EventArgs.Empty); } public event EventHandler UINeedsUpdate; internal void FillTextModules( ToolStripDropDownItem textModulesToolStripItem) { checkGetTextModules(); textModulesToolStripItem.DropDownItems.Clear(); foreach (var textModule in _textModules) { var mi = new ToolStripMenuItem(textModule.Name) {Tag = textModule}; mi.Click += delegate { var tm = (TextModuleInfo) mi.Tag; InsertHtmlAtCurrentSelection(tm.Html); }; textModulesToolStripItem.DropDownItems.Add(mi); } } private void checkGetTextModules() { if (_configuration != null && _configuration.ExternalInformationProvider != null && !_everLoadedTextModules) { _everLoadedTextModules = true; _textModules = _configuration.ExternalInformationProvider.GetTextModules(); } } private void textModulesToolStripMenuItem_DropDownOpening(object sender, EventArgs e) { checkFillTextModules(textModulesToolStripMenuItem); } private void checkFillTextModules(ToolStripDropDownItem toolStripMenuItem) { if (!_textModulesFilled) { _textModulesFilled = true; FillTextModules(toolStripMenuItem); } } protected override bool OnNeedShowContextMenu( NativeMethods.ContextMenuKind contextMenuKind, Point position, NativeMethods.IUnknown queryForStatus, NativeMethods.IDispatch objectAtScreenCoordinates) { base.OnNeedShowContextMenu(contextMenuKind, position, queryForStatus, objectAtScreenCoordinates); if (_configuration != null && _configuration.ExternalInformationProvider != null) { var font = _configuration.ExternalInformationProvider.Font; contextMenuStrip.Font = font ?? Font; } else { contextMenuStrip.Font = Font; } contextMenuStrip.Show(position); return true; } private void underlineToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteUnderline(); } private void pasteFromMsWordToolStripItem_Click(object sender, EventArgs e) { ExecutePasteFromWord(); } private void removeFormattingToolStripMenuItem_Click(object sender, EventArgs e) { ExecuteRemoveFormatting(); } } }
// 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 Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal sealed class ExprFactory { private readonly GlobalSymbolContext _globalSymbolContext; private readonly ConstValFactory _constants; public ExprFactory(GlobalSymbolContext globalSymbolContext) { Debug.Assert(globalSymbolContext != null); _globalSymbolContext = globalSymbolContext; _constants = new ConstValFactory(); } public ConstValFactory GetExprConstants() { return _constants; } private TypeManager GetTypes() { return _globalSymbolContext.GetTypes(); } private BSYMMGR GetGlobalSymbols() { return _globalSymbolContext.GetGlobalSymbols(); } public EXPRCALL CreateCall(EXPRFLAG nFlags, CType pType, EXPR pOptionalArguments, EXPRMEMGRP pMemberGroup, MethWithInst MWI) { Debug.Assert(0 == (nFlags & ~( EXPRFLAG.EXF_NEWOBJCALL | EXPRFLAG.EXF_CONSTRAINED | EXPRFLAG.EXF_BASECALL | EXPRFLAG.EXF_NEWSTRUCTASSG | EXPRFLAG.EXF_IMPLICITSTRUCTASSG | EXPRFLAG.EXF_MASK_ANY ) )); EXPRCALL rval = new EXPRCALL(); rval.kind = ExpressionKind.EK_CALL; rval.type = pType; rval.flags = nFlags; rval.SetOptionalArguments(pOptionalArguments); rval.SetMemberGroup(pMemberGroup); rval.nubLiftKind = NullableCallLiftKind.NotLifted; rval.castOfNonLiftedResultToLiftedType = null; rval.mwi = MWI; Debug.Assert(rval != null); return (rval); } public EXPRFIELD CreateField(EXPRFLAG nFlags, CType pType, EXPR pOptionalObject, uint nOffset, FieldWithType FWT, EXPR pOptionalLHS) { Debug.Assert(0 == (nFlags & ~(EXPRFLAG.EXF_MEMBERSET | EXPRFLAG.EXF_MASK_ANY))); EXPRFIELD rval = new EXPRFIELD(); rval.kind = ExpressionKind.EK_FIELD; rval.type = pType; rval.flags = nFlags; rval.SetOptionalObject(pOptionalObject); if (FWT != null) { rval.fwt = FWT; } Debug.Assert(rval != null); return (rval); } public EXPRFUNCPTR CreateFunctionPointer(EXPRFLAG nFlags, CType pType, EXPR pObject, MethWithInst MWI) { Debug.Assert(0 == (nFlags & ~(EXPRFLAG.EXF_BASECALL))); EXPRFUNCPTR rval = new EXPRFUNCPTR(); rval.kind = ExpressionKind.EK_FUNCPTR; rval.type = pType; rval.flags = nFlags; rval.OptionalObject = pObject; rval.mwi = new MethWithInst(MWI); Debug.Assert(rval != null); return (rval); } public EXPRARRINIT CreateArrayInit(EXPRFLAG nFlags, CType pType, EXPR pOptionalArguments, EXPR pOptionalArgumentDimensions, int[] pDimSizes) { Debug.Assert(0 == (nFlags & ~(EXPRFLAG.EXF_MASK_ANY | EXPRFLAG.EXF_ARRAYCONST | EXPRFLAG.EXF_ARRAYALLCONST))); EXPRARRINIT rval = new EXPRARRINIT(); rval.kind = ExpressionKind.EK_ARRINIT; rval.type = pType; rval.SetOptionalArguments(pOptionalArguments); rval.SetOptionalArgumentDimensions(pOptionalArgumentDimensions); rval.dimSizes = pDimSizes; rval.dimSize = pDimSizes?.Length ?? 0; Debug.Assert(rval != null); return (rval); } public EXPRPROP CreateProperty(CType pType, EXPR pOptionalObject) { MethPropWithInst mwi = new MethPropWithInst(); EXPRMEMGRP pMemGroup = CreateMemGroup(pOptionalObject, mwi); return CreateProperty(pType, null, null, pMemGroup, null, null, null); } public EXPRPROP CreateProperty(CType pType, EXPR pOptionalObjectThrough, EXPR pOptionalArguments, EXPRMEMGRP pMemberGroup, PropWithType pwtSlot, MethWithType mwtGet, MethWithType mwtSet) { EXPRPROP rval = new EXPRPROP(); rval.kind = ExpressionKind.EK_PROP; rval.type = pType; rval.flags = 0; rval.SetOptionalObjectThrough(pOptionalObjectThrough); rval.SetOptionalArguments(pOptionalArguments); rval.SetMemberGroup(pMemberGroup); if (pwtSlot != null) { rval.pwtSlot = pwtSlot; } if (mwtSet != null) { rval.mwtSet = mwtSet; } Debug.Assert(rval != null); return (rval); } public EXPREVENT CreateEvent(CType pType, EXPR pOptionalObject, EventWithType EWT) { EXPREVENT rval = new EXPREVENT(); rval.kind = ExpressionKind.EK_EVENT; rval.type = pType; rval.flags = 0; rval.OptionalObject = pOptionalObject; if (EWT != null) { rval.ewt = EWT; } Debug.Assert(rval != null); return (rval); } public EXPRMEMGRP CreateMemGroup(EXPRFLAG nFlags, Name pName, TypeArray pTypeArgs, SYMKIND symKind, CType pTypePar, MethodOrPropertySymbol pMPS, EXPR pObject, CMemberLookupResults memberLookupResults) { Debug.Assert(0 == (nFlags & ~( EXPRFLAG.EXF_CTOR | EXPRFLAG.EXF_INDEXER | EXPRFLAG.EXF_OPERATOR | EXPRFLAG.EXF_NEWOBJCALL | EXPRFLAG.EXF_BASECALL | EXPRFLAG.EXF_DELEGATE | EXPRFLAG.EXF_USERCALLABLE | EXPRFLAG.EXF_MASK_ANY ) )); EXPRMEMGRP rval = new EXPRMEMGRP(); rval.kind = ExpressionKind.EK_MEMGRP; rval.type = GetTypes().GetMethGrpType(); rval.flags = nFlags; rval.name = pName; rval.typeArgs = pTypeArgs; rval.sk = symKind; rval.SetParentType(pTypePar); rval.SetOptionalObject(pObject); rval.SetMemberLookupResults(memberLookupResults); rval.SetOptionalLHS(null); if (rval.typeArgs == null) { rval.typeArgs = BSYMMGR.EmptyTypeArray(); } Debug.Assert(rval != null); return (rval); } public EXPRMEMGRP CreateMemGroup( EXPR pObject, MethPropWithInst mwi) { Name pName = mwi.Sym?.name; MethodOrPropertySymbol methProp = mwi.MethProp(); CType pType = mwi.GetType(); if (pType == null) { pType = GetTypes().GetErrorSym(); } return CreateMemGroup(0, pName, mwi.TypeArgs, methProp?.getKind() ?? SYMKIND.SK_MethodSymbol, mwi.GetType(), methProp, pObject, new CMemberLookupResults(GetGlobalSymbols().AllocParams(1, new CType[] { pType }), pName)); } public EXPRUSERDEFINEDCONVERSION CreateUserDefinedConversion(EXPR arg, EXPR call, MethWithInst mwi) { Debug.Assert(arg != null); Debug.Assert(call != null); EXPRUSERDEFINEDCONVERSION rval = new EXPRUSERDEFINEDCONVERSION(); rval.kind = ExpressionKind.EK_USERDEFINEDCONVERSION; rval.type = call.type; rval.flags = 0; rval.Argument = arg; rval.UserDefinedCall = call; rval.UserDefinedCallMethod = mwi; if (call.HasError()) { rval.SetError(); } Debug.Assert(rval != null); return rval; } public EXPRCAST CreateCast(EXPRFLAG nFlags, CType pType, EXPR pArg) { return CreateCast(nFlags, CreateClass(pType, null, null), pArg); } public EXPRCAST CreateCast(EXPRFLAG nFlags, EXPRTYPEORNAMESPACE pType, EXPR pArg) { Debug.Assert(pArg != null); Debug.Assert(pType != null); Debug.Assert(0 == (nFlags & ~(EXPRFLAG.EXF_CAST_ALL | EXPRFLAG.EXF_MASK_ANY))); EXPRCAST rval = new EXPRCAST(); rval.type = pType.TypeOrNamespace as CType; rval.kind = ExpressionKind.EK_CAST; rval.Argument = pArg; rval.flags = nFlags; rval.DestinationType = pType; Debug.Assert(rval != null); return (rval); } public EXPRRETURN CreateReturn(EXPRFLAG nFlags, Scope pCurrentScope, EXPR pOptionalObject) { return CreateReturn(nFlags, pCurrentScope, pOptionalObject, pOptionalObject); } private EXPRRETURN CreateReturn(EXPRFLAG nFlags, Scope pCurrentScope, EXPR pOptionalObject, EXPR pOptionalOriginalObject) { Debug.Assert(0 == (nFlags & ~(EXPRFLAG.EXF_ASLEAVE | EXPRFLAG.EXF_FINALLYBLOCKED | EXPRFLAG.EXF_RETURNISYIELD | EXPRFLAG.EXF_ASFINALLYLEAVE | EXPRFLAG.EXF_GENERATEDSTMT | EXPRFLAG.EXF_MARKING | EXPRFLAG.EXF_MASK_ANY ) )); EXPRRETURN rval = new EXPRRETURN(); rval.kind = ExpressionKind.EK_RETURN; rval.type = null; rval.flags = nFlags; rval.SetOptionalObject(pOptionalObject); Debug.Assert(rval != null); return (rval); } public EXPRLOCAL CreateLocal(EXPRFLAG nFlags, LocalVariableSymbol pLocal) { Debug.Assert(0 == (nFlags & ~(EXPRFLAG.EXF_MASK_ANY))); CType type = null; if (pLocal != null) { type = pLocal.GetType(); } EXPRLOCAL rval = new EXPRLOCAL(); rval.kind = ExpressionKind.EK_LOCAL; rval.type = type; rval.flags = nFlags; rval.local = pLocal; Debug.Assert(rval != null); return (rval); } public EXPRTHISPOINTER CreateThis(LocalVariableSymbol pLocal, bool fImplicit) { Debug.Assert(pLocal == null || pLocal.isThis); CType type = null; if (pLocal != null) { type = pLocal.GetType(); } EXPRFLAG flags = EXPRFLAG.EXF_CANTBENULL; if (fImplicit) { flags |= EXPRFLAG.EXF_IMPLICITTHIS; } if (type != null && type.isStructType()) { flags |= EXPRFLAG.EXF_LVALUE; } EXPRTHISPOINTER rval = new EXPRTHISPOINTER(); rval.kind = ExpressionKind.EK_THISPOINTER; rval.type = type; rval.flags = flags; rval.local = pLocal; Debug.Assert(rval != null); return (rval); } public EXPRBOUNDLAMBDA CreateAnonymousMethod(AggregateType delegateType) { Debug.Assert(delegateType == null || delegateType.isDelegateType()); EXPRBOUNDLAMBDA rval = new EXPRBOUNDLAMBDA(); rval.kind = ExpressionKind.EK_BOUNDLAMBDA; rval.type = delegateType; rval.flags = 0; Debug.Assert(rval != null); return (rval); } public EXPRUNBOUNDLAMBDA CreateLambda() { CType type = GetTypes().GetAnonMethType(); EXPRUNBOUNDLAMBDA rval = new EXPRUNBOUNDLAMBDA(); rval.kind = ExpressionKind.EK_UNBOUNDLAMBDA; rval.type = type; rval.flags = 0; Debug.Assert(rval != null); return (rval); } public EXPRHOISTEDLOCALEXPR CreateHoistedLocalInExpression(EXPRLOCAL localToHoist) { Debug.Assert(localToHoist != null); EXPRHOISTEDLOCALEXPR rval = new EXPRHOISTEDLOCALEXPR(); rval.kind = ExpressionKind.EK_HOISTEDLOCALEXPR; rval.type = GetTypes().GetOptPredefAgg(PredefinedType.PT_EXPRESSION).getThisType(); rval.flags = 0; return rval; } public EXPRMETHODINFO CreateMethodInfo(MethPropWithInst mwi) { return CreateMethodInfo(mwi.Meth(), mwi.GetType(), mwi.TypeArgs); } public EXPRMETHODINFO CreateMethodInfo(MethodSymbol method, AggregateType methodType, TypeArray methodParameters) { Debug.Assert(method != null); Debug.Assert(methodType != null); EXPRMETHODINFO methodInfo = new EXPRMETHODINFO(); CType type; if (method.IsConstructor()) { type = GetTypes().GetOptPredefAgg(PredefinedType.PT_CONSTRUCTORINFO).getThisType(); } else { type = GetTypes().GetOptPredefAgg(PredefinedType.PT_METHODINFO).getThisType(); } methodInfo.kind = ExpressionKind.EK_METHODINFO; methodInfo.type = type; methodInfo.flags = 0; methodInfo.Method = new MethWithInst(method, methodType, methodParameters); return methodInfo; } public EXPRPropertyInfo CreatePropertyInfo(PropertySymbol prop, AggregateType propertyType) { Debug.Assert(prop != null); Debug.Assert(propertyType != null); EXPRPropertyInfo propInfo = new EXPRPropertyInfo(); propInfo.kind = ExpressionKind.EK_PROPERTYINFO; propInfo.type = GetTypes().GetOptPredefAgg(PredefinedType.PT_PROPERTYINFO).getThisType(); propInfo.flags = 0; propInfo.Property = new PropWithType(prop, propertyType); return propInfo; } public EXPRFIELDINFO CreateFieldInfo(FieldSymbol field, AggregateType fieldType) { Debug.Assert(field != null); Debug.Assert(fieldType != null); EXPRFIELDINFO rval = new EXPRFIELDINFO(); rval.kind = ExpressionKind.EK_FIELDINFO; rval.type = GetTypes().GetOptPredefAgg(PredefinedType.PT_FIELDINFO).getThisType(); rval.flags = 0; rval.Init(field, fieldType); return rval; } private EXPRTYPEOF CreateTypeOf(EXPRTYPEORNAMESPACE pSourceType) { EXPRTYPEOF rval = new EXPRTYPEOF(); rval.kind = ExpressionKind.EK_TYPEOF; rval.type = GetTypes().GetReqPredefAgg(PredefinedType.PT_TYPE).getThisType(); rval.flags = EXPRFLAG.EXF_CANTBENULL; rval.SetSourceType(pSourceType); Debug.Assert(rval != null); return (rval); } public EXPRTYPEOF CreateTypeOf(CType pSourceType) { return CreateTypeOf(MakeClass(pSourceType)); } public EXPRUSERLOGOP CreateUserLogOp(CType pType, EXPR pCallTF, EXPRCALL pCallOp) { Debug.Assert(pCallTF != null); Debug.Assert(pCallOp != null); Debug.Assert(pCallOp.GetOptionalArguments() != null); Debug.Assert(pCallOp.GetOptionalArguments().isLIST()); Debug.Assert(pCallOp.GetOptionalArguments().asLIST().GetOptionalElement() != null); EXPRUSERLOGOP rval = new EXPRUSERLOGOP(); EXPR leftChild = pCallOp.GetOptionalArguments().asLIST().GetOptionalElement(); Debug.Assert(leftChild != null); if (leftChild.isWRAP()) { // In the EE case, we don't create WRAPEXPRs. leftChild = leftChild.asWRAP().GetOptionalExpression(); Debug.Assert(leftChild != null); } rval.kind = ExpressionKind.EK_USERLOGOP; rval.type = pType; rval.flags = EXPRFLAG.EXF_ASSGOP; rval.TrueFalseCall = pCallTF; rval.OperatorCall = pCallOp; rval.FirstOperandToExamine = leftChild; Debug.Assert(rval != null); return (rval); } public EXPRUSERLOGOP CreateUserLogOpError(CType pType, EXPR pCallTF, EXPRCALL pCallOp) { EXPRUSERLOGOP rval = CreateUserLogOp(pType, pCallTF, pCallOp); rval.SetError(); return rval; } public EXPRCONCAT CreateConcat(EXPR op1, EXPR op2) { Debug.Assert(op1?.type != null); Debug.Assert(op2?.type != null); Debug.Assert(op1.type.isPredefType(PredefinedType.PT_STRING) || op2.type.isPredefType(PredefinedType.PT_STRING)); CType type = op1.type; if (!type.isPredefType(PredefinedType.PT_STRING)) { type = op2.type; } Debug.Assert(type.isPredefType(PredefinedType.PT_STRING)); EXPRCONCAT rval = new EXPRCONCAT(); rval.kind = ExpressionKind.EK_CONCAT; rval.type = type; rval.flags = 0; rval.SetFirstArgument(op1); rval.SetSecondArgument(op2); Debug.Assert(rval != null); return (rval); } public EXPRCONSTANT CreateStringConstant(string str) { return CreateConstant(GetTypes().GetReqPredefAgg(PredefinedType.PT_STRING).getThisType(), _constants.Create(str)); } public EXPRMULTIGET CreateMultiGet(EXPRFLAG nFlags, CType pType, EXPRMULTI pOptionalMulti) { Debug.Assert(0 == (nFlags & ~(EXPRFLAG.EXF_MASK_ANY))); EXPRMULTIGET rval = new EXPRMULTIGET(); rval.kind = ExpressionKind.EK_MULTIGET; rval.type = pType; rval.flags = nFlags; rval.SetOptionalMulti(pOptionalMulti); Debug.Assert(rval != null); return (rval); } public EXPRMULTI CreateMulti(EXPRFLAG nFlags, CType pType, EXPR pLeft, EXPR pOp) { Debug.Assert(pLeft != null); Debug.Assert(pOp != null); EXPRMULTI rval = new EXPRMULTI(); rval.kind = ExpressionKind.EK_MULTI; rval.type = pType; rval.flags = nFlags; rval.SetLeft(pLeft); rval.SetOperator(pOp); Debug.Assert(rval != null); return (rval); } //////////////////////////////////////////////////////////////////////////////// // // Precondition: // // pType - Non-null // // This returns a null for reference types and an EXPRZEROINIT for all others. public EXPR CreateZeroInit(CType pType) { EXPRCLASS exprClass = MakeClass(pType); return CreateZeroInit(exprClass); } private EXPR CreateZeroInit(EXPRTYPEORNAMESPACE pTypeExpr) { return CreateZeroInit(pTypeExpr, null, false); } private EXPR CreateZeroInit(EXPRTYPEORNAMESPACE pTypeExpr, EXPR pOptionalOriginalConstructorCall, bool isConstructor) { Debug.Assert(pTypeExpr != null); CType pType = pTypeExpr.TypeOrNamespace.AsType(); bool bIsError = false; if (pType.isEnumType()) { // For enum types, we create a constant that has the default value // as an object pointer. ConstValFactory factory = new ConstValFactory(); EXPRCONSTANT expr = CreateConstant(pType, factory.Create(Activator.CreateInstance(pType.AssociatedSystemType))); return expr; } switch (pType.fundType()) { default: bIsError = true; break; case FUNDTYPE.FT_PTR: { CType nullType = GetTypes().GetNullType(); // It looks like this if is always false ... if (nullType.fundType() == pType.fundType()) { // Create a constant here. EXPRCONSTANT expr = CreateConstant(pType, ConstValFactory.GetDefaultValue(ConstValKind.IntPtr)); return (expr); } // Just allocate a new node and fill it in. EXPRCAST cast = CreateCast(0, pTypeExpr, CreateNull()); return (cast); } case FUNDTYPE.FT_REF: case FUNDTYPE.FT_I1: case FUNDTYPE.FT_U1: case FUNDTYPE.FT_I2: case FUNDTYPE.FT_U2: case FUNDTYPE.FT_I4: case FUNDTYPE.FT_U4: case FUNDTYPE.FT_I8: case FUNDTYPE.FT_U8: case FUNDTYPE.FT_R4: case FUNDTYPE.FT_R8: { EXPRCONSTANT expr = CreateConstant(pType, ConstValFactory.GetDefaultValue(pType.constValKind())); EXPRCONSTANT exprInOriginal = CreateConstant(pType, ConstValFactory.GetDefaultValue(pType.constValKind())); exprInOriginal.SetOptionalConstructorCall(pOptionalOriginalConstructorCall); return expr; } case FUNDTYPE.FT_STRUCT: if (pType.isPredefType(PredefinedType.PT_DECIMAL)) { EXPRCONSTANT expr = CreateConstant(pType, ConstValFactory.GetDefaultValue(pType.constValKind())); EXPRCONSTANT exprOriginal = CreateConstant(pType, ConstValFactory.GetDefaultValue(pType.constValKind())); exprOriginal.SetOptionalConstructorCall(pOptionalOriginalConstructorCall); return expr; } break; case FUNDTYPE.FT_VAR: break; } EXPRZEROINIT rval = new EXPRZEROINIT(); rval.kind = ExpressionKind.EK_ZEROINIT; rval.type = pType; rval.flags = 0; rval.OptionalConstructorCall = pOptionalOriginalConstructorCall; rval.IsConstructor = isConstructor; if (bIsError) { rval.SetError(); } Debug.Assert(rval != null); return (rval); } public EXPRCONSTANT CreateConstant(CType pType, CONSTVAL constVal) { return CreateConstant(pType, constVal, null); } private EXPRCONSTANT CreateConstant(CType pType, CONSTVAL constVal, EXPR pOriginal) { EXPRCONSTANT rval = CreateConstant(pType); rval.setVal(constVal); Debug.Assert(rval != null); return (rval); } private EXPRCONSTANT CreateConstant(CType pType) { EXPRCONSTANT rval = new EXPRCONSTANT(); rval.kind = ExpressionKind.EK_CONSTANT; rval.type = pType; rval.flags = 0; return rval; } public EXPRCONSTANT CreateIntegerConstant(int x) { return CreateConstant(GetTypes().GetReqPredefAgg(PredefinedType.PT_INT).getThisType(), ConstValFactory.GetInt(x)); } public EXPRCONSTANT CreateBoolConstant(bool b) { return CreateConstant(GetTypes().GetReqPredefAgg(PredefinedType.PT_BOOL).getThisType(), ConstValFactory.GetBool(b)); } public EXPRBLOCK CreateBlock(EXPRBLOCK pOptionalCurrentBlock, EXPRSTMT pOptionalStatements, Scope pOptionalScope) { EXPRBLOCK rval = new EXPRBLOCK(); rval.kind = ExpressionKind.EK_BLOCK; rval.type = null; rval.flags = 0; rval.SetOptionalStatements(pOptionalStatements); rval.OptionalScopeSymbol = pOptionalScope; Debug.Assert(rval != null); return (rval); } public EXPRQUESTIONMARK CreateQuestionMark(EXPR pTestExpression, EXPRBINOP pConsequence) { Debug.Assert(pTestExpression != null); Debug.Assert(pConsequence != null); CType pType = pConsequence.type; if (pType == null) { Debug.Assert(pConsequence.GetOptionalLeftChild() != null); pType = pConsequence.GetOptionalLeftChild().type; Debug.Assert(pType != null); } EXPRQUESTIONMARK pResult = new EXPRQUESTIONMARK(); pResult.kind = ExpressionKind.EK_QUESTIONMARK; pResult.type = pType; pResult.flags = 0; pResult.SetTestExpression(pTestExpression); pResult.SetConsequence(pConsequence); Debug.Assert(pResult != null); return pResult; } public EXPRARRAYINDEX CreateArrayIndex(EXPR pArray, EXPR pIndex) { CType pType = pArray.type; if (pType != null && pType.IsArrayType()) { pType = pType.AsArrayType().GetElementType(); } else if (pType == null) { pType = GetTypes().GetReqPredefAgg(PredefinedType.PT_INT).getThisType(); } EXPRARRAYINDEX pResult = new EXPRARRAYINDEX(); pResult.kind = ExpressionKind.EK_ARRAYINDEX; pResult.type = pType; pResult.flags = 0; pResult.SetArray(pArray); pResult.SetIndex(pIndex); return pResult; } public EXPRARRAYLENGTH CreateArrayLength(EXPR pArray) { EXPRARRAYLENGTH pResult = new EXPRARRAYLENGTH(); pResult.kind = ExpressionKind.EK_ARRAYLENGTH; pResult.type = GetTypes().GetReqPredefAgg(PredefinedType.PT_INT).getThisType(); pResult.flags = 0; pResult.SetArray(pArray); return pResult; } public EXPRBINOP CreateBinop(ExpressionKind exprKind, CType pType, EXPR p1, EXPR p2) { //Debug.Assert(exprKind.isBinaryOperator()); EXPRBINOP rval = new EXPRBINOP(); rval.kind = exprKind; rval.type = pType; rval.flags = EXPRFLAG.EXF_BINOP; rval.SetOptionalLeftChild(p1); rval.SetOptionalRightChild(p2); rval.isLifted = false; rval.SetOptionalUserDefinedCall(null); rval.SetUserDefinedCallMethod(null); Debug.Assert(rval != null); return (rval); } public EXPRUNARYOP CreateUnaryOp(ExpressionKind exprKind, CType pType, EXPR pOperand) { Debug.Assert(exprKind.isUnaryOperator()); Debug.Assert(pOperand != null); EXPRUNARYOP rval = new EXPRUNARYOP(); rval.kind = exprKind; rval.type = pType; rval.flags = 0; rval.Child = pOperand; rval.OptionalUserDefinedCall = null; rval.UserDefinedCallMethod = null; Debug.Assert(rval != null); return (rval); } public EXPR CreateOperator(ExpressionKind exprKind, CType pType, EXPR pArg1, EXPR pOptionalArg2) { Debug.Assert(pArg1 != null); EXPR rval = null; if (exprKind.isUnaryOperator()) { Debug.Assert(pOptionalArg2 == null); rval = CreateUnaryOp(exprKind, pType, pArg1); } else rval = CreateBinop(exprKind, pType, pArg1, pOptionalArg2); Debug.Assert(rval != null); return rval; } public EXPRBINOP CreateUserDefinedBinop(ExpressionKind exprKind, CType pType, EXPR p1, EXPR p2, EXPR call, MethPropWithInst pmpwi) { Debug.Assert(p1 != null); Debug.Assert(p2 != null); Debug.Assert(call != null); EXPRBINOP rval = new EXPRBINOP(); rval.kind = exprKind; rval.type = pType; rval.flags = EXPRFLAG.EXF_BINOP; rval.SetOptionalLeftChild(p1); rval.SetOptionalRightChild(p2); // The call may be lifted, but we do not mark the outer binop as lifted. rval.isLifted = false; rval.SetOptionalUserDefinedCall(call); rval.SetUserDefinedCallMethod(pmpwi); if (call.HasError()) { rval.SetError(); } Debug.Assert(rval != null); return (rval); } public EXPRUNARYOP CreateUserDefinedUnaryOperator(ExpressionKind exprKind, CType pType, EXPR pOperand, EXPR call, MethPropWithInst pmpwi) { Debug.Assert(pType != null); Debug.Assert(pOperand != null); Debug.Assert(call != null); Debug.Assert(pmpwi != null); EXPRUNARYOP rval = new EXPRUNARYOP(); rval.kind = exprKind; rval.type = pType; rval.flags = 0; rval.Child = pOperand; // The call may be lifted, but we do not mark the outer binop as lifted. rval.OptionalUserDefinedCall = call; rval.UserDefinedCallMethod = pmpwi; if (call.HasError()) { rval.SetError(); } Debug.Assert(rval != null); return (rval); } public EXPRUNARYOP CreateNeg(EXPRFLAG nFlags, EXPR pOperand) { Debug.Assert(pOperand != null); EXPRUNARYOP pUnaryOp = CreateUnaryOp(ExpressionKind.EK_NEG, pOperand.type, pOperand); pUnaryOp.flags |= nFlags; return pUnaryOp; } //////////////////////////////////////////////////////////////////////////////// // Create a node that evaluates the first, evaluates the second, results in the second. public EXPRBINOP CreateSequence(EXPR p1, EXPR p2) { Debug.Assert(p1 != null); Debug.Assert(p2 != null); return CreateBinop(ExpressionKind.EK_SEQUENCE, p2.type, p1, p2); } //////////////////////////////////////////////////////////////////////////////// // Create a node that evaluates the first, evaluates the second, results in the first. public EXPRBINOP CreateReverseSequence(EXPR p1, EXPR p2) { Debug.Assert(p1 != null); Debug.Assert(p2 != null); return CreateBinop(ExpressionKind.EK_SEQREV, p1.type, p1, p2); } public EXPRASSIGNMENT CreateAssignment(EXPR pLHS, EXPR pRHS) { EXPRASSIGNMENT pAssignment = new EXPRASSIGNMENT(); pAssignment.kind = ExpressionKind.EK_ASSIGNMENT; pAssignment.type = pLHS.type; pAssignment.flags = EXPRFLAG.EXF_ASSGOP; pAssignment.SetLHS(pLHS); pAssignment.SetRHS(pRHS); return pAssignment; } //////////////////////////////////////////////////////////////////////////////// public EXPRNamedArgumentSpecification CreateNamedArgumentSpecification(Name pName, EXPR pValue) { EXPRNamedArgumentSpecification pResult = new EXPRNamedArgumentSpecification(); pResult.kind = ExpressionKind.EK_NamedArgumentSpecification; pResult.type = pValue.type; pResult.flags = 0; pResult.Value = pValue; pResult.Name = pName; return pResult; } public EXPRWRAP CreateWrap( Scope pCurrentScope, EXPR pOptionalExpression ) { EXPRWRAP rval = new EXPRWRAP(); rval.kind = ExpressionKind.EK_WRAP; rval.type = null; rval.flags = 0; rval.SetOptionalExpression(pOptionalExpression); if (pOptionalExpression != null) { rval.setType(pOptionalExpression.type); } rval.flags |= EXPRFLAG.EXF_LVALUE; Debug.Assert(rval != null); return (rval); } public EXPRWRAP CreateWrapNoAutoFree(Scope pCurrentScope, EXPR pOptionalWrap) { EXPRWRAP rval = CreateWrap(pCurrentScope, pOptionalWrap); return rval; } public EXPRBINOP CreateSave(EXPRWRAP wrap) { Debug.Assert(wrap != null); EXPRBINOP expr = CreateBinop(ExpressionKind.EK_SAVE, wrap.type, wrap.GetOptionalExpression(), wrap); expr.setAssignment(); return expr; } public EXPR CreateNull() { return CreateConstant(GetTypes().GetNullType(), ConstValFactory.GetNullRef()); } public void AppendItemToList( EXPR newItem, ref EXPR first, ref EXPR last ) { if (newItem == null) { // Nothing changes. return; } if (first == null) { Debug.Assert(last == first); first = newItem; last = newItem; return; } if (first.kind != ExpressionKind.EK_LIST) { Debug.Assert(last == first); first = CreateList(first, newItem); last = first; return; } Debug.Assert(last.kind == ExpressionKind.EK_LIST); Debug.Assert(last.asLIST().OptionalNextListNode != null); Debug.Assert(last.asLIST().OptionalNextListNode.kind != ExpressionKind.EK_LIST); last.asLIST().OptionalNextListNode = CreateList(last.asLIST().OptionalNextListNode, newItem); last = last.asLIST().OptionalNextListNode; } public EXPRLIST CreateList(EXPR op1, EXPR op2) { EXPRLIST rval = new EXPRLIST(); rval.kind = ExpressionKind.EK_LIST; rval.type = null; rval.flags = 0; rval.SetOptionalElement(op1); rval.SetOptionalNextListNode(op2); Debug.Assert(rval != null); return (rval); } public EXPRLIST CreateList(EXPR op1, EXPR op2, EXPR op3) { return CreateList(op1, CreateList(op2, op3)); } public EXPRLIST CreateList(EXPR op1, EXPR op2, EXPR op3, EXPR op4) { return CreateList(op1, CreateList(op2, CreateList(op3, op4))); } public EXPRTYPEARGUMENTS CreateTypeArguments(TypeArray pTypeArray, EXPR pOptionalElements) { Debug.Assert(pTypeArray != null); EXPRTYPEARGUMENTS rval = new EXPRTYPEARGUMENTS(); rval.kind = ExpressionKind.EK_TYPEARGUMENTS; rval.type = null; rval.flags = 0; rval.SetOptionalElements(pOptionalElements); return rval; } public EXPRCLASS CreateClass(CType pType, EXPR pOptionalLHS, EXPRTYPEARGUMENTS pOptionalTypeArguments) { Debug.Assert(pType != null); EXPRCLASS rval = new EXPRCLASS(); rval.kind = ExpressionKind.EK_CLASS; rval.type = pType; rval.TypeOrNamespace = pType; Debug.Assert(rval != null); return (rval); } public EXPRCLASS MakeClass(CType pType) { Debug.Assert(pType != null); return CreateClass(pType, null/* LHS */, null/* type arguments */); } } }
//! \file ImagePX.cs //! \date Thu Aug 18 05:35:34 2016 //! \brief Leaf image format. // // Copyright (C) 2016 by morkt // // 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.ComponentModel.Composition; using System.IO; using System.Windows.Media; using System.Windows.Media.Imaging; using GameRes.Utility; namespace GameRes.Formats.Leaf { internal class PxMetaData : ImageMetaData { public int Type; public int FrameCount; public int BlockSize; public int BlocksWidth; public int BlocksHeight; } // XXX this format changes significantly from game to game [Export(typeof(ImageFormat))] public class PxFormat : ImageFormat { public override string Tag { get { return "PX"; } } public override string Description { get { return "Leaf image format"; } } public override uint Signature { get { return 0; } } public override ImageMetaData ReadMetaData (IBinaryStream stream) { var header = stream.ReadHeader (0x20); int type = header.ToUInt16 (0x10); if (0x0C == type) { int count = header.ToInt32 (0); if (!ArchiveFormat.IsSaneCount (count)) return null; int block_size = header.ToInt32 (4); if (block_size <= 0) return null; int bpp = header.ToUInt16 (0x12); uint width = header.ToUInt16 (0x14); uint height = header.ToUInt16 (0x16); if (bpp != 32 || 0 == width || 0 == height) return null; return new PxMetaData { Width = width, Height = height, BPP = bpp, Type = type, FrameCount = count, BlockSize = block_size, BlocksWidth = header.ToUInt16 (0x1C), BlocksHeight = header.ToUInt16 (0x1E), }; } else if (0x90 == type) { if (!header.AsciiEqual (0x14, "Leaf")) return null; int count = header.ToInt32 (4); if (!ArchiveFormat.IsSaneCount (count)) return null; var header_ex = stream.ReadBytes (0x20); if (0x20 != header_ex.Length) return null; if (0x0A != LittleEndian.ToUInt16 (header_ex, 0x10)) return null; return new PxMetaData { Width = LittleEndian.ToUInt32 (header_ex, 0), Height = LittleEndian.ToUInt32 (header_ex, 4), BPP = LittleEndian.ToUInt16 (header_ex, 0x12), Type = type, FrameCount = count, }; } else if (0x40 == type || 0x44 == type) { int count = header.ToInt32 (0); if (!ArchiveFormat.IsSaneCount (count)) return null; return new PxMetaData { Width = header.ToUInt32 (0x14), Height = header.ToUInt32 (0x18), Type = 0x40, BPP = 32, FrameCount = count, }; } else if (1 == type || 4 == type || 7 == type) { int bpp = header.ToUInt16 (0x12); if (bpp != 32 && bpp != 8) return null; return new PxMetaData { Width = header.ToUInt32 (0x14), Height = header.ToUInt32 (0x18), Type = type, BPP = bpp, FrameCount = 1, }; } return null; } public override ImageData Read (IBinaryStream stream, ImageMetaData info) { using (var reader = new PxReader (stream, (PxMetaData)info)) { var pixels = reader.Unpack(); return ImageData.Create (info, reader.Format, reader.Palette, pixels, reader.Stride); } } public override void Write (Stream file, ImageData image) { throw new System.NotImplementedException ("PxFormat.Write not implemented"); } } internal sealed class PxReader : IDisposable { IBinaryStream m_input; PxMetaData m_info; byte[] m_output; int m_pixel_size; int m_stride; public PixelFormat Format { get; private set; } public byte[] Data { get { return m_output; } } public int Stride { get { return m_stride; } } public int FrameCount { get { return m_info.FrameCount; } } public BitmapPalette Palette { get; private set; } public PxReader (IBinaryStream input, PxMetaData info) { m_input = input; m_info = info; m_pixel_size = m_info.BPP / 8; m_stride = (int)m_info.Width * m_pixel_size; m_output = new byte[m_stride * (int)m_info.Height]; if (1 == m_pixel_size) Format = PixelFormats.Gray8; else Format = PixelFormats.Bgra32; } public byte[] Unpack (int frame = 0) { if (frame < 0 || frame >= FrameCount) throw new ArgumentException ("[PX] Invalid frame number", "frame"); switch (m_info.Type) { case 0x0C: Unpack0C (frame); break; case 0x90: Unpack90 (frame); break; case 0x40: Unpack40(); break; default: ReadBlock (0); break; } return m_output; } void Unpack0C (int frame) { int block_count = m_info.BlocksWidth * m_info.BlocksHeight; var block_table = new ushort[block_count]; m_input.Position = 0x20 + frame * block_count * 2; for (int i = 0; i < block_count; ++i) block_table[i] = m_input.ReadUInt16(); int data_pos = 0x20 + FrameCount * block_count * 2; int block_length = 2 + (m_info.BlockSize + 2) * (m_info.BlockSize + 2) * m_pixel_size; int current_block = 0; int dst_line = 0; for (int by = 0; by < m_info.BlocksHeight; ++by) { for (int bx = 0; bx < m_info.BlocksWidth; ++bx) { int dst = dst_line + bx * m_info.BlockSize * m_pixel_size; int block_num = block_table[current_block++]; if (block_num != 0) { m_input.Position = data_pos + (block_num - 1) * block_length; int block_width = m_input.ReadByte() - 2; int block_height = m_input.ReadByte() - 2; int line_length = block_width * m_pixel_size; for (int y = 0; y < block_height; ++y) { m_input.Read (m_output, dst, line_length); dst += m_stride; m_input.Seek (8, SeekOrigin.Current); } } } dst_line += m_info.BlockSize * m_stride; } } void Unpack90 (int frame) { m_input.Position = 0x40 + frame * (0x20 + m_output.Length); if (m_output.Length != m_input.Read (m_output, 0, m_output.Length)) throw new EndOfStreamException(); } void Unpack40 () { m_input.Position = 0x20; uint data_offset = 0x20 + (uint)m_info.FrameCount * 4; var offsets = new uint[m_info.FrameCount]; for (int i = 0; i < offsets.Length; ++i) offsets[i] = data_offset + m_input.ReadUInt32(); foreach (var offset in offsets) ReadBlock (offset); } internal class PxBlock { public int Width; public int Height; public int X; public int Y; public int Type; public int Bits; } void ReadBlock (uint offset) { m_input.Position = offset; var px = new PxBlock(); px.Width = m_input.ReadInt32(); px.Height = m_input.ReadInt32(); px.X = m_input.ReadInt32(); px.Y = m_input.ReadInt32(); px.Type = m_input.ReadUInt16(); px.Bits = m_input.ReadUInt16(); m_input.Position = offset + 0x20; switch (px.Type) { case 0: Palette = ImageFormat.ReadPalette (m_input.AsStream, (int)px.Width); break; case 1: switch (px.Bits) { case 8: UnpackBlock_1_8 (px); break; case 0x20: UnpackBlock_1_20 (px); break; } break; case 4: switch (px.Bits) { case 8: UnpackBlock_4_8 (px); break; case 9: UnpackBlock_4_9 (px); break; case 0x20: UnpackBlock_4_20 (px); break; case 0x30: UnpackBlock_4_30 (px); break; } break; case 7: UnpackBlock_7 (px); break; default: throw new InvalidFormatException(); } } void UnpackBlock_1_8 (PxBlock block) { m_input.Read (m_output, 0, (int)m_info.Width * (int)m_info.Height); } void UnpackBlock_1_20 (PxBlock block) { int dst = 0; for (int y = 0; y < block.Height; ++y) for (int x = 0; x < block.Width; ++x) { m_input.Read (m_output, dst, 4); if (0 != m_output[dst+3]) { byte alpha = (byte)((m_output[dst+3] << 1 | m_output[dst+2] >> 7) + 0xFF); m_output[dst+3] = alpha; } else { m_output[dst+3] = 0xFF; } dst += 4; } } void UnpackBlock_4_8 (PxBlock block) { throw new NotImplementedException(); } const int MaxBlockSize = 1024; // lazily evaluated to avoid unnecessary allocation Lazy<uint[]> m_block = new Lazy<uint[]> (() => new uint[MaxBlockSize * MaxBlockSize]); uint[] NewBlock (PxBlock block_info) { var block = m_block.Value; Array.Clear (block, 0, MaxBlockSize * block_info.Height); return block; } void UnpackBlock_4_9 (PxBlock block_info) { var output = NewBlock (block_info); int dst = 0; bool has_alpha = true; for (;;) { int code = m_input.ReadInt32(); if (-1 == code) break; if (0 != (code & 0x180000)) has_alpha = !has_alpha; dst += (code & 0x1FF) * MaxBlockSize; dst += code >> 21; int count = (code >> 9) & 0x3FF; for (int i = 0; i < count; ++i) { byte alpha = (byte)(has_alpha ? (m_input.ReadUInt8() << 1) - 1 : 0xFF); int color_idx = m_input.ReadByte(); if (dst < output.Length) { var color = Palette.Colors[color_idx]; output[dst] = (uint)(color.B | color.G << 8 | color.R << 16 | alpha << 24); } dst++; } } PutBlock (block_info); } void UnpackBlock_4_20 (PxBlock block_info) { var block = NewBlock (block_info); int dst = 0; int next; while ((next = m_input.ReadInt32()) != -1) { if (next < 0 || next > 0xFFFFFF) continue; dst += next / 4; m_input.ReadInt32(); int count = m_input.ReadInt32(); while (count --> 0) { uint color = m_input.ReadUInt32(); if (dst < block.Length) { if (0 != (color & 0xFF000000)) { uint alpha = ((color >> 23) + 0xFF) << 24; block[dst] = (color & 0xFFFFFFu) | alpha; } else { block[dst] = color | 0xFF000000u; } } ++dst; } } PutBlock (block_info); } void UnpackBlock_4_30 (PxBlock block_info) { var output = NewBlock (block_info); int dst = 0; for (;;) { int next = m_input.ReadInt32(); if (-1 == next) break; if (0 != (next & 0xFF000000)) continue; dst += next / 4; m_input.ReadInt32(); int count = m_input.ReadInt32(); for (int i = 0; i < count; ++i) { uint color = m_input.ReadUInt32(); m_input.ReadInt16(); if (dst < output.Length) { if (0 != (color & 0xFF000000)) { uint alpha = ((color >> 23) + 0xFF) << 24; output[dst] = (color & 0xFFFFFF) | alpha; } else { output[dst] = 0; } } dst++; } } PutBlock (block_info); } void UnpackBlock_7 (PxBlock block) { m_stride = 4 * block.Width; m_output = new byte[m_stride * block.Height]; Format = PixelFormats.Bgra32; m_info.OffsetX = block.X; m_info.OffsetY = block.Y; int dst = 0; var color_map = ImageFormat.ReadColorMap (m_input.AsStream, 0x100, PaletteFormat.BgrA); for (int y = 0; y < block.Height; ++y) for (int x = 0; x < block.Width; ++x) { int idx = m_input.ReadUInt8(); var c = color_map[idx]; m_output[dst++] = c.B; m_output[dst++] = c.G; m_output[dst++] = c.R; if (c.A != 0) m_output[dst++] = (byte)((c.A << 1 | c.R >> 7) + 0xFF); else m_output[dst++] = 0xFF; } } void PutBlock (PxBlock block_info) { var block = m_block.Value; int left = Math.Max (0, block_info.X); int top = Math.Max (0, block_info.Y); int right = Math.Min (block_info.X + block_info.Width, (int)m_info.Width); int bottom = Math.Min (block_info.Y + block_info.Height, (int)m_info.Height); int dst_row = top * m_stride + left * 4; int row_size = (right - left) * 4; for (int y = top; y < bottom; ++y) { int src = (left - block_info.X) + (y - block_info.Y) * MaxBlockSize; Buffer.BlockCopy (block, src * 4, m_output, dst_row, row_size); dst_row += m_stride; } } #region IDisposable Members public void Dispose () { } #endregion } }
// 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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; using System.Threading; using System.Threading.Tasks; namespace System.IO.Pipes { public abstract partial class PipeStream : Stream { // The Windows implementation of PipeStream sets the stream's handle during // creation, and as such should always have a handle, but the Unix implementation // sometimes sets the handle not during creation but later during connection. // As such, validation during member access needs to verify a valid handle on // Windows, but can't assume a valid handle on Unix. internal const bool CheckOperationsRequiresSetHandle = false; private static readonly string PipeDirectoryPath = Path.Combine(Path.GetTempPath(), "corefxnamedpipes"); internal static string GetPipePath(string serverName, string pipeName) { if (serverName != "." && serverName != Interop.libc.gethostname()) { // Cross-machine pipes are not supported. throw new PlatformNotSupportedException(); } if (pipeName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { // Since pipes are stored as files in the file system, we don't support // pipe names that are actually paths or that otherwise have invalid // filename characters in them. throw new PlatformNotSupportedException(); } // Make sure we have the directory in which to put the pipe paths while (true) { int result = Interop.libc.mkdir(PipeDirectoryPath, (int)Interop.libc.Permissions.S_IRWXU); if (result >= 0) { // directory created break; } Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EINTR) { // I/O was interrupted, try again continue; } else if (errorInfo.Error == Interop.Error.EEXIST) { // directory already exists break; } else { throw Interop.GetExceptionForIoErrno(errorInfo, PipeDirectoryPath, isDirectory: true); } } // Return the pipe path return Path.Combine(PipeDirectoryPath, pipeName); } /// <summary>Throws an exception if the supplied handle does not represent a valid pipe.</summary> /// <param name="safePipeHandle">The handle to validate.</param> internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle) { SysCall(safePipeHandle, (fd, _, __) => { Interop.Sys.FileStatus status; int result = Interop.Sys.FStat(fd, out status); if (result == 0) { if ((status.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFIFO) { throw new IOException(SR.IO_InvalidPipeHandle); } } return result; }); } /// <summary>Initializes the handle to be used asynchronously.</summary> /// <param name="handle">The handle.</param> [SecurityCritical] private void InitializeAsyncHandle(SafePipeHandle handle) { // nop } private void UninitializeAsyncHandle() { // nop } [SecurityCritical] private unsafe int ReadCore(byte[] buffer, int offset, int count) { Debug.Assert(_handle != null, "_handle is null"); Debug.Assert(!_handle.IsClosed, "_handle is closed"); Debug.Assert(CanRead, "can't read"); Debug.Assert(buffer != null, "buffer is null"); Debug.Assert(offset >= 0, "offset is negative"); Debug.Assert(count >= 0, "count is negative"); fixed (byte* bufPtr = buffer) { return (int)SysCall(_handle, (fd, ptr, len) => { long result = (long)Interop.libc.read(fd, (byte*)ptr, (IntPtr)len); Debug.Assert(result <= len); return result; }, (IntPtr)(bufPtr + offset), count); } } [SecuritySafeCritical] private Task<int> ReadAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { // Delegate to the base Stream's ReadAsync, which will just invoke Read asynchronously. return base.ReadAsync(buffer, offset, count, cancellationToken); } [SecurityCritical] private unsafe void WriteCore(byte[] buffer, int offset, int count) { Debug.Assert(_handle != null, "_handle is null"); Debug.Assert(!_handle.IsClosed, "_handle is closed"); Debug.Assert(CanWrite, "can't write"); Debug.Assert(buffer != null, "buffer is null"); Debug.Assert(offset >= 0, "offset is negative"); Debug.Assert(count >= 0, "count is negative"); fixed (byte* bufPtr = buffer) { while (count > 0) { int bytesWritten = (int)SysCall(_handle, (fd, ptr, len) => { long result = (long)Interop.libc.write(fd, (byte*)ptr, (IntPtr)len); Debug.Assert(result <= len); return result; }, (IntPtr)(bufPtr + offset), count); count -= bytesWritten; offset += bytesWritten; } } } [SecuritySafeCritical] private Task WriteAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { // Delegate to the base Stream's WriteAsync, which will just invoke Write asynchronously. return base.WriteAsync(buffer, offset, count, cancellationToken); } // Blocks until the other end of the pipe has read in all written buffer. [SecurityCritical] public void WaitForPipeDrain() { CheckWriteOperations(); if (!CanWrite) { throw __Error.GetWriteNotSupported(); } throw new PlatformNotSupportedException(); // no mechanism for this on Unix } // Gets the transmission mode for the pipe. This is virtual so that subclassing types can // override this in cases where only one mode is legal (such as anonymous pipes) public virtual PipeTransmissionMode TransmissionMode { [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")] get { CheckPipePropertyOperations(); return PipeTransmissionMode.Byte; // Unix pipes are only byte-based, not message-based } } // Gets the buffer size in the inbound direction for the pipe. This checks if pipe has read // access. If that passes, call to GetNamedPipeInfo will succeed. public virtual int InBufferSize { [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] get { CheckPipePropertyOperations(); if (!CanRead) { throw new NotSupportedException(SR.NotSupported_UnreadableStream); } return InBufferSizeCore; } } // Gets the buffer size in the outbound direction for the pipe. This uses cached version // if it's an outbound only pipe because GetNamedPipeInfo requires read access to the pipe. // However, returning cached is good fallback, especially if user specified a value in // the ctor. public virtual int OutBufferSize { [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")] get { CheckPipePropertyOperations(); if (!CanWrite) { throw new NotSupportedException(SR.NotSupported_UnwritableStream); } return OutBufferSizeCore; } } public virtual PipeTransmissionMode ReadMode { [SecurityCritical] get { CheckPipePropertyOperations(); return PipeTransmissionMode.Byte; // Unix pipes are only byte-based, not message-based } [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")] set { CheckPipePropertyOperations(); if (value < PipeTransmissionMode.Byte || value > PipeTransmissionMode.Message) { throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_TransmissionModeByteOrMsg); } if (value != PipeTransmissionMode.Byte) // Unix pipes are only byte-based, not message-based { throw new PlatformNotSupportedException(); } // nop, since it's already the only valid value } } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- internal static Interop.libc.OpenFlags TranslateFlags(PipeDirection direction, PipeOptions options, HandleInheritability inheritability) { // Translate direction Interop.libc.OpenFlags flags = direction == PipeDirection.InOut ? Interop.libc.OpenFlags.O_RDWR : direction == PipeDirection.Out ? Interop.libc.OpenFlags.O_WRONLY : Interop.libc.OpenFlags.O_RDONLY; // Translate options if ((options & PipeOptions.WriteThrough) != 0) { flags |= Interop.libc.OpenFlags.O_SYNC; } // Translate inheritability. if ((inheritability & HandleInheritability.Inheritable) == 0) { flags |= Interop.libc.OpenFlags.O_CLOEXEC; } // PipeOptions.Asynchronous is ignored, at least for now. Asynchronous processing // is handling just by queueing a work item to do the work synchronously on a pool thread. return flags; } /// <summary> /// Helper for making system calls that involve the stream's file descriptor. /// System calls are expected to return greather than or equal to zero on success, /// and less than zero on failure. In the case of failure, errno is expected to /// be set to the relevant error code. /// </summary> /// <param name="sysCall">A delegate that invokes the system call.</param> /// <param name="arg1">The first argument to be passed to the system call, after the file descriptor.</param> /// <param name="arg2">The second argument to be passed to the system call.</param> /// <returns>The return value of the system call.</returns> /// <remarks> /// Arguments are expected to be passed via <paramref name="arg1"/> and <paramref name="arg2"/> /// so as to avoid delegate and closure allocations at the call sites. /// </remarks> private long SysCall( SafePipeHandle handle, Func<int, IntPtr, int, long> sysCall, IntPtr arg1 = default(IntPtr), int arg2 = default(int)) { bool gotRefOnHandle = false; try { // Get the file descriptor from the handle. We increment the ref count to help // ensure it's not closed out from under us. handle.DangerousAddRef(ref gotRefOnHandle); Debug.Assert(gotRefOnHandle); int fd = (int)handle.DangerousGetHandle(); Debug.Assert(fd >= 0); while (true) { long result = sysCall(fd, arg1, arg2); if (result < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EINTR) continue; if (errorInfo.Error == Interop.Error.EPIPE) State = PipeState.Broken; throw Interop.GetExceptionForIoErrno(errorInfo); } return result; } } finally { if (gotRefOnHandle) { handle.DangerousRelease(); } } } } }
using Content.Client.Atmos.Overlays; using Content.Shared.Atmos; using Content.Shared.Atmos.EntitySystems; using JetBrains.Annotations; using Robust.Client.Graphics; using Robust.Client.ResourceManagement; using Robust.Client.Utility; using Robust.Shared.Map; using Robust.Shared.Utility; namespace Content.Client.Atmos.EntitySystems { [UsedImplicitly] internal sealed class GasTileOverlaySystem : SharedGasTileOverlaySystem { [Dependency] private readonly IResourceCache _resourceCache = default!; [Dependency] private readonly AtmosphereSystem _atmosphereSystem = default!; // Gas overlays public readonly float[] Timer = new float[Atmospherics.TotalNumberOfGases]; public readonly float[][] FrameDelays = new float[Atmospherics.TotalNumberOfGases][]; public readonly int[] FrameCounter = new int[Atmospherics.TotalNumberOfGases]; public readonly Texture[][] Frames = new Texture[Atmospherics.TotalNumberOfGases][]; // Fire overlays public const int FireStates = 3; public const string FireRsiPath = "/Textures/Effects/fire.rsi"; public readonly float[] FireTimer = new float[FireStates]; public readonly float[][] FireFrameDelays = new float[FireStates][]; public readonly int[] FireFrameCounter = new int[FireStates]; public readonly Texture[][] FireFrames = new Texture[FireStates][]; private readonly Dictionary<GridId, Dictionary<Vector2i, GasOverlayChunk>> _tileData = new(); public const int GasOverlayZIndex = 1; public override void Initialize() { base.Initialize(); SubscribeNetworkEvent<GasOverlayMessage>(HandleGasOverlayMessage); SubscribeLocalEvent<GridRemovalEvent>(OnGridRemoved); for (var i = 0; i < Atmospherics.TotalNumberOfGases; i++) { var overlay = _atmosphereSystem.GetOverlay(i); switch (overlay) { case SpriteSpecifier.Rsi animated: var rsi = _resourceCache.GetResource<RSIResource>(animated.RsiPath).RSI; var stateId = animated.RsiState; if(!rsi.TryGetState(stateId, out var state)) continue; Frames[i] = state.GetFrames(RSI.State.Direction.South); FrameDelays[i] = state.GetDelays(); FrameCounter[i] = 0; break; case SpriteSpecifier.Texture texture: Frames[i] = new[] {texture.Frame0()}; FrameDelays[i] = Array.Empty<float>(); break; case null: Frames[i] = Array.Empty<Texture>(); FrameDelays[i] = Array.Empty<float>(); break; } } var fire = _resourceCache.GetResource<RSIResource>(FireRsiPath).RSI; for (var i = 0; i < FireStates; i++) { if (!fire.TryGetState((i+1).ToString(), out var state)) throw new ArgumentOutOfRangeException($"Fire RSI doesn't have state \"{i}\"!"); FireFrames[i] = state.GetFrames(RSI.State.Direction.South); FireFrameDelays[i] = state.GetDelays(); FireFrameCounter[i] = 0; } var overlayManager = IoCManager.Resolve<IOverlayManager>(); overlayManager.AddOverlay(new GasTileOverlay()); overlayManager.AddOverlay(new FireTileOverlay()); } private void HandleGasOverlayMessage(GasOverlayMessage message) { foreach (var (indices, data) in message.OverlayData) { var chunk = GetOrCreateChunk(message.GridId, indices); chunk.Update(data, indices); } } // Slightly different to the server-side system version private GasOverlayChunk GetOrCreateChunk(GridId gridId, Vector2i indices) { if (!_tileData.TryGetValue(gridId, out var chunks)) { chunks = new Dictionary<Vector2i, GasOverlayChunk>(); _tileData[gridId] = chunks; } var chunkIndices = GetGasChunkIndices(indices); if (!chunks.TryGetValue(chunkIndices, out var chunk)) { chunk = new GasOverlayChunk(gridId, chunkIndices); chunks[chunkIndices] = chunk; } return chunk; } public override void Shutdown() { base.Shutdown(); var overlayManager = IoCManager.Resolve<IOverlayManager>(); overlayManager.RemoveOverlay<GasTileOverlay>(); overlayManager.RemoveOverlay<FireTileOverlay>(); } private void OnGridRemoved(GridRemovalEvent ev) { if (_tileData.ContainsKey(ev.GridId)) { _tileData.Remove(ev.GridId); } } public bool HasData(GridId gridId) { return _tileData.ContainsKey(gridId); } public GasOverlayEnumerator GetOverlays(GridId gridIndex, Vector2i indices) { if (!_tileData.TryGetValue(gridIndex, out var chunks)) return default; var chunkIndex = GetGasChunkIndices(indices); if (!chunks.TryGetValue(chunkIndex, out var chunk)) return default; var overlays = chunk.GetData(indices); return new GasOverlayEnumerator(overlays, this); } public FireOverlayEnumerator GetFireOverlays(GridId gridIndex, Vector2i indices) { if (!_tileData.TryGetValue(gridIndex, out var chunks)) return default; var chunkIndex = GetGasChunkIndices(indices); if (!chunks.TryGetValue(chunkIndex, out var chunk)) return default; var overlays = chunk.GetData(indices); return new FireOverlayEnumerator(overlays, this); } public override void FrameUpdate(float frameTime) { base.FrameUpdate(frameTime); for (var i = 0; i < Atmospherics.TotalNumberOfGases; i++) { var delays = FrameDelays[i]; if (delays.Length == 0) continue; var frameCount = FrameCounter[i]; Timer[i] += frameTime; var time = delays[frameCount]; if (Timer[i] < time) continue; Timer[i] -= time; FrameCounter[i] = (frameCount + 1) % Frames[i].Length; } for (var i = 0; i < FireStates; i++) { var delays = FireFrameDelays[i]; if (delays.Length == 0) continue; var frameCount = FireFrameCounter[i]; FireTimer[i] += frameTime; var time = delays[frameCount]; if (FireTimer[i] < time) continue; FireTimer[i] -= time; FireFrameCounter[i] = (frameCount + 1) % FireFrames[i].Length; } } public struct GasOverlayEnumerator { private readonly GasTileOverlaySystem _system; private readonly GasData[]? _data; // TODO: Take Fire Temperature into account, when we code fire color private readonly int _length; // We cache the length so we can avoid a pointer dereference, for speed. Brrr. private int _current; public GasOverlayEnumerator(in GasOverlayData data, GasTileOverlaySystem system) { // Gas can't be null, as the caller to this constructor already ensured it wasn't. _data = data.Gas; _system = system; _length = _data?.Length ?? 0; _current = 0; } public bool MoveNext(out (Texture Texture, Color Color) overlay) { if (_current < _length) { // Data can't be null here unless length/current are incorrect var gas = _data![_current++]; var frames = _system.Frames[gas.Index]; overlay = (frames[_system.FrameCounter[gas.Index]], Color.White.WithAlpha(gas.Opacity)); return true; } overlay = default; return false; } } public struct FireOverlayEnumerator { private readonly GasTileOverlaySystem _system; private byte _fireState; // TODO: Take Fire Temperature into account, when we code fire color public FireOverlayEnumerator(in GasOverlayData data, GasTileOverlaySystem system) { _fireState = data.FireState; _system = system; } public bool MoveNext(out (Texture Texture, Color Color) overlay) { if (_fireState != 0) { var state = _fireState - 1; var frames = _system.FireFrames[state]; // TODO ATMOS Set color depending on temperature overlay = (frames[_system.FireFrameCounter[state]], Color.White); // Setting this to zero so we don't get stuck in an infinite loop. _fireState = 0; return true; } overlay = default; return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Text; using System.Threading; namespace System.Net.WebSockets { // This class helps to abstract the internal WebSocket buffer, which is used to interact with the native WebSocket // protocol component (WSPC). It helps to shield the details of the layout and the involved pointer arithmetic. // The internal WebSocket buffer also contains a segment, which is used by the WebSocketBase class to buffer // payload (parsed by WSPC already) for the application, if the application requested fewer bytes than the // WSPC returned. The internal buffer is pinned for the whole lifetime if this class. // LAYOUT: // | Native buffer | PayloadReceiveBuffer | PropertyBuffer | // | RBS + SBS + 144 | RBS | PBS | // | Only WSPC may modify | Only WebSocketBase may modify | // // *RBS = ReceiveBufferSize, *SBS = SendBufferSize // *PBS = PropertyBufferSize (32-bit: 16, 64 bit: 20 bytes) internal class WebSocketBuffer : IDisposable { private const int NativeOverheadBufferSize = 144; internal const int MinSendBufferSize = 16; internal const int MinReceiveBufferSize = 256; internal const int MaxBufferSize = 64 * 1024; private static readonly int s_PropertyBufferSize = 3 * sizeof(uint) + IntPtr.Size; private readonly int _receiveBufferSize; // Indicates the range of the pinned byte[] that can be used by the WSPC (nativeBuffer + pinnedSendBuffer) private readonly long _startAddress; private readonly long _endAddress; private readonly GCHandle _gcHandle; private readonly ArraySegment<byte> _internalBuffer; private readonly ArraySegment<byte> _nativeBuffer; private readonly ArraySegment<byte> _payloadBuffer; private readonly ArraySegment<byte> _propertyBuffer; private readonly int _sendBufferSize; private volatile int _payloadOffset; private volatile WebSocketReceiveResult _bufferedPayloadReceiveResult; private long _pinnedSendBufferStartAddress; private long _pinnedSendBufferEndAddress; private ArraySegment<byte> _pinnedSendBuffer; private GCHandle _pinnedSendBufferHandle; private int _stateWhenDisposing = int.MinValue; private int _sendBufferState; private WebSocketBuffer(ArraySegment<byte> internalBuffer, int receiveBufferSize, int sendBufferSize) { Debug.Assert(internalBuffer.Array != null, "'internalBuffer.Array' MUST NOT be NULL."); Debug.Assert(receiveBufferSize >= MinReceiveBufferSize, "'receiveBufferSize' MUST be at least " + MinReceiveBufferSize.ToString(NumberFormatInfo.InvariantInfo) + "."); Debug.Assert(sendBufferSize >= MinSendBufferSize, "'sendBufferSize' MUST be at least " + MinSendBufferSize.ToString(NumberFormatInfo.InvariantInfo) + "."); Debug.Assert(receiveBufferSize <= MaxBufferSize, "'receiveBufferSize' MUST NOT exceed " + MaxBufferSize.ToString(NumberFormatInfo.InvariantInfo) + "."); Debug.Assert(sendBufferSize <= MaxBufferSize, "'sendBufferSize' MUST NOT exceed " + MaxBufferSize.ToString(NumberFormatInfo.InvariantInfo) + "."); _receiveBufferSize = receiveBufferSize; _sendBufferSize = sendBufferSize; _internalBuffer = internalBuffer; _gcHandle = GCHandle.Alloc(internalBuffer.Array, GCHandleType.Pinned); // Size of the internal buffer owned exclusively by the WSPC. int nativeBufferSize = _receiveBufferSize + _sendBufferSize + NativeOverheadBufferSize; _startAddress = Marshal.UnsafeAddrOfPinnedArrayElement(internalBuffer.Array, internalBuffer.Offset).ToInt64(); _endAddress = _startAddress + nativeBufferSize; _nativeBuffer = new ArraySegment<byte>(internalBuffer.Array, internalBuffer.Offset, nativeBufferSize); _payloadBuffer = new ArraySegment<byte>(internalBuffer.Array, _nativeBuffer.Offset + _nativeBuffer.Count, _receiveBufferSize); _propertyBuffer = new ArraySegment<byte>(internalBuffer.Array, _payloadBuffer.Offset + _payloadBuffer.Count, s_PropertyBufferSize); _sendBufferState = SendBufferState.None; } public int ReceiveBufferSize { get { return _receiveBufferSize; } } public int SendBufferSize { get { return _sendBufferSize; } } internal static WebSocketBuffer CreateServerBuffer(ArraySegment<byte> internalBuffer, int receiveBufferSize) { int sendBufferSize = GetNativeSendBufferSize(MinSendBufferSize, true); Debug.Assert(internalBuffer.Count >= GetInternalBufferSize(receiveBufferSize, sendBufferSize, true), "Array 'internalBuffer' is TOO SMALL. Call Validate before instantiating WebSocketBuffer."); return new WebSocketBuffer(internalBuffer, receiveBufferSize, sendBufferSize); } public void Dispose(WebSocketState webSocketState) { if (Interlocked.CompareExchange(ref _stateWhenDisposing, (int)webSocketState, int.MinValue) != int.MinValue) { return; } this.CleanUp(); } public void Dispose() { this.Dispose(WebSocketState.None); } internal Interop.WebSocket.Property[] CreateProperties(bool useZeroMaskingKey) { ThrowIfDisposed(); // serialize marshaled property values in the property segment of the internal buffer // m_GCHandle.AddrOfPinnedObject() points to the address of m_InternalBuffer.Array IntPtr internalBufferPtr = _gcHandle.AddrOfPinnedObject(); int offset = _propertyBuffer.Offset; Marshal.WriteInt32(internalBufferPtr, offset, _receiveBufferSize); offset += sizeof(uint); Marshal.WriteInt32(internalBufferPtr, offset, _sendBufferSize); offset += sizeof(uint); Marshal.WriteIntPtr(internalBufferPtr, offset, internalBufferPtr + _internalBuffer.Offset); offset += IntPtr.Size; Marshal.WriteInt32(internalBufferPtr, offset, useZeroMaskingKey ? (int)1 : (int)0); int propertyCount = useZeroMaskingKey ? 4 : 3; Interop.WebSocket.Property[] properties = new Interop.WebSocket.Property[propertyCount]; // Calculate the pointers to the positions of the properties within the internal buffer offset = _propertyBuffer.Offset; properties[0] = new Interop.WebSocket.Property() { Type = WebSocketProtocolComponent.PropertyType.ReceiveBufferSize, PropertySize = (uint)sizeof(uint), PropertyData = IntPtr.Add(internalBufferPtr, offset) }; offset += sizeof(uint); properties[1] = new Interop.WebSocket.Property() { Type = WebSocketProtocolComponent.PropertyType.SendBufferSize, PropertySize = (uint)sizeof(uint), PropertyData = IntPtr.Add(internalBufferPtr, offset) }; offset += sizeof(uint); properties[2] = new Interop.WebSocket.Property() { Type = WebSocketProtocolComponent.PropertyType.AllocatedBuffer, PropertySize = (uint)_nativeBuffer.Count, PropertyData = IntPtr.Add(internalBufferPtr, offset) }; offset += IntPtr.Size; if (useZeroMaskingKey) { properties[3] = new Interop.WebSocket.Property() { Type = WebSocketProtocolComponent.PropertyType.DisableMasking, PropertySize = (uint)sizeof(uint), PropertyData = IntPtr.Add(internalBufferPtr, offset) }; } return properties; } // This method is not thread safe. It must only be called after enforcing at most 1 outstanding send operation internal void PinSendBuffer(ArraySegment<byte> payload, out bool bufferHasBeenPinned) { bufferHasBeenPinned = false; WebSocketValidate.ValidateBuffer(payload.Array, payload.Offset, payload.Count); int previousState = Interlocked.Exchange(ref _sendBufferState, SendBufferState.SendPayloadSpecified); if (previousState != SendBufferState.None) { Debug.Assert(false, "'m_SendBufferState' MUST BE 'None' at this point."); // Indicates a violation in the API contract that could indicate // memory corruption because the pinned sendbuffer is shared between managed and native code throw new AccessViolationException(); } _pinnedSendBuffer = payload; _pinnedSendBufferHandle = GCHandle.Alloc(_pinnedSendBuffer.Array, GCHandleType.Pinned); bufferHasBeenPinned = true; _pinnedSendBufferStartAddress = Marshal.UnsafeAddrOfPinnedArrayElement(_pinnedSendBuffer.Array, _pinnedSendBuffer.Offset).ToInt64(); _pinnedSendBufferEndAddress = _pinnedSendBufferStartAddress + _pinnedSendBuffer.Count; } // This method is not thread safe. It must only be called after enforcing at most 1 outstanding send operation internal IntPtr ConvertPinnedSendPayloadToNative(ArraySegment<byte> payload) { return ConvertPinnedSendPayloadToNative(payload.Array, payload.Offset, payload.Count); } // This method is not thread safe. It must only be called after enforcing at most 1 outstanding send operation internal IntPtr ConvertPinnedSendPayloadToNative(byte[] buffer, int offset, int count) { if (!IsPinnedSendPayloadBuffer(buffer, offset, count)) { // Indicates a violation in the API contract that could indicate // memory corruption because the pinned sendbuffer is shared between managed and native code throw new AccessViolationException(); } Debug.Assert(Marshal.UnsafeAddrOfPinnedArrayElement(_pinnedSendBuffer.Array, _pinnedSendBuffer.Offset).ToInt64() == _pinnedSendBufferStartAddress, "'m_PinnedSendBuffer.Array' MUST be pinned during the entire send operation."); return new IntPtr(_pinnedSendBufferStartAddress + offset - _pinnedSendBuffer.Offset); } // This method is not thread safe. It must only be called after enforcing at most 1 outstanding send operation internal ArraySegment<byte> ConvertPinnedSendPayloadFromNative(Interop.WebSocket.Buffer buffer, WebSocketProtocolComponent.BufferType bufferType) { if (!IsPinnedSendPayloadBuffer(buffer, bufferType)) { // Indicates a violation in the API contract that could indicate // memory corruption because the pinned sendbuffer is shared between managed and native code throw new AccessViolationException(); } Debug.Assert(Marshal.UnsafeAddrOfPinnedArrayElement(_pinnedSendBuffer.Array, _pinnedSendBuffer.Offset).ToInt64() == _pinnedSendBufferStartAddress, "'m_PinnedSendBuffer.Array' MUST be pinned during the entire send operation."); IntPtr bufferData; uint bufferSize; UnwrapWebSocketBuffer(buffer, bufferType, out bufferData, out bufferSize); int internalOffset = (int)(bufferData.ToInt64() - _pinnedSendBufferStartAddress); return new ArraySegment<byte>(_pinnedSendBuffer.Array, _pinnedSendBuffer.Offset + internalOffset, (int)bufferSize); } // This method is not thread safe. It must only be called after enforcing at most 1 outstanding send operation private bool IsPinnedSendPayloadBuffer(byte[] buffer, int offset, int count) { if (_sendBufferState != SendBufferState.SendPayloadSpecified) { return false; } return object.ReferenceEquals(buffer, _pinnedSendBuffer.Array) && offset >= _pinnedSendBuffer.Offset && offset + count <= _pinnedSendBuffer.Offset + _pinnedSendBuffer.Count; } // This method is not thread safe. It must only be called after enforcing at most 1 outstanding send operation internal bool IsPinnedSendPayloadBuffer(Interop.WebSocket.Buffer buffer, WebSocketProtocolComponent.BufferType bufferType) { if (_sendBufferState != SendBufferState.SendPayloadSpecified) { return false; } IntPtr bufferData; uint bufferSize; UnwrapWebSocketBuffer(buffer, bufferType, out bufferData, out bufferSize); long nativeBufferStartAddress = bufferData.ToInt64(); long nativeBufferEndAddress = nativeBufferStartAddress + bufferSize; return nativeBufferStartAddress >= _pinnedSendBufferStartAddress && nativeBufferEndAddress >= _pinnedSendBufferStartAddress && nativeBufferStartAddress <= _pinnedSendBufferEndAddress && nativeBufferEndAddress <= _pinnedSendBufferEndAddress; } // This method is only thread safe for races between Abort and at most 1 uncompleted send operation internal void ReleasePinnedSendBuffer() { int previousState = Interlocked.Exchange(ref _sendBufferState, SendBufferState.None); if (previousState != SendBufferState.SendPayloadSpecified) { return; } if (_pinnedSendBufferHandle.IsAllocated) { _pinnedSendBufferHandle.Free(); } _pinnedSendBuffer = HttpWebSocket.EmptyPayload; } internal void BufferPayload(ArraySegment<byte> payload, int unconsumedDataOffset, WebSocketMessageType messageType, bool endOfMessage) { ThrowIfDisposed(); int bytesBuffered = payload.Count - unconsumedDataOffset; Debug.Assert(_payloadOffset == 0, "'m_PayloadOffset' MUST be '0' at this point."); Debug.Assert(_bufferedPayloadReceiveResult == null || _bufferedPayloadReceiveResult.Count == 0, "'m_BufferedPayloadReceiveResult.Count' MUST be '0' at this point."); Buffer.BlockCopy(payload.Array, payload.Offset + unconsumedDataOffset, _payloadBuffer.Array, _payloadBuffer.Offset, bytesBuffered); _bufferedPayloadReceiveResult = new WebSocketReceiveResult(bytesBuffered, messageType, endOfMessage); this.ValidateBufferedPayload(); } internal bool ReceiveFromBufferedPayload(ArraySegment<byte> buffer, out WebSocketReceiveResult receiveResult) { ThrowIfDisposed(); ValidateBufferedPayload(); int bytesTransferred = Math.Min(buffer.Count, _bufferedPayloadReceiveResult.Count); receiveResult = new WebSocketReceiveResult( bytesTransferred, _bufferedPayloadReceiveResult.MessageType, bytesTransferred == 0 && _bufferedPayloadReceiveResult.EndOfMessage, _bufferedPayloadReceiveResult.CloseStatus, _bufferedPayloadReceiveResult.CloseStatusDescription); Buffer.BlockCopy(_payloadBuffer.Array, _payloadBuffer.Offset + _payloadOffset, buffer.Array, buffer.Offset, bytesTransferred); bool morePayloadBuffered; if (_bufferedPayloadReceiveResult.Count == 0) { _payloadOffset = 0; _bufferedPayloadReceiveResult = null; morePayloadBuffered = false; } else { _payloadOffset += bytesTransferred; morePayloadBuffered = true; this.ValidateBufferedPayload(); } return morePayloadBuffered; } internal ArraySegment<byte> ConvertNativeBuffer(WebSocketProtocolComponent.Action action, Interop.WebSocket.Buffer buffer, WebSocketProtocolComponent.BufferType bufferType) { ThrowIfDisposed(); IntPtr bufferData; uint bufferLength; UnwrapWebSocketBuffer(buffer, bufferType, out bufferData, out bufferLength); if (bufferData == IntPtr.Zero) { return HttpWebSocket.EmptyPayload; } if (this.IsNativeBuffer(bufferData, bufferLength)) { return new ArraySegment<byte>(_internalBuffer.Array, this.GetOffset(bufferData), (int)bufferLength); } Debug.Assert(false, "'buffer' MUST reference a memory segment within the pinned InternalBuffer."); // Indicates a violation in the contract with native Websocket.dll and could indicate // memory corruption because the internal buffer is shared between managed and native code throw new AccessViolationException(); } internal void ConvertCloseBuffer(WebSocketProtocolComponent.Action action, Interop.WebSocket.Buffer buffer, out WebSocketCloseStatus closeStatus, out string reason) { ThrowIfDisposed(); IntPtr bufferData; uint bufferLength; closeStatus = (WebSocketCloseStatus)buffer.CloseStatus.CloseStatus; UnwrapWebSocketBuffer(buffer, WebSocketProtocolComponent.BufferType.Close, out bufferData, out bufferLength); if (bufferData == IntPtr.Zero) { reason = null; } else { ArraySegment<byte> reasonBlob; if (this.IsNativeBuffer(bufferData, bufferLength)) { reasonBlob = new ArraySegment<byte>(_internalBuffer.Array, this.GetOffset(bufferData), (int)bufferLength); } else { Debug.Assert(false, "'buffer' MUST reference a memory segment within the pinned InternalBuffer."); // Indicates a violation in the contract with native Websocket.dll and could indicate // memory corruption because the internal buffer is shared between managed and native code throw new AccessViolationException(); } // No need to wrap DecoderFallbackException for invalid UTF8 chacters, because // Encoding.UTF8 will not throw but replace invalid characters instead. reason = Encoding.UTF8.GetString(reasonBlob.Array, reasonBlob.Offset, reasonBlob.Count); } } internal void ValidateNativeBuffers(WebSocketProtocolComponent.Action action, WebSocketProtocolComponent.BufferType bufferType, Interop.WebSocket.Buffer[] dataBuffers, uint dataBufferCount) { Debug.Assert(dataBufferCount <= (uint)int.MaxValue, "'dataBufferCount' MUST NOT be bigger than Int32.MaxValue."); Debug.Assert(dataBuffers != null, "'dataBuffers' MUST NOT be NULL."); ThrowIfDisposed(); if (dataBufferCount > dataBuffers.Length) { Debug.Assert(false, "'dataBufferCount' MUST NOT be bigger than 'dataBuffers.Length'."); // Indicates a violation in the contract with native Websocket.dll and could indicate // memory corruption because the internal buffer is shared between managed and native code throw new AccessViolationException(); } int count = dataBuffers.Length; bool isSendActivity = action == WebSocketProtocolComponent.Action.IndicateSendComplete || action == WebSocketProtocolComponent.Action.SendToNetwork; if (isSendActivity) { count = (int)dataBufferCount; } bool nonZeroBufferFound = false; for (int i = 0; i < count; i++) { Interop.WebSocket.Buffer dataBuffer = dataBuffers[i]; IntPtr bufferData; uint bufferLength; UnwrapWebSocketBuffer(dataBuffer, bufferType, out bufferData, out bufferLength); if (bufferData == IntPtr.Zero) { continue; } nonZeroBufferFound = true; bool isPinnedSendPayloadBuffer = IsPinnedSendPayloadBuffer(dataBuffer, bufferType); if (bufferLength > GetMaxBufferSize()) { if (!isSendActivity || !isPinnedSendPayloadBuffer) { Debug.Assert(false, "'dataBuffer.BufferLength' MUST NOT be bigger than 'm_ReceiveBufferSize' and 'm_SendBufferSize'."); // Indicates a violation in the contract with native Websocket.dll and could indicate // memory corruption because the internal buffer is shared between managed and native code throw new AccessViolationException(); } } if (!isPinnedSendPayloadBuffer && !IsNativeBuffer(bufferData, bufferLength)) { Debug.Assert(false, "WebSocketGetAction MUST return a pointer within the pinned internal buffer."); // Indicates a violation in the contract with native Websocket.dll and could indicate // memory corruption because the internal buffer is shared between managed and native code throw new AccessViolationException(); } } if (!nonZeroBufferFound && action != WebSocketProtocolComponent.Action.NoAction && action != WebSocketProtocolComponent.Action.IndicateReceiveComplete && action != WebSocketProtocolComponent.Action.IndicateSendComplete) { Debug.Assert(false, "At least one 'dataBuffer.Buffer' MUST NOT be NULL."); } } private static int GetNativeSendBufferSize(int sendBufferSize, bool isServerBuffer) { return isServerBuffer ? MinSendBufferSize : sendBufferSize; } internal static void UnwrapWebSocketBuffer(Interop.WebSocket.Buffer buffer, WebSocketProtocolComponent.BufferType bufferType, out IntPtr bufferData, out uint bufferLength) { bufferData = IntPtr.Zero; bufferLength = 0; switch (bufferType) { case WebSocketProtocolComponent.BufferType.Close: bufferData = buffer.CloseStatus.ReasonData; bufferLength = buffer.CloseStatus.ReasonLength; break; case WebSocketProtocolComponent.BufferType.None: case WebSocketProtocolComponent.BufferType.BinaryFragment: case WebSocketProtocolComponent.BufferType.BinaryMessage: case WebSocketProtocolComponent.BufferType.UTF8Fragment: case WebSocketProtocolComponent.BufferType.UTF8Message: case WebSocketProtocolComponent.BufferType.PingPong: case WebSocketProtocolComponent.BufferType.UnsolicitedPong: bufferData = buffer.Data.BufferData; bufferLength = buffer.Data.BufferLength; break; default: Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "BufferType '{0}' is invalid/unknown.", bufferType)); break; } } private void ThrowIfDisposed() { switch (_stateWhenDisposing) { case int.MinValue: return; case (int)WebSocketState.Closed: case (int)WebSocketState.Aborted: throw new WebSocketException(WebSocketError.InvalidState, SR.Format(SR.net_WebSockets_InvalidState_ClosedOrAborted, typeof(WebSocketBase), _stateWhenDisposing)); default: throw new ObjectDisposedException(GetType().FullName); } } [Conditional("DEBUG")] private void ValidateBufferedPayload() { Debug.Assert(_bufferedPayloadReceiveResult != null, "'m_BufferedPayloadReceiveResult' MUST NOT be NULL."); Debug.Assert(_bufferedPayloadReceiveResult.Count >= 0, "'m_BufferedPayloadReceiveResult.Count' MUST NOT be negative."); Debug.Assert(_payloadOffset >= 0, "'m_PayloadOffset' MUST NOT be smaller than 0."); Debug.Assert(_payloadOffset <= _payloadBuffer.Count, "'m_PayloadOffset' MUST NOT be bigger than 'm_PayloadBuffer.Count'."); Debug.Assert(_payloadOffset + _bufferedPayloadReceiveResult.Count <= _payloadBuffer.Count, "'m_PayloadOffset + m_PayloadBytesBuffered' MUST NOT be bigger than 'm_PayloadBuffer.Count'."); } private int GetOffset(IntPtr pBuffer) { Debug.Assert(pBuffer != IntPtr.Zero, "'pBuffer' MUST NOT be IntPtr.Zero."); int offset = (int)(pBuffer.ToInt64() - _startAddress + _internalBuffer.Offset); Debug.Assert(offset >= 0, "'offset' MUST NOT be negative."); return offset; } private int GetMaxBufferSize() { return Math.Max(_receiveBufferSize, _sendBufferSize); } // This method is actually checking whether the array "buffer" is located // within m_NativeBuffer not m_InternalBuffer internal bool IsInternalBuffer(byte[] buffer, int offset, int count) { Debug.Assert(buffer != null, "'buffer' MUST NOT be NULL."); Debug.Assert(_nativeBuffer.Array != null, "'m_NativeBuffer.Array' MUST NOT be NULL."); Debug.Assert(offset >= 0, "'offset' MUST NOT be negative."); Debug.Assert(count >= 0, "'count' MUST NOT be negative."); Debug.Assert(offset + count <= buffer.Length, "'offset + count' MUST NOT exceed 'buffer.Length'."); return object.ReferenceEquals(buffer, _nativeBuffer.Array) && offset >= _nativeBuffer.Offset && offset + count <= _nativeBuffer.Offset + _nativeBuffer.Count; } internal IntPtr ToIntPtr(int offset) { Debug.Assert(offset >= 0, "'offset' MUST NOT be negative."); Debug.Assert(_startAddress + offset - _internalBuffer.Offset <= _endAddress, "'offset' is TOO BIG."); return new IntPtr(_startAddress + offset - _internalBuffer.Offset); } private bool IsNativeBuffer(IntPtr pBuffer, uint bufferSize) { Debug.Assert(pBuffer != IntPtr.Zero, "'pBuffer' MUST NOT be NULL."); Debug.Assert(bufferSize <= GetMaxBufferSize(), "'bufferSize' MUST NOT be bigger than 'm_ReceiveBufferSize' and 'm_SendBufferSize'."); long nativeBufferStartAddress = pBuffer.ToInt64(); long nativeBufferEndAddress = bufferSize + nativeBufferStartAddress; Debug.Assert(Marshal.UnsafeAddrOfPinnedArrayElement(_internalBuffer.Array, _internalBuffer.Offset).ToInt64() == _startAddress, "'m_InternalBuffer.Array' MUST be pinned for the whole lifetime of a WebSocket."); if (nativeBufferStartAddress >= _startAddress && nativeBufferStartAddress <= _endAddress && nativeBufferEndAddress >= _startAddress && nativeBufferEndAddress <= _endAddress) { return true; } return false; } private void CleanUp() { if (_gcHandle.IsAllocated) { _gcHandle.Free(); } ReleasePinnedSendBuffer(); } internal static ArraySegment<byte> CreateInternalBufferArraySegment(int receiveBufferSize, int sendBufferSize, bool isServerBuffer) { Debug.Assert(receiveBufferSize >= MinReceiveBufferSize, "'receiveBufferSize' MUST be at least " + MinReceiveBufferSize.ToString(NumberFormatInfo.InvariantInfo) + "."); Debug.Assert(sendBufferSize >= MinSendBufferSize, "'sendBufferSize' MUST be at least " + MinSendBufferSize.ToString(NumberFormatInfo.InvariantInfo) + "."); int internalBufferSize = GetInternalBufferSize(receiveBufferSize, sendBufferSize, isServerBuffer); return new ArraySegment<byte>(new byte[internalBufferSize]); } internal static void Validate(int count, int receiveBufferSize, int sendBufferSize, bool isServerBuffer) { Debug.Assert(receiveBufferSize >= MinReceiveBufferSize, "'receiveBufferSize' MUST be at least " + MinReceiveBufferSize.ToString(NumberFormatInfo.InvariantInfo) + "."); Debug.Assert(sendBufferSize >= MinSendBufferSize, "'sendBufferSize' MUST be at least " + MinSendBufferSize.ToString(NumberFormatInfo.InvariantInfo) + "."); int minBufferSize = GetInternalBufferSize(receiveBufferSize, sendBufferSize, isServerBuffer); if (count < minBufferSize) { throw new ArgumentOutOfRangeException("internalBuffer", SR.Format(SR.net_WebSockets_ArgumentOutOfRange_InternalBuffer, minBufferSize)); } } private static int GetInternalBufferSize(int receiveBufferSize, int sendBufferSize, bool isServerBuffer) { Debug.Assert(receiveBufferSize >= MinReceiveBufferSize, "'receiveBufferSize' MUST be at least " + MinReceiveBufferSize.ToString(NumberFormatInfo.InvariantInfo) + "."); Debug.Assert(sendBufferSize >= MinSendBufferSize, "'sendBufferSize' MUST be at least " + MinSendBufferSize.ToString(NumberFormatInfo.InvariantInfo) + "."); Debug.Assert(receiveBufferSize <= MaxBufferSize, "'receiveBufferSize' MUST be less than or equal to " + MaxBufferSize.ToString(NumberFormatInfo.InvariantInfo) + "."); Debug.Assert(sendBufferSize <= MaxBufferSize, "'sendBufferSize' MUST be at less than or equal to " + MaxBufferSize.ToString(NumberFormatInfo.InvariantInfo) + "."); int nativeSendBufferSize = GetNativeSendBufferSize(sendBufferSize, isServerBuffer); return 2 * receiveBufferSize + nativeSendBufferSize + NativeOverheadBufferSize + s_PropertyBufferSize; } private static class SendBufferState { public const int None = 0; public const int SendPayloadSpecified = 1; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using Umbraco.Core.Events; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.UnitOfWork; namespace Umbraco.Core.Services { public class PublicAccessService : ScopeRepositoryService, IPublicAccessService { public PublicAccessService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory, ILogger logger, IEventMessagesFactory eventMessagesFactory) : base(provider, repositoryFactory, logger, eventMessagesFactory) { } /// <summary> /// Gets all defined entries and associated rules /// </summary> /// <returns></returns> public IEnumerable<PublicAccessEntry> GetAll() { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repo = RepositoryFactory.CreatePublicAccessRepository(uow); return repo.GetAll(); } } /// <summary> /// Gets the entry defined for the content item's path /// </summary> /// <param name="content"></param> /// <returns>Returns null if no entry is found</returns> public PublicAccessEntry GetEntryForContent(IContent content) { return GetEntryForContent(content.Path.EnsureEndsWith("," + content.Id)); } /// <summary> /// Gets the entry defined for the content item based on a content path /// </summary> /// <param name="contentPath"></param> /// <returns>Returns null if no entry is found</returns> /// <remarks> /// NOTE: This method get's called *very* often! This will return the results from cache /// </remarks> public PublicAccessEntry GetEntryForContent(string contentPath) { //Get all ids in the path for the content item and ensure they all // parse to ints that are not -1. var ids = contentPath.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => { int val; if (int.TryParse(x, out val)) { return val; } return -1; }) .Where(x => x != -1) .ToList(); //start with the deepest id ids.Reverse(); using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { //This will retrieve from cache! var repo = RepositoryFactory.CreatePublicAccessRepository(uow); var entries = repo.GetAll().ToArray(); foreach (var id in ids) { var found = entries.FirstOrDefault(x => x.ProtectedNodeId == id); if (found != null) return found; } } return null; } /// <summary> /// Returns true if the content has an entry for it's path /// </summary> /// <param name="content"></param> /// <returns></returns> public Attempt<PublicAccessEntry> IsProtected(IContent content) { var result = GetEntryForContent(content); return Attempt.If(result != null, result); } /// <summary> /// Returns true if the content has an entry based on a content path /// </summary> /// <param name="contentPath"></param> /// <returns></returns> public Attempt<PublicAccessEntry> IsProtected(string contentPath) { var result = GetEntryForContent(contentPath); return Attempt.If(result != null, result); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use AddRule instead, this method will be removed in future versions")] public Attempt<OperationStatus<PublicAccessEntry, OperationStatusType>> AddOrUpdateRule(IContent content, string ruleType, string ruleValue) { return AddRule(content, ruleType, ruleValue); } /// <summary> /// Adds a rule /// </summary> /// <param name="content"></param> /// <param name="ruleType"></param> /// <param name="ruleValue"></param> /// <returns></returns> public Attempt<OperationStatus<PublicAccessEntry, OperationStatusType>> AddRule(IContent content, string ruleType, string ruleValue) { var evtMsgs = EventMessagesFactory.Get(); using (var uow = UowProvider.GetUnitOfWork()) { var repo = RepositoryFactory.CreatePublicAccessRepository(uow); var entry = repo.GetAll().FirstOrDefault(x => x.ProtectedNodeId == content.Id); if (entry == null) { uow.Commit(); return Attempt<OperationStatus<PublicAccessEntry, OperationStatusType>>.Fail(); } var existingRule = entry.Rules.FirstOrDefault(x => x.RuleType == ruleType && x.RuleValue == ruleValue); if (existingRule == null) { entry.AddRule(ruleValue, ruleType); } else { uow.Commit(); //If they are both the same already then there's nothing to update, exit return Attempt<OperationStatus<PublicAccessEntry, OperationStatusType>>.Succeed(new OperationStatus<PublicAccessEntry, OperationStatusType>(entry, OperationStatusType.Success, evtMsgs)); } var saveEventArgs = new SaveEventArgs<PublicAccessEntry>(entry, evtMsgs); if (uow.Events.DispatchCancelable(Saving, this, saveEventArgs)) { uow.Commit(); return Attempt<OperationStatus<PublicAccessEntry, OperationStatusType>>.Fail( new OperationStatus<PublicAccessEntry, OperationStatusType>(entry, OperationStatusType.FailedCancelledByEvent, evtMsgs)); } repo.AddOrUpdate(entry); uow.Commit(); saveEventArgs.CanCancel = false; uow.Events.Dispatch(Saved, this, saveEventArgs); return Attempt<OperationStatus<PublicAccessEntry, OperationStatusType>>.Succeed( new OperationStatus<PublicAccessEntry, OperationStatusType>(entry, OperationStatusType.Success, evtMsgs)); } } /// <summary> /// Removes a rule /// </summary> /// <param name="content"></param> /// <param name="ruleType"></param> /// <param name="ruleValue"></param> public Attempt<OperationStatus> RemoveRule(IContent content, string ruleType, string ruleValue) { var evtMsgs = EventMessagesFactory.Get(); using (var uow = UowProvider.GetUnitOfWork()) { var repo = RepositoryFactory.CreatePublicAccessRepository(uow); var entry = repo.GetAll().FirstOrDefault(x => x.ProtectedNodeId == content.Id); if (entry == null) { uow.Commit(); return Attempt<OperationStatus>.Fail(); } var existingRule = entry.Rules.FirstOrDefault(x => x.RuleType == ruleType && x.RuleValue == ruleValue); if (existingRule == null) { uow.Commit(); return Attempt<OperationStatus>.Fail(); } entry.RemoveRule(existingRule); var saveEventArgs = new SaveEventArgs<PublicAccessEntry>(entry, evtMsgs); if (uow.Events.DispatchCancelable(Saving, this, saveEventArgs)) { uow.Commit(); return OperationStatus.Cancelled(evtMsgs); } repo.AddOrUpdate(entry); uow.Commit(); saveEventArgs.CanCancel = false; uow.Events.Dispatch(Saved, this, saveEventArgs); return OperationStatus.Success(evtMsgs); } } /// <summary> /// Saves the entry /// </summary> /// <param name="entry"></param> public Attempt<OperationStatus> Save(PublicAccessEntry entry) { var evtMsgs = EventMessagesFactory.Get(); using (var uow = UowProvider.GetUnitOfWork()) { var saveEventArgs = new SaveEventArgs<PublicAccessEntry>(entry, evtMsgs); if (uow.Events.DispatchCancelable(Saving, this, saveEventArgs)) { uow.Commit(); return OperationStatus.Cancelled(evtMsgs); } var repo = RepositoryFactory.CreatePublicAccessRepository(uow); repo.AddOrUpdate(entry); uow.Commit(); saveEventArgs.CanCancel = false; uow.Events.Dispatch(Saved, this, saveEventArgs); return OperationStatus.Success(evtMsgs); } } /// <summary> /// Deletes the entry and all associated rules /// </summary> /// <param name="entry"></param> public Attempt<OperationStatus> Delete(PublicAccessEntry entry) { var evtMsgs = EventMessagesFactory.Get(); using (var uow = UowProvider.GetUnitOfWork()) { var deleteEventArgs = new DeleteEventArgs<PublicAccessEntry>(entry, evtMsgs); if (uow.Events.DispatchCancelable(Deleting, this, deleteEventArgs)) { uow.Commit(); return OperationStatus.Cancelled(evtMsgs); } var repo = RepositoryFactory.CreatePublicAccessRepository(uow); repo.Delete(entry); uow.Commit(); deleteEventArgs.CanCancel = false; uow.Events.Dispatch(Deleted, this, deleteEventArgs); return OperationStatus.Success(evtMsgs); } } /// <summary> /// Occurs before Save /// </summary> public static event TypedEventHandler<IPublicAccessService, SaveEventArgs<PublicAccessEntry>> Saving; /// <summary> /// Occurs after Save /// </summary> public static event TypedEventHandler<IPublicAccessService, SaveEventArgs<PublicAccessEntry>> Saved; /// <summary> /// Occurs before Delete /// </summary> public static event TypedEventHandler<IPublicAccessService, DeleteEventArgs<PublicAccessEntry>> Deleting; /// <summary> /// Occurs after Delete /// </summary> public static event TypedEventHandler<IPublicAccessService, DeleteEventArgs<PublicAccessEntry>> Deleted; } }
// 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.Reflection; using System.Runtime; using System.Reflection.Runtime.General; using Internal.Runtime; using Internal.Runtime.TypeLoader; using Internal.Runtime.Augments; using Internal.Runtime.CompilerServices; using Internal.Metadata.NativeFormat; using Internal.NativeFormat; using Internal.TypeSystem; using Debug = System.Diagnostics.Debug; namespace Internal.Runtime.TypeLoader { public sealed partial class TypeLoaderEnvironment { public bool CompareMethodSignatures(RuntimeSignature signature1, RuntimeSignature signature2) { if (signature1.IsNativeLayoutSignature && signature2.IsNativeLayoutSignature) { if(signature1.StructuralEquals(signature2)) return true; NativeFormatModuleInfo module1 = ModuleList.GetModuleInfoByHandle(new TypeManagerHandle(signature1.ModuleHandle)); NativeReader reader1 = GetNativeLayoutInfoReader(signature1); NativeParser parser1 = new NativeParser(reader1, signature1.NativeLayoutOffset); NativeFormatModuleInfo module2 = ModuleList.GetModuleInfoByHandle(new TypeManagerHandle(signature2.ModuleHandle)); NativeReader reader2 = GetNativeLayoutInfoReader(signature2); NativeParser parser2 = new NativeParser(reader2, signature2.NativeLayoutOffset); return CompareMethodSigs(parser1, module1, parser2, module2); } else if (signature1.IsNativeLayoutSignature) { int token = signature2.Token; MetadataReader metadataReader = ModuleList.Instance.GetMetadataReaderForModule(new TypeManagerHandle(signature2.ModuleHandle)); MethodSignatureComparer comparer = new MethodSignatureComparer(metadataReader, token.AsHandle().ToMethodHandle(metadataReader)); return comparer.IsMatchingNativeLayoutMethodSignature(signature1); } else if (signature2.IsNativeLayoutSignature) { int token = signature1.Token; MetadataReader metadataReader = ModuleList.Instance.GetMetadataReaderForModule(new TypeManagerHandle(signature1.ModuleHandle)); MethodSignatureComparer comparer = new MethodSignatureComparer(metadataReader, token.AsHandle().ToMethodHandle(metadataReader)); return comparer.IsMatchingNativeLayoutMethodSignature(signature2); } else { // For now, RuntimeSignatures are only used to compare for method signature equality (along with their Name) // So we can implement this with the simple equals check if (signature1.Token != signature2.Token) return false; if (signature1.ModuleHandle != signature2.ModuleHandle) return false; return true; } } public uint GetGenericArgumentCountFromMethodNameAndSignature(MethodNameAndSignature signature) { if (signature.Signature.IsNativeLayoutSignature) { NativeReader reader = GetNativeLayoutInfoReader(signature.Signature); NativeParser parser = new NativeParser(reader, signature.Signature.NativeLayoutOffset); return GetGenericArgCountFromSig(parser); } else { ModuleInfo module = signature.Signature.GetModuleInfo(); #if ECMA_METADATA_SUPPORT if (module is NativeFormatModuleInfo) #endif { NativeFormatModuleInfo nativeFormatModule = (NativeFormatModuleInfo)module; var metadataReader = nativeFormatModule.MetadataReader; var methodHandle = signature.Signature.Token.AsHandle().ToMethodHandle(metadataReader); var method = methodHandle.GetMethod(metadataReader); var methodSignature = method.Signature.GetMethodSignature(metadataReader); return checked((uint)methodSignature.GenericParameterCount); } #if ECMA_METADATA_SUPPORT else { EcmaModuleInfo ecmaModuleInfo = (EcmaModuleInfo)module; var metadataReader = ecmaModuleInfo.MetadataReader; var ecmaHandle = (System.Reflection.Metadata.MethodDefinitionHandle)System.Reflection.Metadata.Ecma335.MetadataTokens.Handle(signature.Signature.Token); var method = metadataReader.GetMethodDefinition(ecmaHandle); var blobHandle = method.Signature; var blobReader = metadataReader.GetBlobReader(blobHandle); byte sigByte = blobReader.ReadByte(); if ((sigByte & (byte)System.Reflection.Metadata.SignatureAttributes.Generic) == 0) return 0; uint genArgCount = checked((uint)blobReader.ReadCompressedInteger()); return genArgCount; } #endif } } public bool TryGetMethodNameAndSignatureFromNativeLayoutSignature(RuntimeSignature signature, out MethodNameAndSignature nameAndSignature) { nameAndSignature = null; NativeReader reader = GetNativeLayoutInfoReader(signature); NativeParser parser = new NativeParser(reader, signature.NativeLayoutOffset); if (parser.IsNull) return false; RuntimeSignature methodSig; RuntimeSignature methodNameSig; nameAndSignature = GetMethodNameAndSignature(ref parser, new TypeManagerHandle(signature.ModuleHandle), out methodNameSig, out methodSig); return true; } public bool TryGetMethodNameAndSignaturePointersFromNativeLayoutSignature(TypeManagerHandle module, uint methodNameAndSigToken, out RuntimeSignature methodNameSig, out RuntimeSignature methodSig) { methodNameSig = default(RuntimeSignature); methodSig = default(RuntimeSignature); NativeReader reader = GetNativeLayoutInfoReader(module); NativeParser parser = new NativeParser(reader, methodNameAndSigToken); if (parser.IsNull) return false; methodNameSig = RuntimeSignature.CreateFromNativeLayoutSignature(module, parser.Offset); string methodName = parser.GetString(); // Signatures are indirected to through a relative offset so that we don't have to parse them // when not comparing signatures (parsing them requires resolving types and is tremendously // expensive). NativeParser sigParser = parser.GetParserFromRelativeOffset(); methodSig = RuntimeSignature.CreateFromNativeLayoutSignature(module, sigParser.Offset); return true; } public bool TryGetMethodNameAndSignatureFromNativeLayoutOffset(TypeManagerHandle moduleHandle, uint nativeLayoutOffset, out MethodNameAndSignature nameAndSignature) { nameAndSignature = null; NativeReader reader = GetNativeLayoutInfoReader(moduleHandle); NativeParser parser = new NativeParser(reader, nativeLayoutOffset); if (parser.IsNull) return false; RuntimeSignature methodSig; RuntimeSignature methodNameSig; nameAndSignature = GetMethodNameAndSignature(ref parser, moduleHandle, out methodNameSig, out methodSig); return true; } internal MethodNameAndSignature GetMethodNameAndSignature(ref NativeParser parser, TypeManagerHandle moduleHandle, out RuntimeSignature methodNameSig, out RuntimeSignature methodSig) { methodNameSig = RuntimeSignature.CreateFromNativeLayoutSignature(moduleHandle, parser.Offset); string methodName = parser.GetString(); // Signatures are indirected to through a relative offset so that we don't have to parse them // when not comparing signatures (parsing them requires resolving types and is tremendously // expensive). NativeParser sigParser = parser.GetParserFromRelativeOffset(); methodSig = RuntimeSignature.CreateFromNativeLayoutSignature(moduleHandle, sigParser.Offset); return new MethodNameAndSignature(methodName, methodSig); } internal bool IsStaticMethodSignature(RuntimeSignature methodSig) { if (methodSig.IsNativeLayoutSignature) { NativeReader reader = GetNativeLayoutInfoReader(methodSig); NativeParser parser = new NativeParser(reader, methodSig.NativeLayoutOffset); MethodCallingConvention callingConvention = (MethodCallingConvention)parser.GetUnsigned(); return callingConvention.HasFlag(MethodCallingConvention.Static); } else { ModuleInfo module = methodSig.GetModuleInfo(); #if ECMA_METADATA_SUPPORT if (module is NativeFormatModuleInfo) #endif { NativeFormatModuleInfo nativeFormatModule = (NativeFormatModuleInfo)module; var metadataReader = nativeFormatModule.MetadataReader; var methodHandle = methodSig.Token.AsHandle().ToMethodHandle(metadataReader); var method = methodHandle.GetMethod(metadataReader); return (method.Flags & MethodAttributes.Static) != 0; } #if ECMA_METADATA_SUPPORT else { EcmaModuleInfo ecmaModuleInfo = (EcmaModuleInfo)module; var metadataReader = ecmaModuleInfo.MetadataReader; var ecmaHandle = (System.Reflection.Metadata.MethodDefinitionHandle)System.Reflection.Metadata.Ecma335.MetadataTokens.Handle(methodSig.Token); var method = metadataReader.GetMethodDefinition(ecmaHandle); var blobHandle = method.Signature; var blobReader = metadataReader.GetBlobReader(blobHandle); byte sigByte = blobReader.ReadByte(); return ((sigByte & (byte)System.Reflection.Metadata.SignatureAttributes.Instance) == 0); } #endif } } #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING // Create a TypeSystem.MethodSignature object from a RuntimeSignature that isn't a NativeLayoutSignature private TypeSystem.MethodSignature TypeSystemSigFromRuntimeSignature(TypeSystemContext context, RuntimeSignature signature) { Debug.Assert(!signature.IsNativeLayoutSignature); ModuleInfo module = signature.GetModuleInfo(); #if ECMA_METADATA_SUPPORT if (module is NativeFormatModuleInfo) #endif { NativeFormatModuleInfo nativeFormatModule = (NativeFormatModuleInfo)module; var metadataReader = nativeFormatModule.MetadataReader; var methodHandle = signature.Token.AsHandle().ToMethodHandle(metadataReader); var metadataUnit = ((TypeLoaderTypeSystemContext)context).ResolveMetadataUnit(nativeFormatModule); var parser = new Internal.TypeSystem.NativeFormat.NativeFormatSignatureParser(metadataUnit, metadataReader.GetMethod(methodHandle).Signature, metadataReader); return parser.ParseMethodSignature(); } #if ECMA_METADATA_SUPPORT else { EcmaModuleInfo ecmaModuleInfo = (EcmaModuleInfo)module; TypeSystem.Ecma.EcmaModule ecmaModule = context.ResolveEcmaModule(ecmaModuleInfo); var ecmaHandle = System.Reflection.Metadata.Ecma335.MetadataTokens.EntityHandle(signature.Token); MethodDesc ecmaMethod = ecmaModule.GetMethod(ecmaHandle); return ecmaMethod.Signature; } #endif } #endif internal bool GetCallingConverterDataFromMethodSignature(TypeSystemContext context, RuntimeSignature methodSig, Instantiation typeInstantiation, Instantiation methodInstantiation, out bool hasThis, out TypeDesc[] parameters, out bool[] parametersWithGenericDependentLayout) { if (methodSig.IsNativeLayoutSignature) return GetCallingConverterDataFromMethodSignature_NativeLayout(context, methodSig, typeInstantiation, methodInstantiation, out hasThis, out parameters, out parametersWithGenericDependentLayout); else { #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING var sig = TypeSystemSigFromRuntimeSignature(context, methodSig); return GetCallingConverterDataFromMethodSignature_MethodSignature(sig, typeInstantiation, methodInstantiation, out hasThis, out parameters, out parametersWithGenericDependentLayout); #else parametersWithGenericDependentLayout = null; hasThis = false; parameters = null; return false; #endif } } internal bool GetCallingConverterDataFromMethodSignature_NativeLayout(TypeSystemContext context, RuntimeSignature methodSig, Instantiation typeInstantiation, Instantiation methodInstantiation, out bool hasThis, out TypeDesc[] parameters, out bool[] parametersWithGenericDependentLayout) { hasThis = false; parameters = null; NativeLayoutInfoLoadContext nativeLayoutContext = new NativeLayoutInfoLoadContext(); nativeLayoutContext._module = (NativeFormatModuleInfo)methodSig.GetModuleInfo(); nativeLayoutContext._typeSystemContext = context; nativeLayoutContext._typeArgumentHandles = typeInstantiation; nativeLayoutContext._methodArgumentHandles = methodInstantiation; NativeReader reader = GetNativeLayoutInfoReader(methodSig); NativeFormatModuleInfo module = ModuleList.Instance.GetModuleInfoByHandle(new TypeManagerHandle(methodSig.ModuleHandle)); NativeParser parser = new NativeParser(reader, methodSig.NativeLayoutOffset); MethodCallingConvention callingConvention = (MethodCallingConvention)parser.GetUnsigned(); hasThis = !callingConvention.HasFlag(MethodCallingConvention.Static); uint numGenArgs = callingConvention.HasFlag(MethodCallingConvention.Generic) ? parser.GetUnsigned() : 0; uint parameterCount = parser.GetUnsigned(); parameters = new TypeDesc[parameterCount + 1]; parametersWithGenericDependentLayout = new bool[parameterCount + 1]; // One extra parameter to account for the return type for (uint i = 0; i <= parameterCount; i++) { // NativeParser is a struct, so it can be copied. NativeParser parserCopy = parser; // Parse the signature twice. The first time to find out the exact type of the signature // The second time to identify if the parameter loaded via the signature should be forced to be // passed byref as part of the universal generic calling convention. parameters[i] = GetConstructedTypeFromParserAndNativeLayoutContext(ref parser, nativeLayoutContext); parametersWithGenericDependentLayout[i] = TypeSignatureHasVarsNeedingCallingConventionConverter(ref parserCopy, module, context, HasVarsInvestigationLevel.Parameter); if (parameters[i] == null) return false; } return true; } #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING private static bool GetCallingConverterDataFromMethodSignature_MethodSignature(TypeSystem.MethodSignature methodSignature, Instantiation typeInstantiation, Instantiation methodInstantiation, out bool hasThis, out TypeDesc[] parameters, out bool[] parametersWithGenericDependentLayout) { // Compute parameters dependent on generic instantiation for their layout parametersWithGenericDependentLayout = new bool[methodSignature.Length + 1]; parametersWithGenericDependentLayout[0] = UniversalGenericParameterLayout.IsLayoutDependentOnGenericInstantiation(methodSignature.ReturnType); for (int i = 0; i < methodSignature.Length; i++) { parametersWithGenericDependentLayout[i + 1] = UniversalGenericParameterLayout.IsLayoutDependentOnGenericInstantiation(methodSignature[i]); } // Compute hasThis-ness hasThis = !methodSignature.IsStatic; // Compute parameter exact types parameters = new TypeDesc[methodSignature.Length + 1]; parameters[0] = methodSignature.ReturnType.InstantiateSignature(typeInstantiation, methodInstantiation); for (int i = 0; i < methodSignature.Length; i++) { parameters[i + 1] = methodSignature[i].InstantiateSignature(typeInstantiation, methodInstantiation); } return true; } #endif internal bool MethodSignatureHasVarsNeedingCallingConventionConverter(TypeSystemContext context, RuntimeSignature methodSig) { if (methodSig.IsNativeLayoutSignature) return MethodSignatureHasVarsNeedingCallingConventionConverter_NativeLayout(context, methodSig); else { #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING var sig = TypeSystemSigFromRuntimeSignature(context, methodSig); return UniversalGenericParameterLayout.MethodSignatureHasVarsNeedingCallingConventionConverter(sig); #else Environment.FailFast("Cannot parse signature"); return false; #endif } } private bool MethodSignatureHasVarsNeedingCallingConventionConverter_NativeLayout(TypeSystemContext context, RuntimeSignature methodSig) { NativeReader reader = GetNativeLayoutInfoReader(methodSig); NativeParser parser = new NativeParser(reader, methodSig.NativeLayoutOffset); NativeFormatModuleInfo module = ModuleList.Instance.GetModuleInfoByHandle(new TypeManagerHandle(methodSig.ModuleHandle)); MethodCallingConvention callingConvention = (MethodCallingConvention)parser.GetUnsigned(); uint numGenArgs = callingConvention.HasFlag(MethodCallingConvention.Generic) ? parser.GetUnsigned() : 0; uint parameterCount = parser.GetUnsigned(); // Check the return type of the method if (TypeSignatureHasVarsNeedingCallingConventionConverter(ref parser, module, context, HasVarsInvestigationLevel.Parameter)) return true; // Check the parameters of the method for (uint i = 0; i < parameterCount; i++) { if (TypeSignatureHasVarsNeedingCallingConventionConverter(ref parser, module, context, HasVarsInvestigationLevel.Parameter)) return true; } return false; } #region Private Helpers private enum HasVarsInvestigationLevel { Parameter, NotParameter, Ignore } /// <summary> /// IF THESE SEMANTICS EVER CHANGE UPDATE THE LOGIC WHICH DEFINES THIS BEHAVIOR IN /// THE DYNAMIC TYPE LOADER AS WELL AS THE COMPILER. /// (There is a version of this in UniversalGenericParameterLayout.cs that must be kept in sync with this.) /// /// Parameter's are considered to have type layout dependent on their generic instantiation /// if the type of the parameter in its signature is a type variable, or if the type is a generic /// structure which meets 2 characteristics: /// 1. Structure size/layout is affected by the size/layout of one or more of its generic parameters /// 2. One or more of the generic parameters is a type variable, or a generic structure which also recursively /// would satisfy constraint 2. (Note, that in the recursion case, whether or not the structure is affected /// by the size/layout of its generic parameters is not investigated.) /// /// Examples parameter types, and behavior. /// /// T = true /// List[T] = false /// StructNotDependentOnArgsForSize[T] = false /// GenStructDependencyOnArgsForSize[T] = true /// StructNotDependentOnArgsForSize[GenStructDependencyOnArgsForSize[T]] = true /// StructNotDependentOnArgsForSize[GenStructDependencyOnArgsForSize[List[T]]]] = false /// /// Example non-parameter type behavior /// T = true /// List[T] = false /// StructNotDependentOnArgsForSize[T] = *true* /// GenStructDependencyOnArgsForSize[T] = true /// StructNotDependentOnArgsForSize[GenStructDependencyOnArgsForSize[T]] = true /// StructNotDependentOnArgsForSize[GenStructDependencyOnArgsForSize[List[T]]]] = false /// </summary> private bool TypeSignatureHasVarsNeedingCallingConventionConverter(ref NativeParser parser, NativeFormatModuleInfo moduleHandle, TypeSystemContext context, HasVarsInvestigationLevel investigationLevel) { uint data; var kind = parser.GetTypeSignatureKind(out data); switch (kind) { case TypeSignatureKind.External: return false; case TypeSignatureKind.Variable: return true; case TypeSignatureKind.Lookback: { var lookbackParser = parser.GetLookbackParser(data); return TypeSignatureHasVarsNeedingCallingConventionConverter(ref lookbackParser, moduleHandle, context, investigationLevel); } case TypeSignatureKind.Instantiation: { RuntimeTypeHandle genericTypeDef; if (!TryGetTypeFromSimpleTypeSignature(ref parser, moduleHandle, out genericTypeDef)) { Debug.Assert(false); return true; // Returning true will prevent further reading from the native parser } if (!RuntimeAugments.IsValueType(genericTypeDef)) { // Reference types are treated like pointers. No calling convention conversion needed. Just consume the rest of the signature. for (uint i = 0; i < data; i++) TypeSignatureHasVarsNeedingCallingConventionConverter(ref parser, moduleHandle, context, HasVarsInvestigationLevel.Ignore); return false; } else { bool result = false; for (uint i = 0; i < data; i++) result = TypeSignatureHasVarsNeedingCallingConventionConverter(ref parser, moduleHandle, context, HasVarsInvestigationLevel.NotParameter) || result; if ((result == true) && (investigationLevel == HasVarsInvestigationLevel.Parameter)) { if (!TryComputeHasInstantiationDeterminedSize(genericTypeDef, context, out result)) Environment.FailFast("Unable to setup calling convention converter correctly"); return result; } return result; } } case TypeSignatureKind.Modifier: { // Arrays, pointers and byref types signatures are treated as pointers, not requiring calling convention conversion. // Just consume the parameter type from the stream and return false; TypeSignatureHasVarsNeedingCallingConventionConverter(ref parser, moduleHandle, context, HasVarsInvestigationLevel.Ignore); return false; } case TypeSignatureKind.MultiDimArray: { // No need for a calling convention converter for this case. Just consume the signature from the stream. TypeSignatureHasVarsNeedingCallingConventionConverter(ref parser, moduleHandle, context, HasVarsInvestigationLevel.Ignore); uint boundCount = parser.GetUnsigned(); for (uint i = 0; i < boundCount; i++) parser.GetUnsigned(); uint lowerBoundCount = parser.GetUnsigned(); for (uint i = 0; i < lowerBoundCount; i++) parser.GetUnsigned(); } return false; case TypeSignatureKind.FunctionPointer: { // No need for a calling convention converter for this case. Just consume the signature from the stream. uint argCount = parser.GetUnsigned(); for (uint i = 0; i < argCount; i++) TypeSignatureHasVarsNeedingCallingConventionConverter(ref parser, moduleHandle, context, HasVarsInvestigationLevel.Ignore); } return false; default: parser.ThrowBadImageFormatException(); return true; } } private bool TryGetTypeFromSimpleTypeSignature(ref NativeParser parser, NativeFormatModuleInfo moduleHandle, out RuntimeTypeHandle typeHandle) { uint data; TypeSignatureKind kind = parser.GetTypeSignatureKind(out data); if (kind == TypeSignatureKind.Lookback) { var lookbackParser = parser.GetLookbackParser(data); return TryGetTypeFromSimpleTypeSignature(ref lookbackParser, moduleHandle, out typeHandle); } else if (kind == TypeSignatureKind.External) { typeHandle = GetExternalTypeHandle(moduleHandle, data); return true; } // Not a simple type signature... requires more work to skip typeHandle = default(RuntimeTypeHandle); return false; } private RuntimeTypeHandle GetExternalTypeHandle(NativeFormatModuleInfo moduleHandle, uint typeIndex) { Debug.Assert(moduleHandle != null); RuntimeTypeHandle result; TypeSystemContext context = TypeSystemContextFactory.Create(); { NativeLayoutInfoLoadContext nativeLayoutContext = new NativeLayoutInfoLoadContext(); nativeLayoutContext._module = moduleHandle; nativeLayoutContext._typeSystemContext = context; TypeDesc type = nativeLayoutContext.GetExternalType(typeIndex); result = type.RuntimeTypeHandle; } TypeSystemContextFactory.Recycle(context); Debug.Assert(!result.IsNull()); return result; } private uint GetGenericArgCountFromSig(NativeParser parser) { MethodCallingConvention callingConvention = (MethodCallingConvention)parser.GetUnsigned(); if ((callingConvention & MethodCallingConvention.Generic) == MethodCallingConvention.Generic) { return parser.GetUnsigned(); } else { return 0; } } private bool CompareMethodSigs(NativeParser parser1, NativeFormatModuleInfo moduleHandle1, NativeParser parser2, NativeFormatModuleInfo moduleHandle2) { MethodCallingConvention callingConvention1 = (MethodCallingConvention)parser1.GetUnsigned(); MethodCallingConvention callingConvention2 = (MethodCallingConvention)parser2.GetUnsigned(); if (callingConvention1 != callingConvention2) return false; if ((callingConvention1 & MethodCallingConvention.Generic) == MethodCallingConvention.Generic) { if (parser1.GetUnsigned() != parser2.GetUnsigned()) return false; } uint parameterCount1 = parser1.GetUnsigned(); uint parameterCount2 = parser2.GetUnsigned(); if (parameterCount1 != parameterCount2) return false; // Compare one extra parameter to account for the return type for (uint i = 0; i <= parameterCount1; i++) { if (!CompareTypeSigs(ref parser1, moduleHandle1, ref parser2, moduleHandle2)) return false; } return true; } private bool CompareTypeSigs(ref NativeParser parser1, NativeFormatModuleInfo moduleHandle1, ref NativeParser parser2, NativeFormatModuleInfo moduleHandle2) { // startOffset lets us backtrack to the TypeSignatureKind for external types since the TypeLoader // expects to read it in. uint data1; uint startOffset1 = parser1.Offset; var typeSignatureKind1 = parser1.GetTypeSignatureKind(out data1); // If the parser is at a lookback type, get a new parser for it and recurse. // Since we haven't read the element type of parser2 yet, we just pass it in unchanged if (typeSignatureKind1 == TypeSignatureKind.Lookback) { NativeParser lookbackParser1 = parser1.GetLookbackParser(data1); return CompareTypeSigs(ref lookbackParser1, moduleHandle1, ref parser2, moduleHandle2); } uint data2; uint startOffset2 = parser2.Offset; var typeSignatureKind2 = parser2.GetTypeSignatureKind(out data2); // If parser2 is a lookback type, we need to rewind parser1 to its startOffset1 // before recursing. if (typeSignatureKind2 == TypeSignatureKind.Lookback) { NativeParser lookbackParser2 = parser2.GetLookbackParser(data2); parser1 = new NativeParser(parser1.Reader, startOffset1); return CompareTypeSigs(ref parser1, moduleHandle1, ref lookbackParser2, moduleHandle2); } if (typeSignatureKind1 != typeSignatureKind2) return false; switch (typeSignatureKind1) { case TypeSignatureKind.Lookback: { // Recursion above better have removed all lookbacks Debug.Assert(false, "Unexpected lookback type"); return false; } case TypeSignatureKind.Modifier: { // Ensure the modifier kind (vector, pointer, byref) is the same if (data1 != data2) return false; return CompareTypeSigs(ref parser1, moduleHandle1, ref parser2, moduleHandle2); } case TypeSignatureKind.Variable: { // variable index is in data if (data1 != data2) return false; break; } case TypeSignatureKind.MultiDimArray: { // rank is in data if (data1 != data2) return false; if (!CompareTypeSigs(ref parser1, moduleHandle1, ref parser2, moduleHandle2)) return false; uint boundCount1 = parser1.GetUnsigned(); uint boundCount2 = parser2.GetUnsigned(); if (boundCount1 != boundCount2) return false; for (uint i = 0; i < boundCount1; i++) { if (parser1.GetUnsigned() != parser2.GetUnsigned()) return false; } uint lowerBoundCount1 = parser1.GetUnsigned(); uint lowerBoundCount2 = parser2.GetUnsigned(); if (lowerBoundCount1 != lowerBoundCount2) return false; for (uint i = 0; i < lowerBoundCount1; i++) { if (parser1.GetUnsigned() != parser2.GetUnsigned()) return false; } break; } case TypeSignatureKind.FunctionPointer: { // callingConvention is in data if (data1 != data2) return false; uint argCount1 = parser1.GetUnsigned(); uint argCount2 = parser2.GetUnsigned(); if (argCount1 != argCount2) return false; for (uint i = 0; i < argCount1; i++) { if (!CompareTypeSigs(ref parser1, moduleHandle1, ref parser2, moduleHandle2)) return false; } break; } case TypeSignatureKind.Instantiation: { // Type parameter count is in data if (data1 != data2) return false; if (!CompareTypeSigs(ref parser1, moduleHandle1, ref parser2, moduleHandle2)) return false; for (uint i = 0; i < data1; i++) { if (!CompareTypeSigs(ref parser1, moduleHandle1, ref parser2, moduleHandle2)) return false; } break; } case TypeSignatureKind.External: { RuntimeTypeHandle typeHandle1 = GetExternalTypeHandle(moduleHandle1, data1); RuntimeTypeHandle typeHandle2 = GetExternalTypeHandle(moduleHandle2, data2); if (!typeHandle1.Equals(typeHandle2)) return false; break; } default: return false; } return true; } #endregion } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.AspNet.SignalR.Infrastructure; namespace Microsoft.AspNet.SignalR.Messaging { // Represents a message store that is backed by a ring buffer. [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The rate sampler doesn't need to be disposed")] public sealed class ScaleoutStore { private const uint _minFragmentCount = 4; [SuppressMessage("Microsoft.Performance", "CA1802:UseLiteralsWhereAppropriate", Justification = "It's conditional based on architecture")] private static readonly uint _maxFragmentSize = (IntPtr.Size == 4) ? (uint)16384 : (uint)8192; // guarantees that fragments never end up in the LOH private static readonly ArraySegment<ScaleoutMapping> _emptyArraySegment = new ArraySegment<ScaleoutMapping>(new ScaleoutMapping[0]); private Fragment[] _fragments; private readonly uint _fragmentSize; private long _minMessageId; private long _nextFreeMessageId; private ulong _minMappingId; private ScaleoutMapping _maxMapping; // Creates a message store with the specified capacity. The actual capacity will be *at least* the // specified value. That is, GetMessages may return more data than 'capacity'. public ScaleoutStore(uint capacity) { // set a minimum capacity if (capacity < 32) { capacity = 32; } // Dynamically choose an appropriate number of fragments and the size of each fragment. // This is chosen to avoid allocations on the large object heap and to minimize contention // in the store. We allocate a small amount of additional space to act as an overflow // buffer; this increases throughput of the data structure. checked { uint fragmentCount = Math.Max(_minFragmentCount, capacity / _maxFragmentSize); _fragmentSize = Math.Min((capacity + fragmentCount - 1) / fragmentCount, _maxFragmentSize); _fragments = new Fragment[fragmentCount + 1]; // +1 for the overflow buffer } } internal ScaleoutStore(uint capacity, uint fragmentSize) { checked { uint fragmentCount = capacity / fragmentSize; _fragmentSize = fragmentSize; _fragments = new Fragment[fragmentCount + 1]; // +1 for the overflow buffer } } internal ulong MinMappingId { get { return _minMappingId; } } public ScaleoutMapping MaxMapping { get { return _maxMapping; } } public uint FragmentSize { get { return _fragmentSize; } } public int FragmentCount { get { return _fragments.Length; } } // Adds a message to the store. Returns the ID of the newly added message. public ulong Add(ScaleoutMapping mapping) { // keep looping in TryAddImpl until it succeeds ulong newMessageId; while (!TryAddImpl(mapping, out newMessageId)) ; // When TryAddImpl succeeds, record the fact that a message was just added to the // store. We increment the next free id rather than set it explicitly since // multiple threads might be trying to write simultaneously. There is a nifty // side effect to this: _nextFreeMessageId will *always* return the total number // of messages that *all* threads agree have ever been added to the store. (The // actual number may be higher, but this field will eventually catch up as threads // flush data.) Interlocked.Increment(ref _nextFreeMessageId); return newMessageId; } private void GetFragmentOffsets(ulong messageId, out ulong fragmentNum, out int idxIntoFragmentsArray, out int idxIntoFragment) { fragmentNum = messageId / _fragmentSize; // from the bucket number, we can figure out where in _fragments this data sits idxIntoFragmentsArray = (int)(fragmentNum % (uint)_fragments.Length); idxIntoFragment = (int)(messageId % _fragmentSize); } private int GetFragmentOffset(ulong messageId) { ulong fragmentNum = messageId / _fragmentSize; return (int)(fragmentNum % (uint)_fragments.Length); } private ulong GetMessageId(ulong fragmentNum, uint offset) { return fragmentNum * _fragmentSize + offset; } private bool TryAddImpl(ScaleoutMapping mapping, out ulong newMessageId) { ulong nextFreeMessageId = (ulong)Volatile.Read(ref _nextFreeMessageId); // locate the fragment containing the next free id, which is where we should write ulong fragmentNum; int idxIntoFragmentsArray, idxIntoFragment; GetFragmentOffsets(nextFreeMessageId, out fragmentNum, out idxIntoFragmentsArray, out idxIntoFragment); Fragment fragment = _fragments[idxIntoFragmentsArray]; if (fragment == null || fragment.FragmentNum < fragmentNum) { // the fragment is outdated (or non-existent) and must be replaced bool overwrite = fragment != null && fragment.FragmentNum < fragmentNum; if (idxIntoFragment == 0) { // this thread is responsible for creating the fragment Fragment newFragment = new Fragment(fragmentNum, _fragmentSize); newFragment.Data[0] = mapping; Fragment existingFragment = Interlocked.CompareExchange(ref _fragments[idxIntoFragmentsArray], newFragment, fragment); if (existingFragment == fragment) { newMessageId = GetMessageId(fragmentNum, offset: 0); newFragment.MinId = newMessageId; newFragment.Length = 1; newFragment.MaxId = GetMessageId(fragmentNum, offset: _fragmentSize - 1); _maxMapping = mapping; // Move the minimum id when we overwrite if (overwrite) { _minMessageId = (long)(existingFragment.MaxId + 1); _minMappingId = existingFragment.MaxId; } else if (idxIntoFragmentsArray == 0) { _minMappingId = mapping.Id; } return true; } } // another thread is responsible for updating the fragment, so fall to bottom of method } else if (fragment.FragmentNum == fragmentNum) { // the fragment is valid, and we can just try writing into it until we reach the end of the fragment ScaleoutMapping[] fragmentData = fragment.Data; for (int i = idxIntoFragment; i < fragmentData.Length; i++) { ScaleoutMapping originalMapping = Interlocked.CompareExchange(ref fragmentData[i], mapping, null); if (originalMapping == null) { newMessageId = GetMessageId(fragmentNum, offset: (uint)i); fragment.Length++; _maxMapping = fragmentData[i]; return true; } } // another thread used the last open space in this fragment, so fall to bottom of method } // failure; caller will retry operation newMessageId = 0; return false; } public MessageStoreResult<ScaleoutMapping> GetMessages(ulong firstMessageIdRequestedByClient) { ulong nextFreeMessageId = (ulong)Volatile.Read(ref _nextFreeMessageId); // Case 1: // The client is already up-to-date with the message store, so we return no data. if (nextFreeMessageId <= firstMessageIdRequestedByClient) { return new MessageStoreResult<ScaleoutMapping>(firstMessageIdRequestedByClient, _emptyArraySegment, hasMoreData: false); } // look for the fragment containing the start of the data requested by the client ulong fragmentNum; int idxIntoFragmentsArray, idxIntoFragment; GetFragmentOffsets(firstMessageIdRequestedByClient, out fragmentNum, out idxIntoFragmentsArray, out idxIntoFragment); Fragment thisFragment = _fragments[idxIntoFragmentsArray]; ulong firstMessageIdInThisFragment = GetMessageId(thisFragment.FragmentNum, offset: 0); ulong firstMessageIdInNextFragment = firstMessageIdInThisFragment + _fragmentSize; // Case 2: // This fragment contains the first part of the data the client requested. if (firstMessageIdInThisFragment <= firstMessageIdRequestedByClient && firstMessageIdRequestedByClient < firstMessageIdInNextFragment) { int count = (int)(Math.Min(nextFreeMessageId, firstMessageIdInNextFragment) - firstMessageIdRequestedByClient); var retMessages = new ArraySegment<ScaleoutMapping>(thisFragment.Data, idxIntoFragment, count); return new MessageStoreResult<ScaleoutMapping>(firstMessageIdRequestedByClient, retMessages, hasMoreData: (nextFreeMessageId > firstMessageIdInNextFragment)); } // Case 3: // The client has missed messages, so we need to send him the earliest fragment we have. while (true) { GetFragmentOffsets(nextFreeMessageId, out fragmentNum, out idxIntoFragmentsArray, out idxIntoFragment); Fragment tailFragment = _fragments[(idxIntoFragmentsArray + 1) % _fragments.Length]; if (tailFragment.FragmentNum < fragmentNum) { firstMessageIdInThisFragment = GetMessageId(tailFragment.FragmentNum, offset: 0); return new MessageStoreResult<ScaleoutMapping>(firstMessageIdInThisFragment, new ArraySegment<ScaleoutMapping>(tailFragment.Data, 0, tailFragment.Length), hasMoreData: true); } nextFreeMessageId = (ulong)Volatile.Read(ref _nextFreeMessageId); } } public MessageStoreResult<ScaleoutMapping> GetMessagesByMappingId(ulong mappingId) { var minMessageId = (ulong)Volatile.Read(ref _minMessageId); int idxIntoFragment; // look for the fragment containing the start of the data requested by the client Fragment thisFragment; if (TryGetFragmentFromMappingId(mappingId, out thisFragment)) { int lastSearchIndex; ulong lastSearchId; if (thisFragment.TrySearch(mappingId, out idxIntoFragment, out lastSearchIndex, out lastSearchId)) { // Skip the first message idxIntoFragment++; ulong firstMessageIdRequestedByClient = GetMessageId(thisFragment.FragmentNum, (uint)idxIntoFragment); return GetMessages(firstMessageIdRequestedByClient); } else { if (mappingId > lastSearchId) { lastSearchIndex++; } var segment = new ArraySegment<ScaleoutMapping>(thisFragment.Data, lastSearchIndex, thisFragment.Length - lastSearchIndex); var firstMessageIdInThisFragment = GetMessageId(thisFragment.FragmentNum, offset: (uint)lastSearchIndex); return new MessageStoreResult<ScaleoutMapping>(firstMessageIdInThisFragment, segment, hasMoreData: true); } } // If we're expired or we're at the first mapping or we're lower than the // min then get everything if (mappingId < _minMappingId || mappingId == UInt64.MaxValue) { return GetAllMessages(minMessageId); } // We're up to date so do nothing return new MessageStoreResult<ScaleoutMapping>(0, _emptyArraySegment, hasMoreData: false); } private MessageStoreResult<ScaleoutMapping> GetAllMessages(ulong minMessageId) { ulong fragmentNum; int idxIntoFragmentsArray, idxIntoFragment; GetFragmentOffsets(minMessageId, out fragmentNum, out idxIntoFragmentsArray, out idxIntoFragment); Fragment fragment = _fragments[idxIntoFragmentsArray]; if (fragment == null) { return new MessageStoreResult<ScaleoutMapping>(minMessageId, _emptyArraySegment, hasMoreData: false); } var firstMessageIdInThisFragment = GetMessageId(fragment.FragmentNum, offset: 0); var messages = new ArraySegment<ScaleoutMapping>(fragment.Data, 0, fragment.Length); return new MessageStoreResult<ScaleoutMapping>(firstMessageIdInThisFragment, messages, hasMoreData: true); } internal bool TryGetFragmentFromMappingId(ulong mappingId, out Fragment fragment) { long low = _minMessageId; long high = _nextFreeMessageId; while (low <= high) { var mid = (ulong)((low + high) / 2); int midOffset = GetFragmentOffset(mid); fragment = _fragments[midOffset]; if (fragment == null) { return false; } if (mappingId < fragment.MinValue) { high = (long)(fragment.MinId - 1); } else if (mappingId > fragment.MaxValue) { low = (long)(fragment.MaxId + 1); } else if (fragment.HasValue(mappingId)) { return true; } } fragment = null; return false; } internal sealed class Fragment { public readonly ulong FragmentNum; public readonly ScaleoutMapping[] Data; public int Length; public ulong MinId; public ulong MaxId; public Fragment(ulong fragmentNum, uint fragmentSize) { FragmentNum = fragmentNum; Data = new ScaleoutMapping[fragmentSize]; } public ulong? MinValue { get { var mapping = Data[0]; if (mapping != null) { return mapping.Id; } return null; } } public ulong? MaxValue { get { ScaleoutMapping mapping = null; if (Length == 0) { mapping = Data[Length]; } else { mapping = Data[Length - 1]; } if (mapping != null) { return mapping.Id; } return null; } } public bool HasValue(ulong id) { return id >= MinValue && id <= MaxValue; } public bool TrySearch(ulong id, out int index, out int lastSearchIndex, out ulong lastSearchId) { lastSearchIndex = 0; lastSearchId = id; var low = 0; var high = Length; while (low <= high) { int mid = (low + high) / 2; ScaleoutMapping mapping = Data[mid]; lastSearchIndex = mid; lastSearchId = mapping.Id; if (id < mapping.Id) { high = mid - 1; } else if (id > mapping.Id) { low = mid + 1; } else if (id == mapping.Id) { index = mid; return true; } } index = -1; return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Headers; using System.Text; using Xunit; namespace System.Net.Http.Tests { public class ProductHeaderValueTest { [Fact] public void Ctor_SetValidHeaderValues_InstanceCreatedCorrectly() { ProductHeaderValue product = new ProductHeaderValue("HTTP", "2.0"); Assert.Equal("HTTP", product.Name); Assert.Equal("2.0", product.Version); product = new ProductHeaderValue("HTTP"); Assert.Equal("HTTP", product.Name); Assert.Null(product.Version); product = new ProductHeaderValue("HTTP", ""); // null and string.Empty are equivalent Assert.Equal("HTTP", product.Name); Assert.Null(product.Version); } [Fact] public void Ctor_UseInvalidValues_Throw() { Assert.Throws<ArgumentException>(() => { new ProductHeaderValue(null); }); Assert.Throws<ArgumentException>(() => { new ProductHeaderValue(string.Empty); }); Assert.Throws<FormatException>(() => { new ProductHeaderValue(" x"); }); Assert.Throws<FormatException>(() => { new ProductHeaderValue("x "); }); Assert.Throws<FormatException>(() => { new ProductHeaderValue("x y"); }); Assert.Throws<FormatException>(() => { new ProductHeaderValue("x", " y"); }); Assert.Throws<FormatException>(() => { new ProductHeaderValue("x", "y "); }); Assert.Throws<FormatException>(() => { new ProductHeaderValue("x", "y z"); }); } [Fact] public void ToString_UseDifferentRanges_AllSerializedCorrectly() { ProductHeaderValue product = new ProductHeaderValue("IRC", "6.9"); Assert.Equal("IRC/6.9", product.ToString()); product = new ProductHeaderValue("product"); Assert.Equal("product", product.ToString()); } [Fact] public void GetHashCode_UseSameAndDifferentRanges_SameOrDifferentHashCodes() { ProductHeaderValue product1 = new ProductHeaderValue("custom", "1.0"); ProductHeaderValue product2 = new ProductHeaderValue("custom"); ProductHeaderValue product3 = new ProductHeaderValue("CUSTOM", "1.0"); ProductHeaderValue product4 = new ProductHeaderValue("RTA", "x11"); ProductHeaderValue product5 = new ProductHeaderValue("rta", "X11"); Assert.NotEqual(product1.GetHashCode(), product2.GetHashCode()); Assert.Equal(product1.GetHashCode(), product3.GetHashCode()); Assert.NotEqual(product1.GetHashCode(), product4.GetHashCode()); Assert.Equal(product4.GetHashCode(), product5.GetHashCode()); } [Fact] public void Equals_UseSameAndDifferentRanges_EqualOrNotEqualNoExceptions() { ProductHeaderValue product1 = new ProductHeaderValue("custom", "1.0"); ProductHeaderValue product2 = new ProductHeaderValue("custom"); ProductHeaderValue product3 = new ProductHeaderValue("CUSTOM", "1.0"); ProductHeaderValue product4 = new ProductHeaderValue("RTA", "x11"); ProductHeaderValue product5 = new ProductHeaderValue("rta", "X11"); Assert.False(product1.Equals(null), "custom/1.0 vs. <null>"); Assert.False(product1.Equals(product2), "custom/1.0 vs. custom"); Assert.False(product2.Equals(product1), "custom/1.0 vs. custom"); Assert.True(product1.Equals(product3), "custom/1.0 vs. CUSTOM/1.0"); Assert.False(product1.Equals(product4), "custom/1.0 vs. rta/X11"); Assert.True(product4.Equals(product5), "RTA/x11 vs. rta/X11"); } [Fact] public void Clone_Call_CloneFieldsMatchSourceFields() { ProductHeaderValue source = new ProductHeaderValue("SHTTP", "1.3"); ProductHeaderValue clone = (ProductHeaderValue)((ICloneable)source).Clone(); Assert.Equal(source.Name, clone.Name); Assert.Equal(source.Version, clone.Version); source = new ProductHeaderValue("SHTTP", null); clone = (ProductHeaderValue)((ICloneable)source).Clone(); Assert.Equal(source.Name, clone.Name); Assert.Null(clone.Version); } [Fact] public void GetProductLength_DifferentValidScenarios_AllReturnNonZero() { ProductHeaderValue result = null; CallGetProductLength(" custom", 1, 6, out result); Assert.Equal("custom", result.Name); Assert.Null(result.Version); CallGetProductLength(" custom, ", 1, 6, out result); Assert.Equal("custom", result.Name); Assert.Null(result.Version); CallGetProductLength(" custom / 5.6 ", 1, 13, out result); Assert.Equal("custom", result.Name); Assert.Equal("5.6", result.Version); CallGetProductLength("RTA / x58 ,", 0, 10, out result); Assert.Equal("RTA", result.Name); Assert.Equal("x58", result.Version); CallGetProductLength("RTA / x58", 0, 9, out result); Assert.Equal("RTA", result.Name); Assert.Equal("x58", result.Version); CallGetProductLength("RTA / x58 XXX", 0, 10, out result); Assert.Equal("RTA", result.Name); Assert.Equal("x58", result.Version); } [Fact] public void GetProductLength_DifferentInvalidScenarios_AllReturnZero() { CheckInvalidGetProductLength(" custom", 0); // no leading whitespace allowed CheckInvalidGetProductLength("custom/", 0); CheckInvalidGetProductLength("custom/[", 0); CheckInvalidGetProductLength("=", 0); CheckInvalidGetProductLength("", 0); CheckInvalidGetProductLength(null, 0); } [Fact] public void Parse_SetOfValidValueStrings_ParsedCorrectly() { CheckValidParse(" y/1 ", new ProductHeaderValue("y", "1")); CheckValidParse(" custom / 1.0 ", new ProductHeaderValue("custom", "1.0")); CheckValidParse("custom / 1.0 ", new ProductHeaderValue("custom", "1.0")); CheckValidParse("custom / 1.0", new ProductHeaderValue("custom", "1.0")); } [Fact] public void Parse_SetOfInvalidValueStrings_Throws() { CheckInvalidParse("product/version="); // only delimiter ',' allowed after last product CheckInvalidParse("product otherproduct"); CheckInvalidParse("product["); CheckInvalidParse("="); CheckInvalidParse(null); CheckInvalidParse(string.Empty); CheckInvalidParse(" "); CheckInvalidParse(" ,,"); } [Fact] public void TryParse_SetOfValidValueStrings_ParsedCorrectly() { CheckValidTryParse(" y/1 ", new ProductHeaderValue("y", "1")); CheckValidTryParse(" custom / 1.0 ", new ProductHeaderValue("custom", "1.0")); CheckValidTryParse("custom / 1.0 ", new ProductHeaderValue("custom", "1.0")); CheckValidTryParse("custom / 1.0", new ProductHeaderValue("custom", "1.0")); } [Fact] public void TryParse_SetOfInvalidValueStrings_ReturnsFalse() { CheckInvalidTryParse("product/version="); // only delimiter ',' allowed after last product CheckInvalidTryParse("product otherproduct"); CheckInvalidTryParse("product["); CheckInvalidTryParse("="); CheckInvalidTryParse(null); CheckInvalidTryParse(string.Empty); CheckInvalidTryParse(" "); CheckInvalidTryParse(" ,,"); } #region Helper methods private void CheckValidParse(string input, ProductHeaderValue expectedResult) { ProductHeaderValue result = ProductHeaderValue.Parse(input); Assert.Equal(expectedResult, result); } private void CheckInvalidParse(string input) { Assert.Throws<FormatException>(() => { ProductHeaderValue.Parse(input); }); } private void CheckValidTryParse(string input, ProductHeaderValue expectedResult) { ProductHeaderValue result = null; Assert.True(ProductHeaderValue.TryParse(input, out result)); Assert.Equal(expectedResult, result); } private void CheckInvalidTryParse(string input) { ProductHeaderValue result = null; Assert.False(ProductHeaderValue.TryParse(input, out result)); Assert.Null(result); } private static void CallGetProductLength(string input, int startIndex, int expectedLength, out ProductHeaderValue result) { Assert.Equal(expectedLength, ProductHeaderValue.GetProductLength(input, startIndex, out result)); } private static void CheckInvalidGetProductLength(string input, int startIndex) { ProductHeaderValue result = null; Assert.Equal(0, ProductHeaderValue.GetProductLength(input, startIndex, out result)); Assert.Null(result); } #endregion } }
using Orleans; using Orleans.Runtime; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Extensions.Logging; namespace OrleansTelemetryConsumers.Counters { /// <summary> /// Telemetry consumer that writes metrics to predefined performance counters. /// </summary> public class OrleansPerfCounterTelemetryConsumer : IMetricTelemetryConsumer { internal const string CATEGORY_NAME = "OrleansRuntime"; internal const string CATEGORY_DESCRIPTION = "Orleans Runtime Counters"; private const string ExplainHowToCreateOrleansPerfCounters = "Run 'InstallUtil.exe OrleansTelemetryConsumers.Counters.dll' as Administrator to create perf counters for Orleans."; private readonly ILogger logger; private readonly List<PerfCounterConfigData> perfCounterData = new List<PerfCounterConfigData>(); private bool isInstalling = false; private readonly object initializationLock = new object(); private readonly Lazy<bool> isInitialized; private bool initializedGrainCounters; /// <summary> /// Default constructor /// </summary> public OrleansPerfCounterTelemetryConsumer(ILoggerFactory loggerFactory) { this.logger = loggerFactory.CreateLogger<OrleansPerfCounterTelemetryConsumer>(); this.isInitialized = new Lazy<bool>(this.Initialize, true); if (!AreWindowsPerfCountersAvailable(this.logger)) { this.logger.Warn(ErrorCode.PerfCounterNotFound, "Windows perf counters not found -- defaulting to in-memory counters. " + ExplainHowToCreateOrleansPerfCounters); } } /// <summary> /// Checks to see if windows perf counters as supported by OS. /// </summary> /// <returns></returns> public static bool AreWindowsPerfCountersAvailable(ILogger logger) { try { if (Environment.OSVersion.ToString().StartsWith("unix", StringComparison.InvariantCultureIgnoreCase)) { logger.Warn(ErrorCode.PerfCounterNotFound, "Windows perf counters are only available on Windows :) -- defaulting to in-memory counters."); return false; } return PerformanceCounterCategory.Exists(CATEGORY_NAME); } catch (Exception exc) { logger.Warn(ErrorCode.PerfCounterCategoryCheckError, string.Format("Ignoring error checking for {0} perf counter category", CATEGORY_NAME), exc); } return false; } private PerformanceCounter CreatePerfCounter(string perfCounterName) { this.logger.Debug(ErrorCode.PerfCounterRegistering, "Creating perf counter {0}", perfCounterName); return new PerformanceCounter(CATEGORY_NAME, perfCounterName, false); } private static string GetPerfCounterName(PerfCounterConfigData cd) { return cd.Name.Name + "." + (cd.UseDeltaValue ? "Delta" : "Current"); } /// <summary> /// Register Orleans perf counters with Windows /// </summary> /// <remarks>Note: Program needs to be running as Administrator to be able to delete Windows perf counters.</remarks> internal void InstallCounters() { if (PerformanceCounterCategory.Exists(CATEGORY_NAME)) DeleteCounters(); this.isInstalling = true; if (!this.isInitialized.Value) { var msg = "Unable to install Windows Performance counters"; this.logger.Warn(ErrorCode.PerfCounterNotFound, msg); throw new InvalidOperationException(msg); } var collection = new CounterCreationDataCollection(); foreach (PerfCounterConfigData cd in this.perfCounterData) { var perfCounterName = GetPerfCounterName(cd); var description = cd.Name.Name; var msg = string.Format("Registering perf counter {0}", perfCounterName); Console.WriteLine(msg); collection.Add(new CounterCreationData(perfCounterName, description, PerformanceCounterType.NumberOfItems32)); } PerformanceCounterCategory.Create( CATEGORY_NAME, CATEGORY_DESCRIPTION, PerformanceCounterCategoryType.SingleInstance, collection); } /// <summary> /// Delete any existing perf counters registered with Windows /// </summary> /// <remarks>Note: Program needs to be running as Administrator to be able to delete Windows perf counters.</remarks> internal void DeleteCounters() { PerformanceCounterCategory.Delete(CATEGORY_NAME); } private PerfCounterConfigData GetCounter(string counterName) { return this.perfCounterData.Where(pcd => GetPerfCounterName(pcd) == counterName).SingleOrDefault(); } /// <summary> /// Increment metric. /// </summary> /// <param name="name">metric name</param> public void IncrementMetric(string name) => WriteMetric(name, UpdateMode.Increment); /// <summary> /// Increment metric by value. /// </summary> /// <param name="name">metric name</param> /// <param name="value">metric value</param> public void IncrementMetric(string name, double value) => WriteMetric(name, UpdateMode.Increment, value); /// <summary> /// Track metric value /// </summary> /// <param name="name">metric name</param> /// <param name="value">metric value</param> /// <param name="properties">related properties</param> public void TrackMetric(string name, double value, IDictionary<string, string> properties = null) => WriteMetric(name, UpdateMode.Set, value); /// <summary> /// Track metric value /// </summary> /// <param name="name">metric name</param> /// <param name="value">metric value</param> /// <param name="properties">related properties</param> public void TrackMetric(string name, TimeSpan value, IDictionary<string, string> properties = null) => WriteMetric(name, UpdateMode.Set, value.Ticks); /// <summary> /// Decrement metric /// </summary> /// <param name="name">metric name</param> public void DecrementMetric(string name) => WriteMetric(name, UpdateMode.Decrement); /// <summary> /// Decrement metric by value /// </summary> /// <param name="name">metric name</param> /// <param name="value">metric value</param> public void DecrementMetric(string name, double value) => WriteMetric(name, UpdateMode.Decrement, value); /// <summary> /// Write all pending metrics /// </summary> public void Flush() { } /// <summary> /// Close telemetry consumer /// </summary> public void Close() { } private bool Initialize() { try { // (1) Start with list of static counters var newPerfCounterData = new List<PerfCounterConfigData>(PerfCounterConfigData.StaticPerfCounters); // TODO: get rid of this static access. Telemetry consumers now allow being injected with dependencies, so extract it as such var grainTypes = CrashUtils.GrainTypes; if (grainTypes != null) { // (2) Then search for grain DLLs and pre-create activation counters for any grain types found foreach (var grainType in grainTypes) { var counterName = new StatisticName(StatisticNames.GRAIN_COUNTS_PER_GRAIN, grainType); newPerfCounterData.Add(new PerfCounterConfigData { Name = counterName, UseDeltaValue = false }); } this.initializedGrainCounters = true; } if (!this.isInstalling) { foreach (var cd in newPerfCounterData) { var perfCounterName = GetPerfCounterName(cd); cd.PerfCounter = CreatePerfCounter(perfCounterName); } } lock (this.initializationLock) { this.perfCounterData.Clear(); this.perfCounterData.AddRange(newPerfCounterData); } return true; } catch { return false; } } private void WriteMetric(string name, UpdateMode mode = UpdateMode.Increment, double? value = null) { if (!this.isInitialized.Value) return; // Attempt to initialize grain-specific counters if they haven't been initialized yet. if (!this.initializedGrainCounters) { this.Initialize(); } PerfCounterConfigData cd = GetCounter(name); if (cd == null || cd.PerfCounter == null) return; StatisticName statsName = cd.Name; string perfCounterName = GetPerfCounterName(cd); try { if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace(ErrorCode.PerfCounterWriting, "Writing perf counter {0}", perfCounterName); switch (mode) { case UpdateMode.Increment: if (value.HasValue) { cd.PerfCounter.IncrementBy((long)value.Value); } else { cd.PerfCounter.Increment(); } break; case UpdateMode.Decrement: if (value.HasValue) { cd.PerfCounter.RawValue = cd.PerfCounter.RawValue - (long)value.Value; } else { cd.PerfCounter.Decrement(); } break; case UpdateMode.Set: cd.PerfCounter.RawValue = (long)value.Value; break; } } catch (Exception ex) { this.logger.Error(ErrorCode.PerfCounterUnableToWrite, string.Format("Unable to write to Windows perf counter '{0}'", statsName), ex); } } private enum UpdateMode { Increment = 0, Decrement, Set } } }
// Generated by SharpKit.QooxDoo.Generator using System; using System.Collections.Generic; using SharpKit.Html; using SharpKit.JavaScript; namespace qx.ui.core.scroll { /// <summary> /// <para>The scroll bar widget wraps the native browser scroll bars as a qooxdoo widget. /// It can be uses instead of the styled qooxdoo scroll bars.</para> /// <para>Scroll bars are used by the <see cref="qx.ui.container.Scroll"/> container. Usually /// a scroll bar is not used directly.</para> /// <para>Example</para> /// <para>Here is a little example of how to use the widget.</para> /// <code> /// var scrollBar = new qx.ui.core.scroll.NativeScrollBar("horizontal"); /// scrollBar.set({ /// maximum: 500 /// }) /// this.getRoot().add(scrollBar); /// </code> /// <para>This example creates a horizontal scroll bar with a maximum value of 500.</para> /// <para>External Documentation</para> /// /// Documentation of this widget in the qooxdoo manual. /// </summary> [JsType(JsMode.Prototype, Name = "qx.ui.core.scroll.NativeScrollBar", OmitOptionalParameters = true, Export = false)] public partial class NativeScrollBar : qx.ui.core.Widget, qx.ui.core.scroll.IScrollBar { #region Events /// <summary> /// <para>Fired if the user scroll</para> /// </summary> public event Action<qx.eventx.type.Data> OnScroll; /// <summary> /// <para>Fired as soon as the scroll animation ended.</para> /// </summary> public event Action<qx.eventx.type.Event> OnScrollAnimationEnd; #endregion Events #region Properties /// <summary> /// <para>The appearance ID. This ID is used to identify the appearance theme /// entry to use for this widget. This controls the styling of the element.</para> /// </summary> [JsProperty(Name = "appearance", NativeField = true)] public string Appearance { get; set; } /// <summary> /// <para>Factor to apply to the width/height of the knob in relation /// to the dimension of the underlying area.</para> /// </summary> [JsProperty(Name = "knobFactor", NativeField = true)] public object KnobFactor { get; set; } /// <summary> /// <para>The maximum value (difference between available size and /// content size).</para> /// </summary> [JsProperty(Name = "maximum", NativeField = true)] public object Maximum { get; set; } /// <summary> /// <para>The scroll bar orientation</para> /// </summary> [JsProperty(Name = "orientation", NativeField = true)] public object Orientation { get; set; } /// <summary> /// <para>Position of the scrollbar (which means the scroll left/top of the /// attached area&#8217;s pane)</para> /// <para>Strictly validates according to <see cref="Maximum"/>. /// Does not apply any correction to the incoming value. If you depend /// on this, please use <see cref="ScrollTo"/> instead.</para> /// </summary> [JsProperty(Name = "position", NativeField = true)] public object Position { get; set; } /// <summary> /// <para>Step size for each click on the up/down or left/right buttons.</para> /// </summary> [JsProperty(Name = "singleStep", NativeField = true)] public double SingleStep { get; set; } #endregion Properties #region Methods public NativeScrollBar() { throw new NotImplementedException(); } /// <param name="orientation">The initial scroll bar orientation</param> public NativeScrollBar(string orientation = "horizontal") { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property knobFactor.</para> /// </summary> [JsMethod(Name = "getKnobFactor")] public object GetKnobFactor() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property maximum.</para> /// </summary> [JsMethod(Name = "getMaximum")] public object GetMaximum() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property orientation.</para> /// </summary> [JsMethod(Name = "getOrientation")] public object GetOrientation() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property position.</para> /// </summary> [JsMethod(Name = "getPosition")] public object GetPosition() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property singleStep.</para> /// </summary> [JsMethod(Name = "getSingleStep")] public double GetSingleStep() { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property knobFactor /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property knobFactor.</param> [JsMethod(Name = "initKnobFactor")] public void InitKnobFactor(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property maximum /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property maximum.</param> [JsMethod(Name = "initMaximum")] public void InitMaximum(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property orientation /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property orientation.</param> [JsMethod(Name = "initOrientation")] public void InitOrientation(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property position /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property position.</param> [JsMethod(Name = "initPosition")] public void InitPosition(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property singleStep /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property singleStep.</param> [JsMethod(Name = "initSingleStep")] public void InitSingleStep(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Used by the layout engine to apply coordinates and dimensions.</para> /// </summary> /// <param name="left">Any integer value for the left position, always in pixels</param> /// <param name="top">Any integer value for the top position, always in pixels</param> /// <param name="width">Any positive integer value for the width, always in pixels</param> /// <param name="height">Any positive integer value for the height, always in pixels</param> /// <returns>A map of which layout sizes changed.</returns> [JsMethod(Name = "renderLayout")] public object RenderLayout(double left, double top, double width, double height) { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property knobFactor.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetKnobFactor")] public void ResetKnobFactor() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property maximum.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetMaximum")] public void ResetMaximum() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property orientation.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetOrientation")] public void ResetOrientation() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property position.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetPosition")] public void ResetPosition() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property singleStep.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetSingleStep")] public void ResetSingleStep() { throw new NotImplementedException(); } /// <summary> /// <para>Scrolls by the given offset.</para> /// <para>This method automatically corrects the given position to respect /// the <see cref="Maximum"/>.</para> /// </summary> /// <param name="offset">Scroll by this offset</param> /// <param name="duration">The time in milliseconds the slide to should take.</param> [JsMethod(Name = "scrollBy")] public void ScrollBy(double offset, double duration) { throw new NotImplementedException(); } /// <summary> /// <para>Scrolls by the given number of steps.</para> /// <para>This method automatically corrects the given position to respect /// the <see cref="Maximum"/>.</para> /// </summary> /// <param name="steps">Number of steps</param> /// <param name="duration">The time in milliseconds the slide to should take.</param> [JsMethod(Name = "scrollBySteps")] public void ScrollBySteps(double steps, double duration) { throw new NotImplementedException(); } /// <summary> /// <para>Scrolls to the given position.</para> /// <para>This method automatically corrects the given position to respect /// the <see cref="Maximum"/>.</para> /// </summary> /// <param name="position">Scroll to this position. Must be greater zero.</param> /// <param name="duration">The time in milliseconds the slide to should take.</param> [JsMethod(Name = "scrollTo")] public void ScrollTo(double position, double duration) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property knobFactor.</para> /// </summary> /// <param name="value">New value for property knobFactor.</param> [JsMethod(Name = "setKnobFactor")] public void SetKnobFactor(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property maximum.</para> /// </summary> /// <param name="value">New value for property maximum.</param> [JsMethod(Name = "setMaximum")] public void SetMaximum(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property orientation.</para> /// </summary> /// <param name="value">New value for property orientation.</param> [JsMethod(Name = "setOrientation")] public void SetOrientation(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property position.</para> /// </summary> /// <param name="value">New value for property position.</param> [JsMethod(Name = "setPosition")] public void SetPosition(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property singleStep.</para> /// </summary> /// <param name="value">New value for property singleStep.</param> [JsMethod(Name = "setSingleStep")] public void SetSingleStep(double value) { throw new NotImplementedException(); } #endregion Methods } }
// // https://github.com/ServiceStack/ServiceStack.Text // ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers. // // Authors: // Demis Bellot ([email protected]) // // Copyright 2012 ServiceStack Ltd. // // Licensed under the same terms of ServiceStack: new BSD license. // using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Threading; using System.Linq; using ServiceStack.Text.Common; namespace ServiceStack.Text { public static class TranslateListWithElements { private static Dictionary<Type, ConvertInstanceDelegate> TranslateICollectionCache = new Dictionary<Type, ConvertInstanceDelegate>(); public static object TranslateToGenericICollectionCache(object from, Type toInstanceOfType, Type elementType) { ConvertInstanceDelegate translateToFn; if (TranslateICollectionCache.TryGetValue(toInstanceOfType, out translateToFn)) return translateToFn(from, toInstanceOfType); var genericType = typeof(TranslateListWithElements<>).MakeGenericType(elementType); #if NETFX_CORE var mi = genericType.GetRuntimeMethods().First(p => p.Name.Equals("LateBoundTranslateToGenericICollection")); translateToFn = (ConvertInstanceDelegate)mi.CreateDelegate(typeof(ConvertInstanceDelegate)); #else var mi = genericType.GetMethod("LateBoundTranslateToGenericICollection", BindingFlags.Static | BindingFlags.Public); translateToFn = (ConvertInstanceDelegate)Delegate.CreateDelegate(typeof(ConvertInstanceDelegate), mi); #endif Dictionary<Type, ConvertInstanceDelegate> snapshot, newCache; do { snapshot = TranslateICollectionCache; newCache = new Dictionary<Type, ConvertInstanceDelegate>(TranslateICollectionCache); newCache[elementType] = translateToFn; } while (!ReferenceEquals( Interlocked.CompareExchange(ref TranslateICollectionCache, newCache, snapshot), snapshot)); return translateToFn(from, toInstanceOfType); } private static Dictionary<ConvertibleTypeKey, ConvertInstanceDelegate> TranslateConvertibleICollectionCache = new Dictionary<ConvertibleTypeKey, ConvertInstanceDelegate>(); public static object TranslateToConvertibleGenericICollectionCache( object from, Type toInstanceOfType, Type fromElementType) { var typeKey = new ConvertibleTypeKey(toInstanceOfType, fromElementType); ConvertInstanceDelegate translateToFn; if (TranslateConvertibleICollectionCache.TryGetValue(typeKey, out translateToFn)) return translateToFn(from, toInstanceOfType); #if NETFX_CORE var toElementType = toInstanceOfType.GetGenericType().GenericTypeArguments[0]; var genericType = typeof(TranslateListWithConvertibleElements<,>).MakeGenericType(fromElementType, toElementType); var mi = genericType.GetRuntimeMethods().First(p => p.Name.Equals("LateBoundTranslateToGenericICollection")); translateToFn = (ConvertInstanceDelegate)mi.CreateDelegate(typeof(ConvertInstanceDelegate)); #else var toElementType = toInstanceOfType.GetGenericType().GetGenericArguments()[0]; var genericType = typeof(TranslateListWithConvertibleElements<,>).MakeGenericType(fromElementType, toElementType); var mi = genericType.GetMethod("LateBoundTranslateToGenericICollection", BindingFlags.Static | BindingFlags.Public); translateToFn = (ConvertInstanceDelegate)Delegate.CreateDelegate(typeof(ConvertInstanceDelegate), mi); #endif Dictionary<ConvertibleTypeKey, ConvertInstanceDelegate> snapshot, newCache; do { snapshot = TranslateConvertibleICollectionCache; newCache = new Dictionary<ConvertibleTypeKey, ConvertInstanceDelegate>(TranslateConvertibleICollectionCache); newCache[typeKey] = translateToFn; } while (!ReferenceEquals( Interlocked.CompareExchange(ref TranslateConvertibleICollectionCache, newCache, snapshot), snapshot)); return translateToFn(from, toInstanceOfType); } public static object TryTranslateToGenericICollection(Type fromPropertyType, Type toPropertyType, object fromValue) { var args = typeof(ICollection<>).GetGenericArgumentsIfBothHaveSameGenericDefinitionTypeAndArguments( fromPropertyType, toPropertyType); if (args != null) { return TranslateToGenericICollectionCache( fromValue, toPropertyType, args[0]); } var varArgs = typeof(ICollection<>).GetGenericArgumentsIfBothHaveConvertibleGenericDefinitionTypeAndArguments( fromPropertyType, toPropertyType); if (varArgs != null) { return TranslateToConvertibleGenericICollectionCache( fromValue, toPropertyType, varArgs.Args1[0]); } return null; } } public class ConvertibleTypeKey { public Type ToInstanceType { get; set; } public Type FromElemenetType { get; set; } public ConvertibleTypeKey() { } public ConvertibleTypeKey(Type toInstanceType, Type fromElemenetType) { ToInstanceType = toInstanceType; FromElemenetType = fromElemenetType; } public bool Equals(ConvertibleTypeKey other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Equals(other.ToInstanceType, ToInstanceType) && Equals(other.FromElemenetType, FromElemenetType); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof(ConvertibleTypeKey)) return false; return Equals((ConvertibleTypeKey)obj); } public override int GetHashCode() { unchecked { return ((ToInstanceType != null ? ToInstanceType.GetHashCode() : 0) * 397) ^ (FromElemenetType != null ? FromElemenetType.GetHashCode() : 0); } } } public class TranslateListWithElements<T> { public static object CreateInstance(Type toInstanceOfType) { #if NETFX_CORE if (toInstanceOfType.GetTypeInfo().IsGenericType) #else if (toInstanceOfType.IsGenericType) #endif { if (toInstanceOfType.HasAnyTypeDefinitionsOf( typeof(ICollection<>), typeof(IList<>))) { return ReflectionExtensions.CreateInstance(typeof(List<T>)); } } return ReflectionExtensions.CreateInstance(toInstanceOfType); } public static IList TranslateToIList(IList fromList, Type toInstanceOfType) { var to = (IList)ReflectionExtensions.CreateInstance(toInstanceOfType); foreach (var item in fromList) { to.Add(item); } return to; } public static object LateBoundTranslateToGenericICollection( object fromList, Type toInstanceOfType) { if (fromList == null) return null; //AOT return TranslateToGenericICollection( (ICollection<T>)fromList, toInstanceOfType); } public static ICollection<T> TranslateToGenericICollection( ICollection<T> fromList, Type toInstanceOfType) { var to = (ICollection<T>)CreateInstance(toInstanceOfType); foreach (var item in fromList) { to.Add(item); } return to; } } public class TranslateListWithConvertibleElements<TFrom, TTo> { private static readonly Func<TFrom, TTo> ConvertFn; static TranslateListWithConvertibleElements() { ConvertFn = GetConvertFn(); } public static object LateBoundTranslateToGenericICollection( object fromList, Type toInstanceOfType) { return TranslateToGenericICollection( (ICollection<TFrom>)fromList, toInstanceOfType); } public static ICollection<TTo> TranslateToGenericICollection( ICollection<TFrom> fromList, Type toInstanceOfType) { if (fromList == null) return null; //AOT var to = (ICollection<TTo>)TranslateListWithElements<TTo>.CreateInstance(toInstanceOfType); foreach (var item in fromList) { var toItem = ConvertFn(item); to.Add(toItem); } return to; } private static Func<TFrom, TTo> GetConvertFn() { if (typeof(TTo) == typeof(string)) { return x => (TTo)(object)TypeSerializer.SerializeToString(x); } if (typeof(TFrom) == typeof(string)) { return x => TypeSerializer.DeserializeFromString<TTo>((string)(object)x); } return x => TypeSerializer.DeserializeFromString<TTo>(TypeSerializer.SerializeToString(x)); } } }
// Copyright (c) 2014 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using Keyman7Interop; using Keyman10Interop; using Microsoft.Win32; using SIL.Keyboarding; namespace SIL.Windows.Forms.Keyboarding.Windows { /// <summary> /// Class for handling Keyman keyboards not associated with a Windows language /// </summary> internal class KeymanKeyboardAdaptor : IKeyboardRetrievingAdaptor { private enum KeymanVersion { NotInstalled, Keyman6, Keyman7to9, Keyman10 } public KeymanKeyboardAdaptor() { InstalledKeymanVersion = GetInstalledKeymanVersion(); } private KeymanVersion InstalledKeymanVersion { get; set; } #region IKeyboardRetrievingAdaptor Members /// <summary> /// The type of keyboards this adaptor handles: system or other (like Keyman, ibus...) /// </summary> public KeyboardAdaptorType Type { get { CheckDisposed(); return KeyboardAdaptorType.OtherIm; } } public bool IsApplicable { get { switch (InstalledKeymanVersion) { case KeymanVersion.Keyman10: var keyman10 = new KeymanClass(); if (keyman10.Keyboards != null && keyman10.Keyboards.Count > 0) { return true; } break; case KeymanVersion.Keyman7to9: var keyman = new TavultesoftKeymanClass(); if (keyman.Keyboards != null && keyman.Keyboards.Count > 0) { return true; } break; case KeymanVersion.Keyman6: var keymanLink = new KeymanLink.KeymanLink(); if (keymanLink.Initialize()) { if (keymanLink.Keyboards != null && keymanLink.Keyboards.Length > 0) { return true; } } break; case KeymanVersion.NotInstalled: return false; default: throw new NotSupportedException($"{InstalledKeymanVersion} not yet supported in IsApplicable"); } return false; } } public IKeyboardSwitchingAdaptor SwitchingAdaptor { get; set; } public void Initialize() { CheckDisposed(); SwitchingAdaptor = GetKeymanSwitchingAdapter(InstalledKeymanVersion); UpdateAvailableKeyboards(); } private IKeyboardSwitchingAdaptor GetKeymanSwitchingAdapter(KeymanVersion installedKeymanVersion) { switch (installedKeymanVersion) { case KeymanVersion.Keyman10: return new KeymanKeyboardSwitchingAdapter(); case KeymanVersion.Keyman6: case KeymanVersion.Keyman7to9: return new LegacyKeymanKeyboardSwitchingAdapter(); } return null; } private KeymanVersion GetInstalledKeymanVersion() { // limit the COMException catching by determining the current version once and assuming it for the // rest of the adaptor's lifetime try { var keyman10 = new KeymanClass(); return KeymanVersion.Keyman10; } catch (COMException) { // not 10 } try { var keyman = new TavultesoftKeymanClass(); return KeymanVersion.Keyman7to9; } catch (COMException) { // Not 7-9 } try { var keymanLink = new KeymanLink.KeymanLink(); return KeymanVersion.Keyman6; } catch (COMException) { } return KeymanVersion.NotInstalled; } public void UpdateAvailableKeyboards() { CheckDisposed(); Dictionary<string, KeymanKeyboardDescription> curKeyboards = KeyboardController.Instance.Keyboards.OfType<KeymanKeyboardDescription>().ToDictionary(kd => kd.Id); switch (InstalledKeymanVersion) { case KeymanVersion.Keyman10: // Keyman10 keyboards are handled by the WinKeyboardAdapter and WindowsKeyboardSwitchingAdapter break; case KeymanVersion.Keyman7to9: var keyman = new TavultesoftKeymanClass(); UpdateKeyboards(curKeyboards, keyman.Keyboards.OfType<Keyman7Interop.IKeymanKeyboard>().Select(kb => kb.Name), false); break; case KeymanVersion.Keyman6: var keymanLink = new KeymanLink.KeymanLink(); if (keymanLink.Initialize()) { UpdateKeyboards(curKeyboards, keymanLink.Keyboards.Select(kb => kb.KbdName), true); } break; } } private void UpdateKeyboards(Dictionary<string, KeymanKeyboardDescription> curKeyboards, IEnumerable<string> availableKeyboardNames, bool isKeyman6) { foreach (string keyboardName in availableKeyboardNames) { KeymanKeyboardDescription existingKeyboard; if (curKeyboards.TryGetValue(keyboardName, out existingKeyboard)) { if (!existingKeyboard.IsAvailable) { existingKeyboard.SetIsAvailable(true); existingKeyboard.IsKeyman6 = isKeyman6; if (existingKeyboard.Format == KeyboardFormat.Unknown) existingKeyboard.Format = KeyboardFormat.CompiledKeyman; } curKeyboards.Remove(keyboardName); } else { KeyboardController.Instance.Keyboards.Add(new KeymanKeyboardDescription(keyboardName, isKeyman6, this, true) { Format = KeyboardFormat.CompiledKeyman }); } } } /// <summary> /// Creates and returns a keyboard definition object based on the ID. /// Note that this method is used when we do NOT have a matching available keyboard. /// Therefore we can presume that the created one is NOT available. /// </summary> public KeyboardDescription CreateKeyboardDefinition(string id) { CheckDisposed(); switch (InstalledKeymanVersion) { case KeymanVersion.Keyman10: string layout, locale; KeyboardController.GetLayoutAndLocaleFromLanguageId(id, out layout, out locale); string cultureName; var inputLanguage = WinKeyboardUtils.GetInputLanguage(locale, layout, out cultureName); return new KeymanKeyboardDescription(id, false, this, false) { InputLanguage = inputLanguage }; default: return new KeymanKeyboardDescription(id, false, this, false); } } public string GetKeyboardSetupApplication(out string arguments) { arguments = null; string keyman; int version = 0; string keymanPath = GetKeymanRegistryValue(@"root path", ref version); if (keymanPath != null) { keyman = Path.Combine(keymanPath, @"kmshell.exe"); if (File.Exists(keyman)) { arguments = @""; if (version > 6) arguments = @"-c"; return keyman; } } return null; } /// <summary> /// This method returns the path to Keyman Configuration if it is installed. Otherwise it returns null. /// It also sets the version of Keyman that it found. /// </summary> /// <param name="key">The key.</param> /// <param name="version">The version.</param> private static string GetKeymanRegistryValue(string key, ref int version) { using (var olderKeyman = Registry.LocalMachine.OpenSubKey(@"Software\Tavultesoft\Keyman", false)) using (var olderKeyman32 = Registry.LocalMachine.OpenSubKey(@"Software\WOW6432Node\Tavultesoft\Keyman", false)) { var keymanKey = olderKeyman32 ?? olderKeyman; if (keymanKey == null) return null; int[] versions = {9, 8, 7, 6, 5}; foreach (var vers in versions) { using (var rkApplication = keymanKey.OpenSubKey($"{vers}.0", false)) { if (rkApplication != null) { foreach (var sKey in rkApplication.GetValueNames()) { if (sKey == key) { version = vers; return (string) rkApplication.GetValue(sKey); } } } } } } return null; } public Action GetKeyboardSetupAction() { switch (InstalledKeymanVersion) { case KeymanVersion.Keyman10: return () => { var keymanClass = new KeymanClass(); keymanClass.Control.OpenConfiguration(); }; case KeymanVersion.Keyman7to9: case KeymanVersion.Keyman6: return () => { string args; var setupApp = GetKeyboardSetupApplication(out args); Process.Start(setupApp, args); }; default: throw new NotSupportedException($"No keyboard setup action defined for keyman version {InstalledKeymanVersion}"); } } public Action GetSecondaryKeyboardSetupAction() => GetKeyboardSetupAction(); public bool IsSecondaryKeyboardSetupApplication => true; public bool CanHandleFormat(KeyboardFormat format) { CheckDisposed(); switch (format) { case KeyboardFormat.CompiledKeyman: case KeyboardFormat.Keyman: case KeyboardFormat.KeymanPackage: return true; } return false; } #endregion #region IDisposable & Co. implementation // Region last reviewed: never /// <summary> /// Check to see if the object has been disposed. /// All public Properties and Methods should call this /// before doing anything else. /// </summary> public void CheckDisposed() { if (IsDisposed) throw new ObjectDisposedException(String.Format("'{0}' in use after being disposed.", GetType().Name)); } /// <summary> /// See if the object has been disposed. /// </summary> public bool IsDisposed { get; private set; } /// <summary> /// Finalizer, in case client doesn't dispose it. /// Force Dispose(false) if not already called (i.e. m_isDisposed is true) /// </summary> /// <remarks> /// In case some clients forget to dispose it directly. /// </remarks> ~KeymanKeyboardAdaptor() { Dispose(false); // The base class finalizer is called automatically. } /// <summary> /// /// </summary> /// <remarks>Must not be virtual.</remarks> public void Dispose() { Dispose(true); // This object will be cleaned up by the Dispose method. // Therefore, you should call GC.SupressFinalize to // take this object off the finalization queue // and prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } /// <summary> /// Executes in two distinct scenarios. /// /// 1. If disposing is true, the method has been called directly /// or indirectly by a user's code via the Dispose method. /// Both managed and unmanaged resources can be disposed. /// /// 2. If disposing is false, the method has been called by the /// runtime from inside the finalizer and you should not reference (access) /// other managed objects, as they already have been garbage collected. /// Only unmanaged resources can be disposed. /// </summary> /// <param name="disposing"></param> /// <remarks> /// If any exceptions are thrown, that is fine. /// If the method is being done in a finalizer, it will be ignored. /// If it is thrown by client code calling Dispose, /// it needs to be handled by fixing the bug. /// /// If subclasses override this method, they should call the base implementation. /// </remarks> protected virtual void Dispose(bool disposing) { Debug.WriteLineIf(!disposing, "****************** " + GetType().Name + " 'disposing' is false. ******************"); // Must not be run more than once. if (IsDisposed) return; if (disposing) { // Dispose managed resources here. } // Dispose unmanaged resources here, whether disposing is true or false. IsDisposed = true; } #endregion IDisposable & Co. implementation } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Data.Common; using System.Diagnostics; // Debug services using System.Runtime.InteropServices; using System.Text; namespace System.Data.Odbc { internal sealed class CNativeBuffer : System.Data.ProviderBase.DbBuffer { internal CNativeBuffer(int initialSize) : base(initialSize) { } internal short ShortLength { get { return checked((short)Length); } } internal object MarshalToManaged(int offset, ODBC32.SQL_C sqlctype, int cb) { object value; switch (sqlctype) { case ODBC32.SQL_C.WCHAR: //Note: We always bind as unicode if (cb == ODBC32.SQL_NTS) { value = PtrToStringUni(offset); break; } Debug.Assert((cb > 0), "Character count negative "); Debug.Assert((Length >= cb), "Native buffer too small "); cb = Math.Min(cb / 2, (Length - 2) / 2); value = PtrToStringUni(offset, cb); break; case ODBC32.SQL_C.CHAR: case ODBC32.SQL_C.BINARY: Debug.Assert((cb > 0), "Character count negative "); Debug.Assert((Length >= cb), "Native buffer too small "); cb = Math.Min(cb, Length); value = ReadBytes(offset, cb); break; case ODBC32.SQL_C.SSHORT: value = ReadInt16(offset); break; case ODBC32.SQL_C.SLONG: value = ReadInt32(offset); break; case ODBC32.SQL_C.SBIGINT: value = ReadInt64(offset); break; case ODBC32.SQL_C.BIT: byte b = ReadByte(offset); value = (b != 0x00); break; case ODBC32.SQL_C.REAL: value = ReadSingle(offset); break; case ODBC32.SQL_C.DOUBLE: value = ReadDouble(offset); break; case ODBC32.SQL_C.UTINYINT: value = ReadByte(offset); break; case ODBC32.SQL_C.GUID: value = ReadGuid(offset); break; case ODBC32.SQL_C.TYPE_TIMESTAMP: //So we are mapping this ourselves. //typedef struct tagTIMESTAMP_STRUCT //{ // SQLSMALLINT year; // SQLUSMALLINT month; // SQLUSMALLINT day; // SQLUSMALLINT hour; // SQLUSMALLINT minute; // SQLUSMALLINT second; // SQLUINTEGER fraction; (billoniths of a second) //} value = ReadDateTime(offset); break; // Note: System does not provide a date-only type case ODBC32.SQL_C.TYPE_DATE: // typedef struct tagDATE_STRUCT // { // SQLSMALLINT year; // SQLUSMALLINT month; // SQLUSMALLINT day; // } DATE_STRUCT; value = ReadDate(offset); break; // Note: System does not provide a date-only type case ODBC32.SQL_C.TYPE_TIME: // typedef struct tagTIME_STRUCT // { // SQLUSMALLINT hour; // SQLUSMALLINT minute; // SQLUSMALLINT second; // } TIME_STRUCT; value = ReadTime(offset); break; case ODBC32.SQL_C.NUMERIC: //Note: Unfortunatly the ODBC NUMERIC structure and the URT DECIMAL structure do not //align, so we can't so do the typical "PtrToStructure" call (below) like other types //We actually have to go through the pain of pulling our raw bytes and building the decimal // Marshal.PtrToStructure(buffer, typeof(decimal)); //So we are mapping this ourselves //typedef struct tagSQL_NUMERIC_STRUCT //{ // SQLCHAR precision; // SQLSCHAR scale; // SQLCHAR sign; /* 1 if positive, 0 if negative */ // SQLCHAR val[SQL_MAX_NUMERIC_LEN]; //} SQL_NUMERIC_STRUCT; value = ReadNumeric(offset); break; default: Debug.Assert(false, "UnknownSQLCType"); value = null; break; }; return value; } // if sizeorprecision applies only for wchar and numeric values // for wchar the a value of null means take the value's size // internal void MarshalToNative(int offset, object value, ODBC32.SQL_C sqlctype, int sizeorprecision, int valueOffset) { switch (sqlctype) { case ODBC32.SQL_C.WCHAR: { //Note: We always bind as unicode //Note: StructureToPtr fails indicating string it a non-blittable type //and there is no MarshalStringTo* that moves to an existing buffer, //they all alloc and return a new one, not at all what we want... //So we have to copy the raw bytes of the string ourself?! char[] rgChars; int length; Debug.Assert(value is string || value is char[], "Only string or char[] can be marshaled to WCHAR"); if (value is string) { length = Math.Max(0, ((string)value).Length - valueOffset); if ((sizeorprecision > 0) && (sizeorprecision < length)) { length = sizeorprecision; } rgChars = ((string)value).ToCharArray(valueOffset, length); Debug.Assert(rgChars.Length < (base.Length - valueOffset), "attempting to extend parameter buffer!"); WriteCharArray(offset, rgChars, 0, rgChars.Length); WriteInt16(offset + (rgChars.Length * 2), 0); // Add the null terminator } else { length = Math.Max(0, ((char[])value).Length - valueOffset); if ((sizeorprecision > 0) && (sizeorprecision < length)) { length = sizeorprecision; } rgChars = (char[])value; Debug.Assert(rgChars.Length < (base.Length - valueOffset), "attempting to extend parameter buffer!"); WriteCharArray(offset, rgChars, valueOffset, length); WriteInt16(offset + (rgChars.Length * 2), 0); // Add the null terminator } break; } case ODBC32.SQL_C.BINARY: case ODBC32.SQL_C.CHAR: { byte[] rgBytes = (byte[])value; int length = rgBytes.Length; Debug.Assert((valueOffset <= length), "Offset out of Range"); // reduce length by the valueOffset // length -= valueOffset; // reduce length to be no more than size (if size is given) // if ((sizeorprecision > 0) && (sizeorprecision < length)) { length = sizeorprecision; } //AdjustSize(rgBytes.Length+1); //buffer = DangerousAllocateAndGetHandle(); // Realloc may have changed buffer address Debug.Assert(length < (base.Length - valueOffset), "attempting to extend parameter buffer!"); WriteBytes(offset, rgBytes, valueOffset, length); break; } case ODBC32.SQL_C.UTINYINT: WriteByte(offset, (byte)value); break; case ODBC32.SQL_C.SSHORT: //Int16 WriteInt16(offset, (short)value); break; case ODBC32.SQL_C.SLONG: //Int32 WriteInt32(offset, (int)value); break; case ODBC32.SQL_C.REAL: //float WriteSingle(offset, (float)value); break; case ODBC32.SQL_C.SBIGINT: //Int64 WriteInt64(offset, (long)value); break; case ODBC32.SQL_C.DOUBLE: //Double WriteDouble(offset, (double)value); break; case ODBC32.SQL_C.GUID: //Guid WriteGuid(offset, (Guid)value); break; case ODBC32.SQL_C.BIT: WriteByte(offset, (byte)(((bool)value) ? 1 : 0)); break; case ODBC32.SQL_C.TYPE_TIMESTAMP: { //typedef struct tagTIMESTAMP_STRUCT //{ // SQLSMALLINT year; // SQLUSMALLINT month; // SQLUSMALLINT day; // SQLUSMALLINT hour; // SQLUSMALLINT minute; // SQLUSMALLINT second; // SQLUINTEGER fraction; (billoniths of a second) //} //We have to map this ourselves, due to the different structures between //ODBC TIMESTAMP and URT DateTime, (ie: can't use StructureToPtr) WriteODBCDateTime(offset, (DateTime)value); break; } // Note: System does not provide a date-only type case ODBC32.SQL_C.TYPE_DATE: { // typedef struct tagDATE_STRUCT // { // SQLSMALLINT year; // SQLUSMALLINT month; // SQLUSMALLINT day; // } DATE_STRUCT; WriteDate(offset, (DateTime)value); break; } // Note: System does not provide a date-only type case ODBC32.SQL_C.TYPE_TIME: { // typedef struct tagTIME_STRUCT // { // SQLUSMALLINT hour; // SQLUSMALLINT minute; // SQLUSMALLINT second; // } TIME_STRUCT; WriteTime(offset, (TimeSpan)value); break; } case ODBC32.SQL_C.NUMERIC: { WriteNumeric(offset, (decimal)value, checked((byte)sizeorprecision)); break; } default: Debug.Assert(false, "UnknownSQLCType"); break; } } internal HandleRef PtrOffset(int offset, int length) { //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // NOTE: You must have called DangerousAddRef before calling this // method, or you run the risk of allowing Handle Recycling // to occur! //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Validate(offset, length); IntPtr ptr = ADP.IntPtrOffset(DangerousGetHandle(), offset); return new HandleRef(this, ptr); } internal void WriteODBCDateTime(int offset, DateTime value) { short[] buffer = new short[6] { unchecked((short)value.Year), unchecked((short)value.Month), unchecked((short)value.Day), unchecked((short)value.Hour), unchecked((short)value.Minute), unchecked((short)value.Second), }; WriteInt16Array(offset, buffer, 0, 6); WriteInt32(offset + 12, value.Millisecond * 1000000); //fraction } } internal sealed class CStringTokenizer { private readonly StringBuilder _token; private readonly string _sqlstatement; private readonly char _quote; // typically the semicolon '"' private readonly char _escape; // typically the same char as the quote private int _len = 0; private int _idx = 0; internal CStringTokenizer(string text, char quote, char escape) { _token = new StringBuilder(); _quote = quote; _escape = escape; _sqlstatement = text; if (text != null) { int iNul = text.IndexOf('\0'); _len = (0 > iNul) ? text.Length : iNul; } else { _len = 0; } } internal int CurrentPosition { get { return _idx; } } // Returns the next token in the statement, advancing the current index to // the start of the token internal string NextToken() { if (_token.Length != 0) { // if we've read a token before _idx += _token.Length; // proceed the internal marker (_idx) behind the token _token.Remove(0, _token.Length); // and start over with a fresh token } while ((_idx < _len) && char.IsWhiteSpace(_sqlstatement[_idx])) { // skip whitespace _idx++; } if (_idx == _len) { // return if string is empty return string.Empty; } int curidx = _idx; // start with internal index at current index bool endtoken = false; // // process characters until we reache the end of the token or the end of the string // while (!endtoken && curidx < _len) { if (IsValidNameChar(_sqlstatement[curidx])) { while ((curidx < _len) && IsValidNameChar(_sqlstatement[curidx])) { _token.Append(_sqlstatement[curidx]); curidx++; } } else { char currentchar = _sqlstatement[curidx]; if (currentchar == '[') { curidx = GetTokenFromBracket(curidx); } else if (' ' != _quote && currentchar == _quote) { // if the ODBC driver does not support quoted identifiers it returns a single blank character curidx = GetTokenFromQuote(curidx); } else { // Some other marker like , ; ( or ) // could also be * or ? if (!char.IsWhiteSpace(currentchar)) { switch (currentchar) { case ',': // commas are not part of a token so we'll only append them if they are at the beginning if (curidx == _idx) _token.Append(currentchar); break; default: _token.Append(currentchar); break; } } endtoken = true; break; } } } return (_token.Length > 0) ? _token.ToString() : string.Empty; } private int GetTokenFromBracket(int curidx) { Debug.Assert((_sqlstatement[curidx] == '['), "GetTokenFromQuote: character at starting position must be same as quotechar"); while (curidx < _len) { _token.Append(_sqlstatement[curidx]); curidx++; if (_sqlstatement[curidx - 1] == ']') break; } return curidx; } // attempts to complete an encapsulated token (e.g. "scott") // double quotes are valid part of the token (e.g. "foo""bar") // private int GetTokenFromQuote(int curidx) { Debug.Assert(_quote != ' ', "ODBC driver doesn't support quoted identifiers -- GetTokenFromQuote should not be used in this case"); Debug.Assert((_sqlstatement[curidx] == _quote), "GetTokenFromQuote: character at starting position must be same as quotechar"); int localidx = curidx; // start with local index at current index while (localidx < _len) { // run to the end of the statement _token.Append(_sqlstatement[localidx]); // append current character to token if (_sqlstatement[localidx] == _quote) { if (localidx > curidx) { // don't care for the first char if (_sqlstatement[localidx - 1] != _escape) { // if it's not escape we look at the following char if (localidx + 1 < _len) { // do not overrun the end of the string if (_sqlstatement[localidx + 1] != _quote) { return localidx + 1; // We've reached the end of the quoted text } } } } } localidx++; } return localidx; } private bool IsValidNameChar(char ch) { return (char.IsLetterOrDigit(ch) || (ch == '_') || (ch == '-') || (ch == '.') || (ch == '$') || (ch == '#') || (ch == '@') || (ch == '~') || (ch == '`') || (ch == '%') || (ch == '^') || (ch == '&') || (ch == '|')); } // Searches for the token given, starting from the current position // If found, positions the currentindex at the // beginning of the token if found. internal int FindTokenIndex(string tokenString) { string nextToken; while (true) { nextToken = NextToken(); if ((_idx == _len) || string.IsNullOrEmpty(nextToken)) { // fxcop break; } if (string.Equals(tokenString, nextToken, StringComparison.OrdinalIgnoreCase)) { return _idx; } } return -1; } // Skips the whitespace found in the beginning of the string. internal bool StartsWith(string tokenString) { int tempidx = 0; while ((tempidx < _len) && char.IsWhiteSpace(_sqlstatement[tempidx])) { tempidx++; } if ((_len - tempidx) < tokenString.Length) { return false; } if (0 == string.Compare(_sqlstatement, tempidx, tokenString, 0, tokenString.Length, StringComparison.OrdinalIgnoreCase)) { // Reset current position and token _idx = 0; NextToken(); return true; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; ///<summary> ///System.Test.UnicodeEncoding.GetString(System.Byte[],System.Int32,System.Int32) [v-zuolan] ///</summary> public class UnicodeEncodingGetString { public static int Main() { UnicodeEncodingGetString testObj = new UnicodeEncodingGetString(); TestLibrary.TestFramework.BeginTestCase("for method of System.Test.UnicodeEncoding.GetString"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("Positive"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; TestLibrary.TestFramework.LogInformation("Positive"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; retVal = NegTest5() && retVal; return retVal; } #region Helper Method //Create a None-Surrogate-Char Array. public Char[] GetCharArray(int length) { if (length <= 0) return new Char[] { }; Char[] charArray = new Char[length]; int i = 0; while (i < length) { Char temp = TestLibrary.Generator.GetChar(-55); if (!Char.IsSurrogate(temp)) { charArray[i] = temp; i++; } } return charArray; } //Convert Char Array to String public String ToString(Char[] chars) { String str = "{"; for (int i = 0; i < chars.Length; i++) { str = str + @"\u" + String.Format("{0:X04}", (int)chars[i]); if (i != chars.Length - 1) str = str + ","; } str = str + "}"; return str; } #endregion #region Positive Test Logic public bool PosTest1() { bool retVal = true; Char[] srcChars = GetCharArray(10); Char[] desChars = new Char[10]; Byte[] bytes = new Byte[20]; UnicodeEncoding uEncoding = new UnicodeEncoding(); int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0); bool expectedValue = true; bool actualValue = true; TestLibrary.TestFramework.BeginScenario("PosTest1:Invoke the method"); try { String desString = uEncoding.GetString(bytes, 0, 20); desChars = desString.ToCharArray(); for (int i = 0; i < 10; i++) { actualValue = actualValue & (desChars[i] == srcChars[i]); } if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("001", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")" + " when chars is :" + ToString(srcChars)); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e + " when chars is :" + ToString(srcChars)); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; Char[] srcChars = GetCharArray(10); Char[] desChars = new Char[10]; Byte[] bytes = new Byte[20]; UnicodeEncoding uEncoding = new UnicodeEncoding(); int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0); bool expectedValue = true; bool actualValue = true; TestLibrary.TestFramework.BeginScenario("PosTest2:Invoke the method,convert 1 char"); try { String desString = uEncoding.GetString(bytes, 0, 2); desChars = desString.ToCharArray(); for (int i = 0; i < 1; i++) { actualValue = actualValue & (desChars[i] == srcChars[i]); } if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("003", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")" + " when chars is :" + ToString(srcChars)); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception:" + e + " when chars is :" + ToString(srcChars)); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; Char[] srcChars = GetCharArray(10); Char[] desChars = new Char[10]; Byte[] bytes = new Byte[20]; UnicodeEncoding uEncoding = new UnicodeEncoding(); int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0); String expectedValue = ""; String actualValue; TestLibrary.TestFramework.BeginScenario("PosTest3:Invoke the method and set byteIndex as 0 and byteCount as 0."); try { actualValue = uEncoding.GetString(bytes, 0, 0); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("005", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")" + " when chars is :" + ToString(srcChars)); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception:" + e + " when chars is :" + ToString(srcChars)); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; Char[] srcChars = GetCharArray(10); Char[] desChars = new Char[10]; Byte[] bytes = new Byte[20]; UnicodeEncoding uEncoding = new UnicodeEncoding(); int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0); String expectedValue = ""; String actualValue; TestLibrary.TestFramework.BeginScenario("PosTest4:Invoke the method and set byteIndex out of range."); try { actualValue = uEncoding.GetString(bytes, 20, 0); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("017", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")" + " when chars is :" + ToString(srcChars)); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("018", "Unexpected exception:" + e); retVal = false; } return retVal; } #endregion #region Negative Test Logic public bool NegTest1() { bool retVal = true; Char[] srcChars = GetCharArray(10); Char[] desChars = new Char[10]; Byte[] bytes = new Byte[20]; UnicodeEncoding uEncoding = new UnicodeEncoding(); int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0); String actualValue; TestLibrary.TestFramework.BeginScenario("NegTest1:Invoke the method and set chars as null"); try { actualValue = uEncoding.GetString(null,0,0); TestLibrary.TestFramework.LogError("007", "No ArgumentNullException throw out expected."); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; Char[] srcChars = GetCharArray(10); Char[] desChars = new Char[10]; Byte[] bytes = new Byte[20]; UnicodeEncoding uEncoding = new UnicodeEncoding(); int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0); String actualValue; TestLibrary.TestFramework.BeginScenario("NegTest2:Invoke the method and set byteIndex out of range."); try { actualValue = uEncoding.GetString(bytes, 21, 0); TestLibrary.TestFramework.LogError("009", "No ArgumentOutOfRangeException throw out expected."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; Char[] srcChars = GetCharArray(10); Char[] desChars = new Char[10]; Byte[] bytes = new Byte[20]; UnicodeEncoding uEncoding = new UnicodeEncoding(); int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0); String actualValue; TestLibrary.TestFramework.BeginScenario("NegTest3:Invoke the method and set byteIndex out of range."); try { actualValue = uEncoding.GetString(bytes, -1, 0); TestLibrary.TestFramework.LogError("011", "No ArgumentOutOfRangeException throw out expected."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; Char[] srcChars = GetCharArray(10); Char[] desChars = new Char[10]; Byte[] bytes = new Byte[20]; UnicodeEncoding uEncoding = new UnicodeEncoding(); int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0); String actualValue; TestLibrary.TestFramework.BeginScenario("NegTest4:Invoke the method and set byteCount out of range."); try { actualValue = uEncoding.GetString(bytes, 0, -1); TestLibrary.TestFramework.LogError("013", "No ArgumentOutOfRangeException throw out expected."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("014", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool NegTest5() { bool retVal = true; Char[] srcChars = GetCharArray(10); Char[] desChars = new Char[10]; Byte[] bytes = new Byte[20]; UnicodeEncoding uEncoding = new UnicodeEncoding(); int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0); String actualValue; TestLibrary.TestFramework.BeginScenario("NegTest5:Invoke the method and set byteCount out of range."); try { actualValue = uEncoding.GetString(bytes, 0, 21); TestLibrary.TestFramework.LogError("015", "No ArgumentOutOfRangeException throw out expected."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("016", "Unexpected exception:" + e); retVal = false; } return retVal; } #endregion }
/* * RepeatElement.cs */ using System; using System.Collections; using System.IO; using Core.Library; namespace Core.Library.RE { /** * A regular expression element repeater. The element repeats the * matches from a specified element, attempting to reach the * maximum repetition count. * * */ internal class RepeatElement : Element { /** * The repeat type constants. */ public enum RepeatType { /** * The greedy repeat type constant. */ GREEDY = 1, /** * The reluctant repeat type constant. */ RELUCTANT = 2, /** * The possesive repeat type constant. */ POSSESSIVE = 3 } /** * The element to repeat. */ private Element elem; /** * The minimum number of repetitions. */ private int min; /** * The maximum number of repetitions. */ private int max; /** * The repeat type. */ private RepeatType type; /** * The start position of the last set of matches. */ private int matchStart; /** * A set with all matches starting at matchStart. A match with * a specific length is reported by a non-zero bit in the bit * array. */ private BitArray matches; /** * Creats a new element repeater. * * @param elem the element to repeat * @param min the minimum count * @param max the maximum count * @param type the repeat type constant */ public RepeatElement(Element elem, int min, int max, RepeatType type) { this.elem = elem; this.min = min; if (max <= 0) { this.max = Int32.MaxValue; } else { this.max = max; } this.type = type; this.matchStart = -1; this.matches = null; } /** * Creates a copy of this element. The copy will be an * instance of the same class matching the same strings. * Copies of elements are necessary to allow elements to cache * intermediate results while matching strings without * interfering with other threads. * * @return a copy of this element */ public override object Clone() { return new RepeatElement((Element) elem.Clone(), min, max, type); } /** * Returns the length of a matching string starting at the * specified position. The number of matches to skip can also be * specified. * * @param m the matcher being used * @param buffer the input character buffer to match * @param start the starting position * @param skip the number of matches to skip * * @return the length of the matching string, or * -1 if no match was found * * @throws IOException if an I/O error occurred */ public override int Match(Matcher m, ReaderBuffer buffer, int start, int skip) { if (skip == 0) { matchStart = -1; matches = null; } switch (type) { case RepeatType.GREEDY: return MatchGreedy(m, buffer, start, skip); case RepeatType.RELUCTANT: return MatchReluctant(m, buffer, start, skip); case RepeatType.POSSESSIVE: if (skip == 0) { return MatchPossessive(m, buffer, start, 0); } break; } return -1; } /** * Returns the length of the longest possible matching string * starting at the specified position. The number of matches * to skip can also be specified. * * @param m the matcher being used * @param buffer the input character buffer to match * @param start the starting position * @param skip the number of matches to skip * * @return the length of the longest matching string, or * -1 if no match was found * * @throws IOException if an I/O error occurred */ private int MatchGreedy(Matcher m, ReaderBuffer buffer, int start, int skip) { // Check for simple case if (skip == 0) { return MatchPossessive(m, buffer, start, 0); } // Find all matches if (matchStart != start) { matchStart = start; matches = new BitArray(10); FindMatches(m, buffer, start, 0, 0, 0); } // Find first non-skipped match for (int i = matches.Count - 1; i >= 0; i--) { if (matches[i]) { if (skip == 0) { return i; } skip--; } } return -1; } /** * Returns the length of the shortest possible matching string * starting at the specified position. The number of matches to * skip can also be specified. * * @param m the matcher being used * @param buffer the input character buffer to match * @param start the starting position * @param skip the number of matches to skip * * @return the length of the shortest matching string, or * -1 if no match was found * * @throws IOException if an I/O error occurred */ private int MatchReluctant(Matcher m, ReaderBuffer buffer, int start, int skip) { // Find all matches if (matchStart != start) { matchStart = start; matches = new BitArray(10); FindMatches(m, buffer, start, 0, 0, 0); } // Find first non-skipped match for (int i = 0; i < matches.Count; i++) { if (matches[i]) { if (skip == 0) { return i; } skip--; } } return -1; } /** * Returns the length of the maximum number of elements matching * the string starting at the specified position. This method * allows no backtracking, i.e. no skips.. * * @param m the matcher being used * @param buffer the input character buffer to match * @param start the starting position * @param count the start count, normally zero (0) * * @return the length of the longest matching string, or * -1 if no match was found * * @throws IOException if an I/O error occurred */ private int MatchPossessive(Matcher m, ReaderBuffer buffer, int start, int count) { int length = 0; int subLength = 1; // Match as many elements as possible while (subLength > 0 && count < max) { subLength = elem.Match(m, buffer, start + length, 0); if (subLength >= 0) { count++; length += subLength; } } // Return result if (min <= count && count <= max) { return length; } else { return -1; } } /** * Finds all matches and adds the lengths to the matches set. * * @param m the matcher being used * @param buffer the input character buffer to match * @param start the starting position * @param length the match length at the start position * @param count the number of sub-elements matched * @param attempt the number of match attempts here * * @throws IOException if an I/O error occurred */ private void FindMatches(Matcher m, ReaderBuffer buffer, int start, int length, int count, int attempt) { int subLength; // Check match ending here if (count > max) { return; } if (min <= count && attempt == 0) { if (matches.Length <= length) { matches.Length = length + 10; } matches[length] = true; } // Check element match subLength = elem.Match(m, buffer, start, attempt); if (subLength < 0) { return; } else if (subLength == 0) { if (min == count + 1) { if (matches.Length <= length) { matches.Length = length + 10; } matches[length] = true; } return; } // Find alternative and subsequent matches FindMatches(m, buffer, start, length, count, attempt + 1); FindMatches(m, buffer, start + subLength, length + subLength, count + 1, 0); } /** * Prints this element to the specified output stream. * * @param output the output stream to use * @param indent the current indentation */ public override void PrintTo(TextWriter output, string indent) { output.Write(indent + "Repeat (" + min + "," + max + ")"); if (type == RepeatType.RELUCTANT) { output.Write("?"); } else if (type == RepeatType.POSSESSIVE) { output.Write("+"); } output.WriteLine(); elem.PrintTo(output, indent + " "); } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using Adaptive.SimpleBinaryEncoding; namespace Adaptive.SimpleBinaryEncoding.Examples.Generated { public class Car { public const ushort TemplateId = (ushort)1; public const byte TemplateVersion = (byte)0; public const ushort BlockLength = (ushort)45; public const string SematicType = ""; private readonly Car _parentMessage; private DirectBuffer _buffer; private int _offset; private int _limit; private int _actingBlockLength; private int _actingVersion; public int Offset { get { return _offset; } } public Car() { _parentMessage = this; } public void WrapForEncode(DirectBuffer buffer, int offset) { _buffer = buffer; _offset = offset; _actingBlockLength = BlockLength; _actingVersion = TemplateVersion; Limit = offset + _actingBlockLength; } public void WrapForDecode(DirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { _buffer = buffer; _offset = offset; _actingBlockLength = actingBlockLength; _actingVersion = actingVersion; Limit = offset + _actingBlockLength; } public int Size { get { return _limit - _offset; } } public int Limit { get { return _limit; } set { _buffer.CheckLimit(_limit); _limit = value; } } public const int SerialNumberSchemaId = 1; public static string SerialNumberMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const ulong SerialNumberNullValue = 0x8000000000000000UL; public const ulong SerialNumberMinValue = 0x0UL; public const ulong SerialNumberMaxValue = 0x7fffffffffffffffUL; public ulong SerialNumber { get { return _buffer.Uint64GetLittleEndian(_offset + 0); } set { _buffer.Uint64PutLittleEndian(_offset + 0, value); } } public const int ModelYearSchemaId = 2; public static string ModelYearMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const ushort ModelYearNullValue = (ushort)65535; public const ushort ModelYearMinValue = (ushort)0; public const ushort ModelYearMaxValue = (ushort)65534; public ushort ModelYear { get { return _buffer.Uint16GetLittleEndian(_offset + 8); } set { _buffer.Uint16PutLittleEndian(_offset + 8, value); } } public const int AvailableSchemaId = 3; public static string AvailableMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public BooleanType Available { get { return (BooleanType)_buffer.Uint8Get(_offset + 10); } set { _buffer.Uint8Put(_offset + 10, (byte)value); } } public const int CodeSchemaId = 4; public static string CodeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public Model Code { get { return (Model)_buffer.CharGet(_offset + 11); } set { _buffer.CharPut(_offset + 11, (byte)value); } } public const int SomeNumbersSchemaId = 5; public static string SomeNumbersMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const int SomeNumbersNullValue = -2147483648; public const int SomeNumbersMinValue = -2147483647; public const int SomeNumbersMaxValue = 2147483647; public const int SomeNumbersLength = 5; public int GetSomeNumbers(int index) { if (index < 0 || index >= 5) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.Int32GetLittleEndian(_offset + 12 + (index * 4)); } public void SetSomeNumbers(int index, int value) { if (index < 0 || index >= 5) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.Int32PutLittleEndian(_offset + 12 + (index * 4), value); } public const int VehicleCodeSchemaId = 6; public static string VehicleCodeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const byte VehicleCodeNullValue = (byte)0; public const byte VehicleCodeMinValue = (byte)32; public const byte VehicleCodeMaxValue = (byte)126; public const int VehicleCodeLength = 6; public byte GetVehicleCode(int index) { if (index < 0 || index >= 6) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 32 + (index * 1)); } public void SetVehicleCode(int index, byte value) { if (index < 0 || index >= 6) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 32 + (index * 1), value); } public const string VehicleCodeCharacterEncoding = "UTF-8"; public int GetVehicleCode(byte[] dst, int dstOffset) { const int length = 6; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 32, dst, dstOffset, length); return length; } public void SetVehicleCode(byte[] src, int srcOffset) { const int length = 6; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 32, src, srcOffset, length); } public const int ExtrasSchemaId = 7; public static string ExtrasMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public OptionalExtras Extras { get { return (OptionalExtras)_buffer.Uint8Get(_offset + 38); } set { _buffer.Uint8Put(_offset + 38, (byte)value); } } public const int EngineSchemaId = 8; public static string EngineMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } private readonly Engine _engine = new Engine(); public Engine Engine { get { _engine.Wrap(_buffer, _offset + 39, _actingVersion); return _engine; } } private readonly FuelFiguresGroup _fuelFigures = new FuelFiguresGroup(); public const long FuelFiguresSchemaId = 9; public FuelFiguresGroup FuelFigures { get { _fuelFigures.WrapForDecode(_parentMessage, _buffer, _actingVersion); return _fuelFigures; } } public FuelFiguresGroup FuelFiguresCount(int count) { _fuelFigures.WrapForEncode(_parentMessage, _buffer, count); return _fuelFigures; } public class FuelFiguresGroup { private readonly GroupSizeEncoding _dimensions = new GroupSizeEncoding(); private Car _parentMessage; private DirectBuffer _buffer; private int _blockLength; private int _actingVersion; private int _count; private int _index; private int _offset; public void WrapForDecode(Car parentMessage, DirectBuffer buffer, int actingVersion) { _parentMessage = parentMessage; _buffer = buffer; _dimensions.Wrap(buffer, parentMessage.Limit, actingVersion); _count = _dimensions.NumInGroup; _blockLength = _dimensions.BlockLength; _actingVersion = actingVersion; _index = -1; _parentMessage.Limit = parentMessage.Limit + 3; } public void WrapForEncode(Car parentMessage, DirectBuffer buffer, int count) { _parentMessage = parentMessage; _buffer = buffer; _dimensions.Wrap(buffer, parentMessage.Limit, _actingVersion); _dimensions.NumInGroup = (byte)count; _dimensions.BlockLength = (ushort)6; _index = -1; _count = count; _blockLength = 6; parentMessage.Limit = parentMessage.Limit + 3; } public int Count { get { return _count; } } public bool HasNext { get { return _index + 1 < _count; } } public FuelFiguresGroup Next() { if (_index + 1 >= _count) { throw new InvalidOperationException(); } _offset = _parentMessage.Limit; _parentMessage.Limit = _offset + _blockLength; ++_index; return this; } public const int SpeedSchemaId = 10; public static string SpeedMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const ushort SpeedNullValue = (ushort)65535; public const ushort SpeedMinValue = (ushort)0; public const ushort SpeedMaxValue = (ushort)65534; public ushort Speed { get { return _buffer.Uint16GetLittleEndian(_offset + 0); } set { _buffer.Uint16PutLittleEndian(_offset + 0, value); } } public const int MpgSchemaId = 11; public static string MpgMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const float MpgNullValue = float.NaN; public const float MpgMinValue = 1.401298464324817E-45f; public const float MpgMaxValue = 3.4028234663852886E38f; public float Mpg { get { return _buffer.FloatGetLittleEndian(_offset + 2); } set { _buffer.FloatPutLittleEndian(_offset + 2, value); } } } private readonly PerformanceFiguresGroup _performanceFigures = new PerformanceFiguresGroup(); public const long PerformanceFiguresSchemaId = 12; public PerformanceFiguresGroup PerformanceFigures { get { _performanceFigures.WrapForDecode(_parentMessage, _buffer, _actingVersion); return _performanceFigures; } } public PerformanceFiguresGroup PerformanceFiguresCount(int count) { _performanceFigures.WrapForEncode(_parentMessage, _buffer, count); return _performanceFigures; } public class PerformanceFiguresGroup { private readonly GroupSizeEncoding _dimensions = new GroupSizeEncoding(); private Car _parentMessage; private DirectBuffer _buffer; private int _blockLength; private int _actingVersion; private int _count; private int _index; private int _offset; public void WrapForDecode(Car parentMessage, DirectBuffer buffer, int actingVersion) { _parentMessage = parentMessage; _buffer = buffer; _dimensions.Wrap(buffer, parentMessage.Limit, actingVersion); _count = _dimensions.NumInGroup; _blockLength = _dimensions.BlockLength; _actingVersion = actingVersion; _index = -1; _parentMessage.Limit = parentMessage.Limit + 3; } public void WrapForEncode(Car parentMessage, DirectBuffer buffer, int count) { _parentMessage = parentMessage; _buffer = buffer; _dimensions.Wrap(buffer, parentMessage.Limit, _actingVersion); _dimensions.NumInGroup = (byte)count; _dimensions.BlockLength = (ushort)1; _index = -1; _count = count; _blockLength = 1; parentMessage.Limit = parentMessage.Limit + 3; } public int Count { get { return _count; } } public bool HasNext { get { return _index + 1 < _count; } } public PerformanceFiguresGroup Next() { if (_index + 1 >= _count) { throw new InvalidOperationException(); } _offset = _parentMessage.Limit; _parentMessage.Limit = _offset + _blockLength; ++_index; return this; } public const int OctaneRatingSchemaId = 13; public static string OctaneRatingMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const byte OctaneRatingNullValue = (byte)255; public const byte OctaneRatingMinValue = (byte)90; public const byte OctaneRatingMaxValue = (byte)110; public byte OctaneRating { get { return _buffer.Uint8Get(_offset + 0); } set { _buffer.Uint8Put(_offset + 0, value); } } private readonly AccelerationGroup _acceleration = new AccelerationGroup(); public const long AccelerationSchemaId = 14; public AccelerationGroup Acceleration { get { _acceleration.WrapForDecode(_parentMessage, _buffer, _actingVersion); return _acceleration; } } public AccelerationGroup AccelerationCount(int count) { _acceleration.WrapForEncode(_parentMessage, _buffer, count); return _acceleration; } public class AccelerationGroup { private readonly GroupSizeEncoding _dimensions = new GroupSizeEncoding(); private Car _parentMessage; private DirectBuffer _buffer; private int _blockLength; private int _actingVersion; private int _count; private int _index; private int _offset; public void WrapForDecode(Car parentMessage, DirectBuffer buffer, int actingVersion) { _parentMessage = parentMessage; _buffer = buffer; _dimensions.Wrap(buffer, parentMessage.Limit, actingVersion); _count = _dimensions.NumInGroup; _blockLength = _dimensions.BlockLength; _actingVersion = actingVersion; _index = -1; _parentMessage.Limit = parentMessage.Limit + 3; } public void WrapForEncode(Car parentMessage, DirectBuffer buffer, int count) { _parentMessage = parentMessage; _buffer = buffer; _dimensions.Wrap(buffer, parentMessage.Limit, _actingVersion); _dimensions.NumInGroup = (byte)count; _dimensions.BlockLength = (ushort)6; _index = -1; _count = count; _blockLength = 6; parentMessage.Limit = parentMessage.Limit + 3; } public int Count { get { return _count; } } public bool HasNext { get { return _index + 1 < _count; } } public AccelerationGroup Next() { if (_index + 1 >= _count) { throw new InvalidOperationException(); } _offset = _parentMessage.Limit; _parentMessage.Limit = _offset + _blockLength; ++_index; return this; } public const int MphSchemaId = 15; public static string MphMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const ushort MphNullValue = (ushort)65535; public const ushort MphMinValue = (ushort)0; public const ushort MphMaxValue = (ushort)65534; public ushort Mph { get { return _buffer.Uint16GetLittleEndian(_offset + 0); } set { _buffer.Uint16PutLittleEndian(_offset + 0, value); } } public const int SecondsSchemaId = 16; public static string SecondsMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const float SecondsNullValue = float.NaN; public const float SecondsMinValue = 1.401298464324817E-45f; public const float SecondsMaxValue = 3.4028234663852886E38f; public float Seconds { get { return _buffer.FloatGetLittleEndian(_offset + 2); } set { _buffer.FloatPutLittleEndian(_offset + 2, value); } } } } public const int MakeSchemaId = 17; public const string MakeCharacterEncoding = "UTF-8"; public static string MakeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "Make"; } return ""; } public int GetMake(byte[] dst, int dstOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; _buffer.CheckLimit(limit + sizeOfLengthField); int dataLength = _buffer.Uint8Get(limit); int bytesCopied = Math.Min(length, dataLength); Limit = limit + sizeOfLengthField + dataLength; _buffer.GetBytes(limit + sizeOfLengthField, dst, dstOffset, bytesCopied); return bytesCopied; } public int SetMake(byte[] src, int srcOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; Limit = limit + sizeOfLengthField + length; _buffer.Uint8Put(limit, (byte)length); _buffer.SetBytes(limit + sizeOfLengthField, src, srcOffset, length); return length; } public const int ModelSchemaId = 18; public const string ModelCharacterEncoding = "UTF-8"; public static string ModelMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public int GetModel(byte[] dst, int dstOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; _buffer.CheckLimit(limit + sizeOfLengthField); int dataLength = _buffer.Uint8Get(limit); int bytesCopied = Math.Min(length, dataLength); Limit = limit + sizeOfLengthField + dataLength; _buffer.GetBytes(limit + sizeOfLengthField, dst, dstOffset, bytesCopied); return bytesCopied; } public int SetModel(byte[] src, int srcOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; Limit = limit + sizeOfLengthField + length; _buffer.Uint8Put(limit, (byte)length); _buffer.SetBytes(limit + sizeOfLengthField, src, srcOffset, length); return length; } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type SiteItemsCollectionRequest. /// </summary> public partial class SiteItemsCollectionRequest : BaseRequest, ISiteItemsCollectionRequest { /// <summary> /// Constructs a new SiteItemsCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public SiteItemsCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified BaseItem to the collection via POST. /// </summary> /// <param name="baseItem">The BaseItem to add.</param> /// <returns>The created BaseItem.</returns> public System.Threading.Tasks.Task<BaseItem> AddAsync(BaseItem baseItem) { return this.AddAsync(baseItem, CancellationToken.None); } /// <summary> /// Adds the specified BaseItem to the collection via POST. /// </summary> /// <param name="baseItem">The BaseItem to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created BaseItem.</returns> public System.Threading.Tasks.Task<BaseItem> AddAsync(BaseItem baseItem, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; baseItem.ODataType = string.Concat("#", StringHelper.ConvertTypeToLowerCamelCase(baseItem.GetType().FullName)); return this.SendAsync<BaseItem>(baseItem, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<ISiteItemsCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<ISiteItemsCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<SiteItemsCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public ISiteItemsCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public ISiteItemsCollectionRequest Expand(Expression<Func<BaseItem, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public ISiteItemsCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public ISiteItemsCollectionRequest Select(Expression<Func<BaseItem, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public ISiteItemsCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public ISiteItemsCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public ISiteItemsCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public ISiteItemsCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.TrafficManager; using Microsoft.Azure.Management.TrafficManager.Models; namespace Microsoft.Azure.Management.TrafficManager { /// <summary> /// The Windows Azure Traffic Manager management API provides a RESTful set /// of web services that interact with Windows Azure Traffic Manager /// service for creating, updating, listing, and deleting Traffic Manager /// profiles and definitions. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn166981.aspx for /// more information) /// </summary> public static partial class ProfileOperationsExtensions { /// <summary> /// Create or update a WATMv2 profile within a resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.TrafficManager.IProfileOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='profileName'> /// Required. The name of the zone without a terminating dot. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the CreateOrUpdate operation. /// </param> /// <returns> /// The response to a Profile CreateOrUpdate operation. /// </returns> public static ProfileCreateOrUpdateResponse CreateOrUpdate(this IProfileOperations operations, string resourceGroupName, string profileName, ProfileCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IProfileOperations)s).CreateOrUpdateAsync(resourceGroupName, profileName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create or update a WATMv2 profile within a resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.TrafficManager.IProfileOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='profileName'> /// Required. The name of the zone without a terminating dot. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the CreateOrUpdate operation. /// </param> /// <returns> /// The response to a Profile CreateOrUpdate operation. /// </returns> public static Task<ProfileCreateOrUpdateResponse> CreateOrUpdateAsync(this IProfileOperations operations, string resourceGroupName, string profileName, ProfileCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, profileName, parameters, CancellationToken.None); } /// <summary> /// Deletes a WATMv2 profile within a resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.TrafficManager.IProfileOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='profileName'> /// Required. The name of the zone without a terminating dot. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IProfileOperations operations, string resourceGroupName, string profileName) { return Task.Factory.StartNew((object s) => { return ((IProfileOperations)s).DeleteAsync(resourceGroupName, profileName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a WATMv2 profile within a resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.TrafficManager.IProfileOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='profileName'> /// Required. The name of the zone without a terminating dot. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IProfileOperations operations, string resourceGroupName, string profileName) { return operations.DeleteAsync(resourceGroupName, profileName, CancellationToken.None); } /// <summary> /// Gets a WATMv2 profile within a resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.TrafficManager.IProfileOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='profileName'> /// Required. The name of the zone without a terminating dot. /// </param> /// <returns> /// The response to a Profile Create operation. /// </returns> public static ProfileGetResponse Get(this IProfileOperations operations, string resourceGroupName, string profileName) { return Task.Factory.StartNew((object s) => { return ((IProfileOperations)s).GetAsync(resourceGroupName, profileName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a WATMv2 profile within a resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.TrafficManager.IProfileOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='profileName'> /// Required. The name of the zone without a terminating dot. /// </param> /// <returns> /// The response to a Profile Create operation. /// </returns> public static Task<ProfileGetResponse> GetAsync(this IProfileOperations operations, string resourceGroupName, string profileName) { return operations.GetAsync(resourceGroupName, profileName, CancellationToken.None); } /// <summary> /// Lists all WATMv2 profile within a subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.TrafficManager.IProfileOperations. /// </param> /// <returns> /// The response to a Profile ProfileListAll operation. /// </returns> public static ProfileListResponse ListAll(this IProfileOperations operations) { return Task.Factory.StartNew((object s) => { return ((IProfileOperations)s).ListAllAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all WATMv2 profile within a subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.TrafficManager.IProfileOperations. /// </param> /// <returns> /// The response to a Profile ProfileListAll operation. /// </returns> public static Task<ProfileListResponse> ListAllAsync(this IProfileOperations operations) { return operations.ListAllAsync(CancellationToken.None); } /// <summary> /// Lists all WATMv2 profiles within a resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.TrafficManager.IProfileOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <returns> /// The response to a Profile ProfileListAll operation. /// </returns> public static ProfileListResponse ListAllInResourceGroup(this IProfileOperations operations, string resourceGroupName) { return Task.Factory.StartNew((object s) => { return ((IProfileOperations)s).ListAllInResourceGroupAsync(resourceGroupName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all WATMv2 profiles within a resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.TrafficManager.IProfileOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <returns> /// The response to a Profile ProfileListAll operation. /// </returns> public static Task<ProfileListResponse> ListAllInResourceGroupAsync(this IProfileOperations operations, string resourceGroupName) { return operations.ListAllInResourceGroupAsync(resourceGroupName, CancellationToken.None); } } }
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// TaxCountry /// </summary> [DataContract] public partial class TaxCountry : IEquatable<TaxCountry>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="TaxCountry" /> class. /// </summary> /// <param name="accountingCode">Accounting code for programs such as QuickBooks.</param> /// <param name="countryCode">Country code (2 characters.</param> /// <param name="countryOid">Tax record object identifier used internally by database.</param> /// <param name="states">States (or regions or territories) within this country.</param> /// <param name="taxGiftCharge">True if taxation within this jurisdiction should charge tax on gift charge.</param> /// <param name="taxGiftWrap">True if taxation within this jurisdiction should charge tax on gift wrap.</param> /// <param name="taxRate">Tax Rate.</param> /// <param name="taxRateFormatted">Tax rate formatted.</param> /// <param name="taxShipping">True if taxation within this jurisdiction should charge tax on shipping.</param> public TaxCountry(string accountingCode = default(string), string countryCode = default(string), int? countryOid = default(int?), List<TaxState> states = default(List<TaxState>), bool? taxGiftCharge = default(bool?), bool? taxGiftWrap = default(bool?), decimal? taxRate = default(decimal?), string taxRateFormatted = default(string), bool? taxShipping = default(bool?)) { this.AccountingCode = accountingCode; this.CountryCode = countryCode; this.CountryOid = countryOid; this.States = states; this.TaxGiftCharge = taxGiftCharge; this.TaxGiftWrap = taxGiftWrap; this.TaxRate = taxRate; this.TaxRateFormatted = taxRateFormatted; this.TaxShipping = taxShipping; } /// <summary> /// Accounting code for programs such as QuickBooks /// </summary> /// <value>Accounting code for programs such as QuickBooks</value> [DataMember(Name="accounting_code", EmitDefaultValue=false)] public string AccountingCode { get; set; } /// <summary> /// Country code (2 characters /// </summary> /// <value>Country code (2 characters</value> [DataMember(Name="country_code", EmitDefaultValue=false)] public string CountryCode { get; set; } /// <summary> /// Tax record object identifier used internally by database /// </summary> /// <value>Tax record object identifier used internally by database</value> [DataMember(Name="country_oid", EmitDefaultValue=false)] public int? CountryOid { get; set; } /// <summary> /// States (or regions or territories) within this country /// </summary> /// <value>States (or regions or territories) within this country</value> [DataMember(Name="states", EmitDefaultValue=false)] public List<TaxState> States { get; set; } /// <summary> /// True if taxation within this jurisdiction should charge tax on gift charge /// </summary> /// <value>True if taxation within this jurisdiction should charge tax on gift charge</value> [DataMember(Name="tax_gift_charge", EmitDefaultValue=false)] public bool? TaxGiftCharge { get; set; } /// <summary> /// True if taxation within this jurisdiction should charge tax on gift wrap /// </summary> /// <value>True if taxation within this jurisdiction should charge tax on gift wrap</value> [DataMember(Name="tax_gift_wrap", EmitDefaultValue=false)] public bool? TaxGiftWrap { get; set; } /// <summary> /// Tax Rate /// </summary> /// <value>Tax Rate</value> [DataMember(Name="tax_rate", EmitDefaultValue=false)] public decimal? TaxRate { get; set; } /// <summary> /// Tax rate formatted /// </summary> /// <value>Tax rate formatted</value> [DataMember(Name="tax_rate_formatted", EmitDefaultValue=false)] public string TaxRateFormatted { get; set; } /// <summary> /// True if taxation within this jurisdiction should charge tax on shipping /// </summary> /// <value>True if taxation within this jurisdiction should charge tax on shipping</value> [DataMember(Name="tax_shipping", EmitDefaultValue=false)] public bool? TaxShipping { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class TaxCountry {\n"); sb.Append(" AccountingCode: ").Append(AccountingCode).Append("\n"); sb.Append(" CountryCode: ").Append(CountryCode).Append("\n"); sb.Append(" CountryOid: ").Append(CountryOid).Append("\n"); sb.Append(" States: ").Append(States).Append("\n"); sb.Append(" TaxGiftCharge: ").Append(TaxGiftCharge).Append("\n"); sb.Append(" TaxGiftWrap: ").Append(TaxGiftWrap).Append("\n"); sb.Append(" TaxRate: ").Append(TaxRate).Append("\n"); sb.Append(" TaxRateFormatted: ").Append(TaxRateFormatted).Append("\n"); sb.Append(" TaxShipping: ").Append(TaxShipping).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as TaxCountry); } /// <summary> /// Returns true if TaxCountry instances are equal /// </summary> /// <param name="input">Instance of TaxCountry to be compared</param> /// <returns>Boolean</returns> public bool Equals(TaxCountry input) { if (input == null) return false; return ( this.AccountingCode == input.AccountingCode || (this.AccountingCode != null && this.AccountingCode.Equals(input.AccountingCode)) ) && ( this.CountryCode == input.CountryCode || (this.CountryCode != null && this.CountryCode.Equals(input.CountryCode)) ) && ( this.CountryOid == input.CountryOid || (this.CountryOid != null && this.CountryOid.Equals(input.CountryOid)) ) && ( this.States == input.States || this.States != null && this.States.SequenceEqual(input.States) ) && ( this.TaxGiftCharge == input.TaxGiftCharge || (this.TaxGiftCharge != null && this.TaxGiftCharge.Equals(input.TaxGiftCharge)) ) && ( this.TaxGiftWrap == input.TaxGiftWrap || (this.TaxGiftWrap != null && this.TaxGiftWrap.Equals(input.TaxGiftWrap)) ) && ( this.TaxRate == input.TaxRate || (this.TaxRate != null && this.TaxRate.Equals(input.TaxRate)) ) && ( this.TaxRateFormatted == input.TaxRateFormatted || (this.TaxRateFormatted != null && this.TaxRateFormatted.Equals(input.TaxRateFormatted)) ) && ( this.TaxShipping == input.TaxShipping || (this.TaxShipping != null && this.TaxShipping.Equals(input.TaxShipping)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.AccountingCode != null) hashCode = hashCode * 59 + this.AccountingCode.GetHashCode(); if (this.CountryCode != null) hashCode = hashCode * 59 + this.CountryCode.GetHashCode(); if (this.CountryOid != null) hashCode = hashCode * 59 + this.CountryOid.GetHashCode(); if (this.States != null) hashCode = hashCode * 59 + this.States.GetHashCode(); if (this.TaxGiftCharge != null) hashCode = hashCode * 59 + this.TaxGiftCharge.GetHashCode(); if (this.TaxGiftWrap != null) hashCode = hashCode * 59 + this.TaxGiftWrap.GetHashCode(); if (this.TaxRate != null) hashCode = hashCode * 59 + this.TaxRate.GetHashCode(); if (this.TaxRateFormatted != null) hashCode = hashCode * 59 + this.TaxRateFormatted.GetHashCode(); if (this.TaxShipping != null) hashCode = hashCode * 59 + this.TaxShipping.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
// 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; using System.Collections.Generic; using System.Composition.Runtime.Util; using System.Linq; namespace System.Composition.Hosting.Core { /// <summary> /// The link between exports and imports. /// </summary> public sealed class CompositionContract { private readonly Type _contractType; private readonly string _contractName; private readonly IDictionary<string, object> _metadataConstraints; /// <summary> /// Construct a <see cref="CompositionContract"/>. /// </summary> /// <param name="contractType">The type shared between the exporter and importer.</param> public CompositionContract(Type contractType) : this(contractType, null) { } /// <summary> /// Construct a <see cref="CompositionContract"/>. /// </summary> /// <param name="contractType">The type shared between the exporter and importer.</param> /// <param name="contractName">Optionally, a name that discriminates this contract from others with the same type.</param> public CompositionContract(Type contractType, string contractName) : this(contractType, contractName, null) { } /// <summary> /// Construct a <see cref="CompositionContract"/>. /// </summary> /// <param name="contractType">The type shared between the exporter and importer.</param> /// <param name="contractName">Optionally, a name that discriminates this contract from others with the same type.</param> /// <param name="metadataConstraints">Optionally, a non-empty collection of named constraints that apply to the contract.</param> public CompositionContract(Type contractType, string contractName, IDictionary<string, object> metadataConstraints) { if (contractType == null) throw new ArgumentNullException(nameof(contractType)); if (metadataConstraints != null && metadataConstraints.Count == 0) throw new ArgumentOutOfRangeException(nameof(metadataConstraints)); _contractType = contractType; _contractName = contractName; _metadataConstraints = metadataConstraints; } /// <summary> /// The type shared between the exporter and importer. /// </summary> public Type ContractType { get { return _contractType; } } /// <summary> /// A name that discriminates this contract from others with the same type. /// </summary> public string ContractName { get { return _contractName; } } /// <summary> /// Constraints applied to the contract. Instead of using this collection /// directly it is advisable to use the <see cref="TryUnwrapMetadataConstraint"/> method. /// </summary> public IEnumerable<KeyValuePair<string, object>> MetadataConstraints { get { return _metadataConstraints; } } /// <summary> /// Determines equality between two contracts. /// </summary> /// <param name="obj">The contract to test.</param> /// <returns>True if the the contracts are equivalent; otherwise, false.</returns> public override bool Equals(object obj) { var contract = obj as CompositionContract; return contract != null && contract._contractType.Equals(_contractType) && (_contractName == null ? contract._contractName == null : _contractName.Equals(contract._contractName)) && ConstraintEqual(_metadataConstraints, contract._metadataConstraints); } /// <summary> /// Gets a hash code for the contract. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { var hc = _contractType.GetHashCode(); if (_contractName != null) hc = hc ^ _contractName.GetHashCode(); if (_metadataConstraints != null) hc = hc ^ ConstraintHashCode(_metadataConstraints); return hc; } /// <summary> /// Creates a string representaiton of the contract. /// </summary> /// <returns>A string representaiton of the contract.</returns> public override string ToString() { var result = Formatters.Format(_contractType); if (_contractName != null) result += " " + Formatters.Format(_contractName); if (_metadataConstraints != null) result += string.Format(" {{ {0} }}", string.Join(Properties.Resources.Formatter_ListSeparatorWithSpace, _metadataConstraints.Select(kv => string.Format("{0} = {1}", kv.Key, Formatters.Format(kv.Value))))); return result; } /// <summary> /// Transform the contract into a matching contract with a /// new contract type (with the same contract name and constraints). /// </summary> /// <param name="newContractType">The contract type for the new contract.</param> /// <returns>A matching contract with a /// new contract type.</returns> public CompositionContract ChangeType(Type newContractType) { if (newContractType == null) throw new ArgumentNullException(nameof(newContractType)); return new CompositionContract(newContractType, _contractName, _metadataConstraints); } /// <summary> /// Check the contract for a constraint with a particular name and value, and, if it exists, /// retrieve both the value and the remainder of the contract with the constraint /// removed. /// </summary> /// <typeparam name="T">The type of the constraint value.</typeparam> /// <param name="constraintName">The name of the constraint.</param> /// <param name="constraintValue">The value if it is present and of the correct type, otherwise null.</param> /// <param name="remainingContract">The contract with the constraint removed if present, otherwise null.</param> /// <returns>True if the constraint is present and of the correct type, otherwise false.</returns> public bool TryUnwrapMetadataConstraint<T>(string constraintName, out T constraintValue, out CompositionContract remainingContract) { if (constraintName == null) throw new ArgumentNullException(nameof(constraintName)); constraintValue = default(T); remainingContract = null; if (_metadataConstraints == null) return false; object value; if (!_metadataConstraints.TryGetValue(constraintName, out value)) return false; if (!(value is T)) return false; constraintValue = (T)value; if (_metadataConstraints.Count == 1) { remainingContract = new CompositionContract(_contractType, _contractName); } else { var remainingConstraints = new Dictionary<string, object>(_metadataConstraints); remainingConstraints.Remove(constraintName); remainingContract = new CompositionContract(_contractType, _contractName, remainingConstraints); } return true; } internal static bool ConstraintEqual(IDictionary<string, object> first, IDictionary<string, object> second) { if (first == second) return true; if (first == null || second == null) return false; if (first.Count != second.Count) return false; foreach (var firstItem in first) { object secondValue; if (!second.TryGetValue(firstItem.Key, out secondValue)) return false; if (firstItem.Value == null && secondValue != null || secondValue == null && firstItem.Value != null) { return false; } else { var firstEnumerable = firstItem.Value as IEnumerable; if (firstEnumerable != null && !(firstEnumerable is string)) { var secondEnumerable = secondValue as IEnumerable; if (secondEnumerable == null || !Enumerable.SequenceEqual(firstEnumerable.Cast<object>(), secondEnumerable.Cast<object>())) return false; } else if (!firstItem.Value.Equals(secondValue)) { return false; } } } return true; } private static int ConstraintHashCode(IDictionary<string, object> metadata) { var result = -1; foreach (var kv in metadata) { result ^= kv.Key.GetHashCode(); if (kv.Value != null) { var sval = kv.Value as string; if (sval != null) { result ^= sval.GetHashCode(); } else { var enumerableValue = kv.Value as IEnumerable; if (enumerableValue != null) { foreach (var ev in enumerableValue) if (ev != null) result ^= ev.GetHashCode(); } else { result ^= kv.Value.GetHashCode(); } } } } return result; } } }
//----------------------------------------------------------------------- // <copyright file="CuspData.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using System.Diagnostics; using System.Windows; using System.Windows.Media; using System.Windows.Ink; using System.Windows.Input; using System.Collections.Generic; using MS.Internal.Ink.InkSerializedFormat; namespace MS.Internal.Ink { internal class CuspData { /// <summary> /// Default constructor /// </summary> internal CuspData() { } /// <summary> /// Constructs internal data structure from points for doing operations like /// cusp detection or tangent computation /// </summary> /// <param name="stylusPoints">Points to be analyzed</param> /// <param name="rSpan">Distance between two consecutive distinct points</param> internal void Analyze(StylusPointCollection stylusPoints, double rSpan) { // If the count is less than 1, return if ((null == stylusPoints) || (stylusPoints.Count == 0)) return; _points = new List<CDataPoint>(stylusPoints.Count); _nodes = new List<double>(stylusPoints.Count); // Construct the lists of data points and nodes _nodes.Add(0); CDataPoint cdp0 = new CDataPoint(); cdp0.Index = 0; //convert from Avalon to Himetric Point point = (Point)stylusPoints[0]; point.X *= StrokeCollectionSerializer.AvalonToHimetricMultiplier; point.Y *= StrokeCollectionSerializer.AvalonToHimetricMultiplier; cdp0.Point = point; _points.Add(cdp0); //drop duplicates int index = 0; for (int i = 1; i < stylusPoints.Count; i++) { if (!DoubleUtil.AreClose(stylusPoints[i].X, stylusPoints[i - 1].X) || !DoubleUtil.AreClose(stylusPoints[i].Y, stylusPoints[i - 1].Y)) { //this is a unique point, add it index++; CDataPoint cdp = new CDataPoint(); cdp.Index = index; //convert from Avalon to Himetric Point point2 = (Point)stylusPoints[i]; point2.X *= StrokeCollectionSerializer.AvalonToHimetricMultiplier; point2.Y *= StrokeCollectionSerializer.AvalonToHimetricMultiplier; cdp.Point = point2; _points.Insert(index, cdp); _nodes.Insert(index, _nodes[index - 1] + (XY(index) - XY(index - 1)).Length); } } SetLinks(rSpan); } /// <summary> /// Set links amongst the points for tangent computation /// </summary> /// <param name="rError">Shortest distance between two distinct points</param> internal void SetTanLinks(double rError) { int count = Count; if (rError < 1.0) rError = 1.0f; for (int i = 0; i < count; ++i) { // Find a StylusPoint at distance-_span forward for (int j = i + 1; j < count; j++) { if (_nodes[j] - _nodes[i] >= rError) { CDataPoint cdp = _points[i]; cdp.TanNext = j; _points[i] = cdp; CDataPoint cdp2 = _points[j]; cdp2.TanPrev = i; _points[j] = cdp2; break; } } if (0 > _points[i].TanPrev) { for (int j = i - 1; 0 <= j; --j) { if (_nodes[i] - _nodes[j] >= rError) { CDataPoint cdp = _points[i]; cdp.TanPrev = j; _points[i] = cdp; break; } } } if (0 > _points[i].TanNext) { CDataPoint cdp = _points[i]; cdp.TanNext = count - 1; _points[i] = cdp; } if (0 > _points[i].TanPrev) { CDataPoint cdp = _points[i]; cdp.TanPrev = 0; _points[i] = cdp; } } } /// <summary> /// Return the Index of the next cusp or the /// Index of the last StylusPoint if no cusp was found /// </summary> /// <param name="iCurrent">Current StylusPoint Index</param> /// <returns>Index into CuspData object for the next cusp </returns> internal int GetNextCusp(int iCurrent) { int last = Count - 1; if (iCurrent < 0) return 0; if (iCurrent >= last) return last; // Perform a binary search int s = 0, e = _cusps.Count; int m = (s + e) / 2; while (s < m) { if (_cusps[m] <= iCurrent) s = m; else e = m; m = (s + e) / 2; } return _cusps[m + 1]; } /// <summary> /// Point at Index i into the cusp data structure /// </summary> /// <param name="i">Index</param> /// <returns>StylusPoint</returns> /// <remarks>The Index is within the bounds</remarks> internal Vector XY(int i) { return new Vector(_points[i].Point.X, _points[i].Point.Y); } /// <summary> /// Number of points in the internal data structure /// </summary> internal int Count { get { return _points.Count; } } /// <summary> /// Returns the chord length of the i-th StylusPoint from start of the stroke /// </summary> /// <param name="i">StylusPoint Index</param> /// <returns>distance</returns> /// <remarks>The Index is within the bounds</remarks> internal double Node(int i) { return _nodes[i]; } /// <summary> /// Returns the Index into original points given an Index into cusp data /// </summary> /// <param name="nodeIndex">Cusp data Index</param> /// <returns>Original StylusPoint Index</returns> internal int GetPointIndex(int nodeIndex) { return _points[nodeIndex].Index; } /// <summary> /// Distance /// </summary> /// <returns>distance</returns> internal double Distance() { return _dist; } /// <summary> /// Finds the approximante tangent at a given StylusPoint /// </summary> /// <param name="ptT">Tangent vector</param> /// <param name="nAt">Index at which the tangent is calculated</param> /// <param name="nPrevCusp">Index of the previous cusp</param> /// <param name="nNextCusp">Index of the next cusp</param> /// <param name="bReverse">Forward or reverse tangent</param> /// <param name="bIsCusp">Whether the current idex is a cusp StylusPoint</param> /// <returns>Return whether the tangent computation succeeded</returns> internal bool Tangent(ref Vector ptT, int nAt, int nPrevCusp, int nNextCusp, bool bReverse, bool bIsCusp) { // Tangent is computed as the unit vector along // PT = (P1 - P0) + (P2 - P0) + (P3 - P0) // => PT = P1 + P2 + P3 - 3 * P0 int i_1, i_2, i_3; if (bIsCusp) { if (bReverse) { i_1 = _points[nAt].TanPrev; if (i_1 < nPrevCusp || (0 > i_1)) { i_2 = nPrevCusp; i_1 = (i_2 + nAt) / 2; } else { i_2 = _points[i_1].TanPrev; if (i_2 < nPrevCusp) i_2 = nPrevCusp; } } else { i_1 = _points[nAt].TanNext; if (i_1 > nNextCusp || (0 > i_1)) { i_2 = nNextCusp; i_1 = (i_2 + nAt) / 2; } else { i_2 = _points[i_1].TanNext; if (i_2 > nNextCusp) i_2 = nNextCusp; } } ptT = XY(i_1) + 0.5 * XY(i_2) - 1.5 * XY(nAt); } else { Debug.Assert(bReverse); i_1 = nAt; i_2 = _points[nAt].TanPrev; if (i_2 < nPrevCusp) { i_3 = nPrevCusp; i_2 = (i_3 + i_1) / 2; } else { i_3 = _points[i_2].TanPrev; if (i_3 < nPrevCusp) i_3 = nPrevCusp; } nAt = _points[nAt].TanNext; if (nAt > nNextCusp) nAt = nNextCusp; ptT = XY(i_1) + XY(i_2) + 0.5 * XY(i_3) - 2.5 * XY(nAt); } if (DoubleUtil.IsZero(ptT.LengthSquared)) { return false; } ptT.Normalize(); return true; } /// <summary> /// This "curvature" is not the theoretical curvature. it is a number between /// 0 and 2 that is defined as 1 - cos(angle between segments) at this StylusPoint. /// </summary> /// <param name="iPrev">Previous data StylusPoint Index</param> /// <param name="iCurrent">Current data StylusPoint Index </param> /// <param name="iNext">Next data StylusPoint Index</param> /// <returns>"Curvature"</returns> private double GetCurvature(int iPrev, int iCurrent, int iNext) { Vector V = XY(iCurrent) - XY(iPrev); Vector W = XY(iNext) - XY(iCurrent); double r = V.Length * W.Length; if (DoubleUtil.IsZero(r)) return 0; return 1 - (V * W) / r; } /// <summary> /// Find all cusps for the stroke /// </summary> private void FindAllCusps() { // Clear the existing cusp indices _cusps.Clear(); // There is nothing to find out from if (1 > this.Count) return; // First StylusPoint is always a cusp _cusps.Add(0); int iPrev = 0, iNext = 0, iCuspPrev = 0; // Find the next StylusPoint for Index 0 // The following check will cover coincident points, stroke with // less than 3 points if (!FindNextAndPrev(0, iCuspPrev, ref iPrev, ref iNext)) { // Point count is zero, thus, there can't be any cusps if (0 == this.Count) _cusps.Clear(); else if (1 < this.Count) // Last StylusPoint is always a cusp _cusps.Add(iNext); return; } // Start the algorithm with the next StylusPoint int iPoint = iNext; double rCurv = 0; // Check all the points on the chord of the stroke while (FindNextAndPrev(iPoint, iCuspPrev, ref iPrev, ref iNext)) { // Find the curvature at iPoint rCurv = GetCurvature(iPrev, iPoint, iNext); /* We'll look at every StylusPoint where rPrevCurv is a local maximum, and the curvature is more than the noise threashold. If we're near the beginning of the stroke then we'll ignore it and carry on. If we're near the end then we'll skip to the end. Otherwise, we'll flag it as a cusp if it deviates is significantly from the curvature at nearby points, forward and backward */ if (0.80 < rCurv) { double rMaxCurv = rCurv; int iMaxCurv = iPoint; int m = 0, k = 0; if (!FindNextAndPrev(iNext, iCuspPrev, ref k, ref m)) { // End of the stroke has been reached break; } for (int i = iPrev + 1; (i <= m) && FindNextAndPrev(i, iCuspPrev, ref iPrev, ref iNext); ++i) { rCurv = GetCurvature(iPrev, i, iNext); if (rCurv > rMaxCurv) { rMaxCurv = rCurv; iMaxCurv = i; } } // Save the Index with max curvature _cusps.Add(iMaxCurv); // Continue the search with next StylusPoint iPoint = m + 1; iCuspPrev = iMaxCurv; } else if (0.035 > rCurv) { // If the angle is less than 15 degree, skip the segment iPoint = iNext; } else ++iPoint; } // If everything went right, add the last StylusPoint to the list of cusps _cusps.Add(this.Count - 1); } /// <summary> /// Finds the next and previous data StylusPoint Index for the given data Index /// </summary> /// <param name="iPoint">Index at which the computation is performed</param> /// <param name="iPrevCusp">Previous cusp</param> /// <param name="iPrev">Previous data Index</param> /// <param name="iNext">Next data Index</param> /// <returns>Returns true if the end has NOT been reached.</returns> private bool FindNextAndPrev(int iPoint, int iPrevCusp, ref int iPrev, ref int iNext) { bool bHasMore = true; if (iPoint >= Count) { bHasMore = false; iPoint = Count - 1; } // Find a StylusPoint at distance-_span forward for (iNext = checked(iPoint + 1); iNext < Count; ++iNext) if (_nodes[iNext] - _nodes[iPoint] >= _span) break; if (iNext >= Count) { bHasMore = false; iNext = Count - 1; } for (iPrev = checked(iPoint - 1); iPrevCusp <= iPrev; --iPrev) if (_nodes[iPoint] - _nodes[iPrev] >= _span) break; if (iPrev < 0) iPrev = 0; return bHasMore; } /// <summary> /// /// </summary> /// <param name="a"></param> /// <param name="rMin"></param> /// <param name="rMax"></param> private static void UpdateMinMax(double a, ref double rMin, ref double rMax) { rMin = Math.Min(rMin, a); rMax = Math.Max(a, rMax); } /// <summary> /// Sets up the internal data structure to construct chain of points /// </summary> /// <param name="rSpan">Shortest distance between two distinct points</param> private void SetLinks(double rSpan) { // NOP, if there is only one StylusPoint int count = Count; if (2 > count) return; // Set up the links to next and previous probe double rL = XY(0).X; double rT = XY(0).Y; double rR = rL; double rB = rT; for (int i = 0; i < count; ++i) { UpdateMinMax(XY(i).X, ref rL, ref rR); UpdateMinMax(XY(i).Y, ref rT, ref rB); } rR -= rL; rB -= rT; _dist = Math.Abs(rR) + Math.Abs(rB); if (false == DoubleUtil.IsZero(rSpan)) _span = rSpan; else if (0 < _dist) { /*** _nodes[count - 1] at this StylusPoint contains the length of the stroke. _dist is the half peripheri of the bounding box of the stroke. The idea here is that the Length/_dist is somewhat analogous to the "fractal dimension" of the stroke (or in other words, how much the stroke winds.) Length/count is the average distance between two consequitive points on the stroke. Thus, this average distance is multiplied by the winding factor. If the stroke were a PURE straight line across the diagone of a square, Lenght/Dist will be approximately 1.41. And if there were one pixel per co-ordinate, the span would have been 1.41, which works fairly well in cusp detection ***/ _span = 0.75f * (_nodes[count - 1] * _nodes[count - 1]) / (count * _dist); } if (_span < 1.0) _span = 1.0f; FindAllCusps(); } private List<CDataPoint> _points; private List<double> _nodes; private double _dist = 0; private List<int> _cusps = new List<int>(); // Parameters governing the cusp detection algorithm // Distance between probes for curvature checking private double _span = 3; // Default span struct CDataPoint { public Point Point; // Point (coordinates are double) public int Index; // Index into the original array public int TanPrev; // Previous StylusPoint Index for tangent computation public int TanNext; // Next StylusPoint Index for tangent computation }; } }
// // SourceManager.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2005-2007 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using Mono.Unix; using Mono.Addins; using Hyena; using Banshee.ServiceStack; using Banshee.Library; namespace Banshee.Sources { public delegate void SourceEventHandler(SourceEventArgs args); public delegate void SourceAddedHandler(SourceAddedArgs args); public class SourceEventArgs : EventArgs { public Source Source; } public class SourceAddedArgs : SourceEventArgs { public int Position; } public class SourceManager : /*ISourceManager,*/ IInitializeService, IRequiredService, IDBusExportable, IDisposable { private List<Source> sources = new List<Source>(); private Dictionary<string, Source> extension_sources = new Dictionary<string, Source> (); private Source active_source; private Source default_source; private MusicLibrarySource music_library; private VideoLibrarySource video_library; public event SourceEventHandler SourceUpdated; public event SourceAddedHandler SourceAdded; public event SourceEventHandler SourceRemoved; public event SourceEventHandler ActiveSourceChanged; public class GroupSource : Source { public GroupSource (string name, int order) : base (name, name, order) { TypeUniqueId = order.ToString (); } } public void Initialize () { // TODO should add library sources here, but requires changing quite a few // things that depend on being loaded before the music library is added. //AddSource (music_library = new MusicLibrarySource (), true); //AddSource (video_library = new VideoLibrarySource (), false); AddSource (new GroupSource (Catalog.GetString ("Libraries"), 39)); AddSource (new GroupSource (Catalog.GetString ("Online Media"), 60)); } internal void LoadExtensionSources () { lock (this) { AddinManager.AddExtensionNodeHandler ("/Banshee/SourceManager/Source", OnExtensionChanged); } } public void Dispose () { lock (this) { try { AddinManager.RemoveExtensionNodeHandler ("/Banshee/SourceManager/Source", OnExtensionChanged); } catch {} active_source = null; default_source = null; music_library = null; video_library = null; // Do dispose extension sources foreach (Source source in extension_sources.Values) { RemoveSource (source, true); } // But do not dispose non-extension sources while (sources.Count > 0) { RemoveSource (sources[0], false); } sources.Clear (); extension_sources.Clear (); } } private void OnExtensionChanged (object o, ExtensionNodeEventArgs args) { lock (this) { TypeExtensionNode node = (TypeExtensionNode)args.ExtensionNode; if (args.Change == ExtensionChange.Add && !extension_sources.ContainsKey (node.Id)) { try { Source source = (Source)node.CreateInstance (); extension_sources.Add (node.Id, source); if (source.Properties.Get<bool> ("AutoAddSource", true)) { AddSource (source); } Log.DebugFormat ("Extension source loaded: {0}", source.Name); } catch {} } else if (args.Change == ExtensionChange.Remove && extension_sources.ContainsKey (node.Id)) { Source source = extension_sources[node.Id]; extension_sources.Remove (node.Id); RemoveSource (source, true); Log.DebugFormat ("Extension source unloaded: {0}", source.Name); } } } public void AddSource(Source source) { AddSource(source, false); } public void AddSource(Source source, bool isDefault) { ThreadAssist.AssertInMainThread (); if(source == null || ContainsSource (source)) { return; } int position = FindSourceInsertPosition(source); sources.Insert(position, source); if(isDefault) { default_source = source; } source.Updated += OnSourceUpdated; source.ChildSourceAdded += OnChildSourceAdded; source.ChildSourceRemoved += OnChildSourceRemoved; if (source is MusicLibrarySource) { music_library = source as MusicLibrarySource; } else if (source is VideoLibrarySource) { video_library = source as VideoLibrarySource; } SourceAdded.SafeInvoke (new SourceAddedArgs () { Position = position, Source = source }); IDBusExportable exportable = source as IDBusExportable; if (exportable != null) { ServiceManager.DBusServiceManager.RegisterObject (exportable); } List<Source> children = new List<Source> (source.Children); foreach(Source child_source in children) { AddSource (child_source, false); } if(isDefault && ActiveSource == null) { SetActiveSource(source); } } public void RemoveSource (Source source) { RemoveSource (source, false); } public void RemoveSource (Source source, bool recursivelyDispose) { if(source == null || !ContainsSource (source)) { return; } if(source == default_source) { default_source = null; } source.Updated -= OnSourceUpdated; source.ChildSourceAdded -= OnChildSourceAdded; source.ChildSourceRemoved -= OnChildSourceRemoved; sources.Remove(source); foreach(Source child_source in source.Children) { RemoveSource (child_source, recursivelyDispose); } IDBusExportable exportable = source as IDBusExportable; if (exportable != null) { ServiceManager.DBusServiceManager.UnregisterObject (exportable); } if (recursivelyDispose) { IDisposable disposable = source as IDisposable; if (disposable != null) { disposable.Dispose (); } } ThreadAssist.ProxyToMain (delegate { if(source == active_source) { if (source.Parent != null && source.Parent.CanActivate) { SetActiveSource(source.Parent); } else { SetActiveSource(default_source); } } SourceEventHandler handler = SourceRemoved; if(handler != null) { SourceEventArgs args = new SourceEventArgs(); args.Source = source; handler(args); } }); } public void RemoveSource(Type type) { Queue<Source> remove_queue = new Queue<Source>(); foreach(Source source in Sources) { if(source.GetType() == type) { remove_queue.Enqueue(source); } } while(remove_queue.Count > 0) { RemoveSource(remove_queue.Dequeue()); } } public bool ContainsSource(Source source) { return sources.Contains(source); } private void OnSourceUpdated(object o, EventArgs args) { ThreadAssist.ProxyToMain (delegate { SourceEventHandler handler = SourceUpdated; if(handler != null) { SourceEventArgs evargs = new SourceEventArgs(); evargs.Source = o as Source; handler(evargs); } }); } private void OnChildSourceAdded(SourceEventArgs args) { AddSource (args.Source); } private void OnChildSourceRemoved(SourceEventArgs args) { RemoveSource (args.Source); } private int FindSourceInsertPosition(Source source) { for(int i = sources.Count - 1; i >= 0; i--) { if((sources[i] as Source).Order == source.Order) { return i; } } for(int i = 0; i < sources.Count; i++) { if((sources[i] as Source).Order >= source.Order) { return i; } } return sources.Count; } public Source DefaultSource { get { return default_source; } set { default_source = value; } } public MusicLibrarySource MusicLibrary { get { return music_library; } } public VideoLibrarySource VideoLibrary { get { return video_library; } } public Source ActiveSource { get { return active_source; } } /*ISource ISourceManager.DefaultSource { get { return DefaultSource; } } ISource ISourceManager.ActiveSource { get { return ActiveSource; } set { value.Activate (); } }*/ public void SetActiveSource(Source source) { SetActiveSource(source, true); } public void SetActiveSource(Source source, bool notify) { ThreadAssist.AssertInMainThread (); if(source == null || !source.CanActivate || active_source == source) { return; } if(active_source != null) { active_source.Deactivate(); } active_source = source; if (source.Parent != null) { source.Parent.Expanded = true; } if(!notify) { source.Activate(); return; } SourceEventHandler handler = ActiveSourceChanged; if(handler != null) { SourceEventArgs args = new SourceEventArgs(); args.Source = active_source; handler(args); } source.Activate(); } public IEnumerable<T> FindSources<T> () where T : Source { foreach (Source source in Sources) { T t_source = source as T; if (t_source != null) { yield return t_source; } } } public ICollection<Source> Sources { get { return sources; } } /*string [] ISourceManager.Sources { get { return DBusServiceManager.MakeObjectPathArray<Source>(sources); } }*/ IDBusExportable IDBusExportable.Parent { get { return null; } } string Banshee.ServiceStack.IService.ServiceName { get { return "SourceManager"; } } } }