context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System.Collections; using System.Collections.Generic; using System; using System.Text.RegularExpressions; namespace Squid.Xml { public enum XmlNodeType { Element, Text, EndElement } public class XmlAttribute { public string Name; public string Value; } public class XmlReader { private string xmlString = ""; private int idx = 0; private XmlNodeType _nodeType; public XmlNodeType NodeType { get { return _nodeType; } } public bool HasAttributes { get; private set; } private List<XmlAttribute> Attributes = new List<XmlAttribute>(); private int AttributeIndex = -1; private bool _isEmptyElement; public XmlReader(string xml) { xmlString = xml; _nodeType = XmlNodeType.Text; } public void New(string xml) { xmlString = xml; _nodeType = XmlNodeType.Text; idx = 0; Name = ""; Value = ""; _isEmptyElement = false; AttributeIndex = -1; Attributes.Clear(); HasAttributes = false; } public string Name = ""; public string Value = ""; // properly looks for the next index of _c, without stopping at line endings, allowing tags to be break lines int IndexOf(char _c, int _i) { int i = _i; while (i < xmlString.Length) { if (xmlString[i] == _c) return i; ++i; } return -1; } public bool EOF { get { return idx < 0; } } public bool IsEmptyElement { get { return _isEmptyElement; } } public string GetAttribute(string name) { foreach (XmlAttribute att in Attributes) { if (att.Name.Equals(name)) return att.Value; } return string.Empty; } public bool MoveToNextAttribute() { AttributeIndex++; if (AttributeIndex < Attributes.Count) { Name = Attributes[AttributeIndex].Name; Value = Attributes[AttributeIndex].Value; } return AttributeIndex < Attributes.Count; } public bool Read() { int newindex = idx; if (idx > -1) newindex = xmlString.IndexOf("<", idx); Name = string.Empty; Value = string.Empty; HasAttributes = false; Attributes.Clear(); AttributeIndex = -1; _isEmptyElement = false; if (newindex != idx) { if (newindex == -1) { if (idx > 0) idx++; Value = xmlString.Substring(idx, xmlString.Length - idx); _nodeType = XmlNodeType.Text; idx = newindex; return true; } else { if (idx > 0) idx++; Value = xmlString.Substring(idx, newindex - idx); _nodeType = XmlNodeType.Text; idx = newindex; return true; } } if (idx == -1) return false; ++idx; // skip attributes, don't include them in the name! int endOfTag = IndexOf('>', idx); int endOfName = IndexOf(' ', idx); if ((endOfName == -1) || (endOfTag < endOfName)) { endOfName = endOfTag; } if (endOfTag == -1) { return false; } Name = xmlString.Substring(idx, endOfName - idx); idx = endOfTag; // check if a closing tag if (Name.StartsWith("/")) { _isEmptyElement = false; _nodeType = XmlNodeType.EndElement; Name = Name.Remove(0, 1); // remove the slash } else if(Name.EndsWith("/")) { _isEmptyElement = true; _nodeType = XmlNodeType.Element; Name = Name.Replace("/", ""); // remove the slash } else { string temp = xmlString.Substring(endOfName, endOfTag - endOfName); Regex r = new Regex("([a-z0-9]+)=(\"(.*?)\")"); foreach (Match m in r.Matches(temp)) { string name = m.Value.Substring(0, m.Value.IndexOf("=")); int i0 = m.Value.IndexOf("\"") + 1; int i1 = m.Value.LastIndexOf("\""); string val = m.Value.Substring(i0, i1 - i0); Attributes.Add(new XmlAttribute { Name = name, Value = val }); } r = new Regex("([a-z0-9]+)=('(.*?)')"); foreach (Match m in r.Matches(temp)) { string name = m.Value.Substring(0, m.Value.IndexOf("=")); int i0 = m.Value.IndexOf("'") + 1; int i1 = m.Value.LastIndexOf("'"); string val = m.Value.Substring(i0, i1 - i0); Attributes.Add(new XmlAttribute { Name = name, Value = val }); } HasAttributes = Attributes.Count > 0; _nodeType = XmlNodeType.Element; } return idx < xmlString.Length; } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading; using System.Timers; using Aurora.Framework; using Nini.Config; using OpenMetaverse; using OpenSim.Region.Framework.Interfaces; using OpenSim.Services.Interfaces; using Timer = System.Timers.Timer; namespace Aurora.Modules.Appearance { public class AvatarFactoryModule : IAvatarFactory, INonSharedRegionModule { #region Declares private readonly TimedSaving<AvatarAppearance> _saveQueue = new TimedSaving<AvatarAppearance>(); private readonly TimedSaving<AvatarAppearance> _sendQueue = new TimedSaving<AvatarAppearance>(); private readonly TimedSaving<AvatarAppearance> _initialSendQueue = new TimedSaving<AvatarAppearance>(); private readonly object m_setAppearanceLock = new object(); private int m_initialsendtime = 3; // seconds to wait before sending the initial appearance private int m_savetime = 5; // seconds to wait before saving changed appearance private int m_sendtime = 2; // seconds to wait before sending appearances private IScene m_scene; #endregion #region Default UnderClothes private static UUID m_underShirtUUID = UUID.Zero; private static UUID m_underPantsUUID = UUID.Zero; private const string m_defaultUnderPants = @"LLWearable version 22 New Underpants permissions 0 { base_mask 7fffffff owner_mask 7fffffff group_mask 00000000 everyone_mask 00000000 next_owner_mask 00082000 creator_id 05948863-b678-433e-87a4-e44d17678d1d owner_id 05948863-b678-433e-87a4-e44d17678d1d last_owner_id 00000000-0000-0000-0000-000000000000 group_id 00000000-0000-0000-0000-000000000000 } sale_info 0 { sale_type not sale_price 10 } type 11 parameters 5 619 .3 624 .8 824 1 825 1 826 1 textures 1 17 5748decc-f629-461c-9a36-a35a221fe21f"; private const string m_defaultUnderShirt = @"LLWearable version 22 New Undershirt permissions 0 { base_mask 7fffffff owner_mask 7fffffff group_mask 00000000 everyone_mask 00000000 next_owner_mask 00082000 creator_id 05948863-b678-433e-87a4-e44d17678d1d owner_id 05948863-b678-433e-87a4-e44d17678d1d last_owner_id 00000000-0000-0000-0000-000000000000 group_id 00000000-0000-0000-0000-000000000000 } sale_info 0 { sale_type not sale_price 10 } type 10 parameters 7 603 .4 604 .85 605 .84 779 .84 821 1 822 1 823 1 textures 1 16 5748decc-f629-461c-9a36-a35a221fe21f"; #endregion #region INonSharedRegionModule Members public void Initialise(IConfigSource config) { if (config != null) { IConfig sconfig = config.Configs["Startup"]; if (sconfig != null) { m_savetime = sconfig.GetInt("DelayBeforeAppearanceSave", m_savetime); m_sendtime = sconfig.GetInt("DelayBeforeAppearanceSend", m_sendtime); m_initialsendtime = sconfig.GetInt("DelayBeforeInitialAppearanceSend", m_initialsendtime); // MainConsole.Instance.InfoFormat("[AVFACTORY] configured for {0} save and {1} send",m_savetime,m_sendtime); } } } public void AddRegion(IScene scene) { if (m_scene == null) m_scene = scene; scene.RegisterModuleInterface<IAvatarFactory>(this); scene.EventManager.OnNewClient += NewClient; scene.EventManager.OnClosingClient += RemoveClient; scene.EventManager.OnNewPresence += EventManager_OnNewPresence; scene.EventManager.OnRemovePresence += EventManager_OnRemovePresence; if (MainConsole.Instance != null) MainConsole.Instance.Commands.AddCommand("force send appearance", "force send appearance", "Force send the avatar's appearance", HandleConsoleForceSendAppearance); _saveQueue.Start(m_savetime, HandleAppearanceSave); _sendQueue.Start(m_sendtime, HandleAppearanceSend); _initialSendQueue.Start(m_initialsendtime, HandleInitialAppearanceSend); } public void RemoveRegion(IScene scene) { scene.UnregisterModuleInterface<IAvatarFactory>(this); scene.EventManager.OnNewClient -= NewClient; scene.EventManager.OnClosingClient -= RemoveClient; scene.EventManager.OnNewPresence -= EventManager_OnNewPresence; scene.EventManager.OnRemovePresence -= EventManager_OnRemovePresence; } public void RegionLoaded(IScene scene) { } public Type ReplaceableInterface { get { return null; } } public void Close() { } public string Name { get { return "Default Avatar Factory"; } } #endregion public void NewClient(IClientAPI client) { client.OnRequestWearables += RequestWearables; client.OnSetAppearance += SetAppearance; client.OnAvatarNowWearing += AvatarIsWearing; client.OnAgentCachedTextureRequest += AgentCachedTexturesRequest; } public void RemoveClient(IClientAPI client) { client.OnRequestWearables -= RequestWearables; client.OnSetAppearance -= SetAppearance; client.OnAvatarNowWearing -= AvatarIsWearing; client.OnAgentCachedTextureRequest -= AgentCachedTexturesRequest; } private void EventManager_OnNewPresence(IScenePresence presence) { AvatarApperanceModule m = new AvatarApperanceModule(presence); presence.RegisterModuleInterface<IAvatarAppearanceModule>(m); } private void EventManager_OnRemovePresence(IScenePresence presence) { AvatarApperanceModule m = (AvatarApperanceModule) presence.RequestModuleInterface<IAvatarAppearanceModule>(); if (m != null) { m.Close(); presence.UnregisterModuleInterface<IAvatarAppearanceModule>(m); } } #region Validate Baked Textures /// <summary> /// Check for the existence of the baked texture assets. /// </summary> /// <param name = "client"></param> public bool ValidateBakedTextureCache(IClientAPI client) { return ValidateBakedTextureCache(client, true); } /// <summary> /// Check for the existence of the baked texture assets. Request a rebake /// unless checkonly is true. /// </summary> /// <param name = "client"></param> /// <param name = "checkonly"></param> private bool ValidateBakedTextureCache(IClientAPI client, bool checkonly) { IScenePresence sp = m_scene.GetScenePresence(client.AgentId); IAvatarAppearanceModule appearance = sp.RequestModuleInterface<IAvatarAppearanceModule>(); bool defonly = true; // are we only using default textures // Process the texture entry foreach (int idx in AvatarAppearance.BAKE_INDICES) { Primitive.TextureEntryFace face = appearance.Appearance.Texture.FaceTextures[idx]; // if there is no texture entry, skip it if (face == null) continue; // if the texture is one of the "defaults" then skip it // this should probably be more intelligent (skirt texture doesnt matter // if the avatar isnt wearing a skirt) but if any of the main baked // textures is default then the rest should be as well if (face.TextureID == UUID.Zero || face.TextureID == AppearanceManager.DEFAULT_AVATAR_TEXTURE) continue; defonly = false; // found a non-default texture reference if (!CheckBakedTextureAsset(client, face.TextureID, idx)) { // the asset didn't exist if we are only checking, then we found a bad // one and we're done otherwise, ask for a rebake if (checkonly) return false; MainConsole.Instance.InfoFormat("[AvatarFactory] missing baked texture {0}, request rebake", face.TextureID); client.SendRebakeAvatarTextures(face.TextureID); } } // If we only found default textures, then the appearance is not cached return (!defonly); } #endregion #region Set Appearance /// <summary> /// Set appearance data (textureentry and slider settings) received from the client /// </summary> /// <param name = "textureEntry"></param> /// <param name = "visualParams"></param> /// <param name="client"></param> /// <param name="wearables"></param> public void SetAppearance(IClientAPI client, Primitive.TextureEntry textureEntry, byte[] visualParams, WearableCache[] wearables, uint serial) { IScenePresence sp = m_scene.GetScenePresence(client.AgentId); IAvatarAppearanceModule appearance = sp.RequestModuleInterface<IAvatarAppearanceModule>(); appearance.Appearance.Serial = (int)serial; //MainConsole.Instance.InfoFormat("[AVFACTORY]: start SetAppearance for {0}", client.AgentId); // Process the texture entry transactionally, this doesn't guarantee that Appearance is // going to be handled correctly but it does serialize the updates to the appearance lock (m_setAppearanceLock) { bool texturesChanged = false; bool visualParamsChanged = false; if (textureEntry != null) { List<UUID> ChangedTextures = new List<UUID>(); texturesChanged = appearance.Appearance.SetTextureEntries(textureEntry, out ChangedTextures); // MainConsole.Instance.WarnFormat("[AVFACTORY]: Prepare to check textures for {0}",client.AgentId); //Do this async as it accesses the asset service (could be remote) multiple times Util.FireAndForget(delegate { //Validate all the textures now that we've updated ValidateBakedTextureCache(client, false); //The client wants us to cache the baked textures CacheWearableData(sp, textureEntry, wearables); }); // MainConsole.Instance.WarnFormat("[AVFACTORY]: Complete texture check for {0}",client.AgentId); } // Process the visual params, this may change height as well if (visualParams != null) { //Now update the visual params and see if they have changed visualParamsChanged = appearance.Appearance.SetVisualParams(visualParams); //Fix the height only if the parameters have changed if (visualParamsChanged && appearance.Appearance.AvatarHeight > 0) sp.SetHeight(appearance.Appearance.AvatarHeight); } // If something changed in the appearance then queue an appearance save if (texturesChanged || visualParamsChanged) QueueAppearanceSave(client.AgentId); } // And always queue up an appearance update to send out QueueAppearanceSend(client.AgentId); // MainConsole.Instance.WarnFormat("[AVFACTORY]: complete SetAppearance for {0}:\n{1}",client.AgentId,sp.Appearance.ToString()); } /// <summary> /// Tell the Avatar Service about these baked textures and items /// </summary> /// <param name = "sp"></param> /// <param name = "textureEntry"></param> /// <param name = "wearables"></param> private void CacheWearableData(IScenePresence sp, Primitive.TextureEntry textureEntry, WearableCache[] wearables) { /*if (textureEntry == null || wearables.Length == 0) return; AvatarWearable cachedWearable = new AvatarWearable {MaxItems = 0}; //Unlimited items #if (!ISWIN) foreach (WearableCache item in wearables) { if (textureEntry.FaceTextures[item.TextureIndex] != null) { cachedWearable.Add(item.CacheID, textureEntry.FaceTextures[item.TextureIndex].TextureID); } } #else foreach (WearableCache item in wearables.Where(item => textureEntry.FaceTextures[item.TextureIndex] != null)) { cachedWearable.Add(item.CacheID, textureEntry.FaceTextures[item.TextureIndex].TextureID); } #endif m_scene.AvatarService.CacheWearableData(sp.UUID, cachedWearable);*/ } /// <summary> /// The client wants to know whether we already have baked textures for the given items /// </summary> /// <param name = "client"></param> /// <param name = "args"></param> public void AgentCachedTexturesRequest(IClientAPI client, List<CachedAgentArgs> args) { List<CachedAgentArgs> resp = (from arg in args let cachedID = UUID.Zero select new CachedAgentArgs {ID = cachedID, TextureIndex = arg.TextureIndex}).ToList(); //AvatarData ad = m_scene.AvatarService.GetAvatar(client.AgentId); //Send all with UUID zero for now so that we don't confuse the client about baked textures... client.SendAgentCachedTexture(resp); } /// <summary> /// Checks for the existance of a baked texture asset and /// requests the viewer rebake if the asset is not found /// </summary> /// <param name = "client"></param> /// <param name = "textureID"></param> /// <param name = "idx"></param> private bool CheckBakedTextureAsset(IClientAPI client, UUID textureID, int idx) { if (m_scene.AssetService.Get(textureID.ToString()) == null) { MainConsole.Instance.WarnFormat("[AvatarFactory]: Missing baked texture {0} ({1}) for avatar {2}", textureID, idx, client.Name); return false; } return true; } #endregion #region UpdateAppearanceTimer /// <summary> /// Queue up a request to send appearance, makes it possible to /// accumulate changes without sending out each one separately. /// </summary> public void QueueAppearanceSend(UUID agentid) { // MainConsole.Instance.WarnFormat("[AVFACTORY]: Queue appearance send for {0}", agentid); // 10000 ticks per millisecond, 1000 milliseconds per second _sendQueue.Add(agentid); } public void QueueAppearanceSave(UUID agentid) { // MainConsole.Instance.WarnFormat("[AVFACTORY]: Queue appearance save for {0}", agentid); // 10000 ticks per millisecond, 1000 milliseconds per second IScenePresence sp = m_scene.GetScenePresence(agentid); if (sp == null) { MainConsole.Instance.WarnFormat("[AvatarFactory]: Agent {0} no longer in the scene", agentid); return; } IAvatarAppearanceModule appearance = sp.RequestModuleInterface<IAvatarAppearanceModule>(); _saveQueue.Add(agentid, appearance.Appearance); } public void QueueInitialAppearanceSend(UUID agentid) { // MainConsole.Instance.WarnFormat("[AVFACTORY]: Queue initial appearance send for {0}", agentid); // 10000 ticks per millisecond, 1000 milliseconds per second _initialSendQueue.Add(agentid); } /// <summary> /// Sends an avatars appearance (only called by the TimeSender) /// </summary> /// <param name="agentid"></param> /// <param name="app">ALWAYS NULL</param> private void HandleAppearanceSend(UUID agentid, AvatarAppearance app) { IScenePresence sp = m_scene.GetScenePresence(agentid); if (sp == null) { MainConsole.Instance.WarnFormat("[AvatarFactory]: Agent {0} no longer in the scene to send appearance for.", agentid); return; } IAvatarAppearanceModule appearance = sp.RequestModuleInterface<IAvatarAppearanceModule>(); // MainConsole.Instance.WarnFormat("[AvatarFactory]: Handle appearance send for {0}", agentid); // Send the appearance to everyone in the scene appearance.SendAppearanceToAllOtherAgents(); // Send animations back to the avatar as well sp.Animator.SendAnimPack(); } /// <summary> /// Saves a user's appearance /// </summary> /// <param name="agentid"></param> /// <param name="app"></param> private void HandleAppearanceSave(UUID agentid, AvatarAppearance app) { //If the avatar changes appearance, then proptly logs out, this will break! //ScenePresence sp = m_scene.GetScenePresence(agentid); //if (sp == null) //{ // MainConsole.Instance.WarnFormat("[AvatarFactory]: Agent {0} no longer in the scene", agentid); // return; //} // MainConsole.Instance.WarnFormat("[AvatarFactory] avatar {0} save appearance",agentid); IScenePresence sp = m_scene.GetScenePresence(agentid); if (sp == null) return; AvatarAppearance appearance = sp != null ? sp.RequestModuleInterface<IAvatarAppearanceModule>().Appearance : app; m_scene.AvatarService.SetAppearance(agentid, appearance); } /// <summary> /// Do everything required once a client completes its movement into a region and becomes /// a root agent. /// </summary> /// <param name="agentid">Agent to send appearance for</param> /// <param name="app">ALWAYS NULL</param> private void HandleInitialAppearanceSend(UUID agentid, AvatarAppearance app) { IScenePresence sp = m_scene.GetScenePresence(agentid); if (sp == null) { MainConsole.Instance.WarnFormat("[AvatarFactory]: Agent {0} no longer in the scene to send appearance for.", agentid); return; } IAvatarAppearanceModule appearance = sp.RequestModuleInterface<IAvatarAppearanceModule>(); //MainConsole.Instance.InfoFormat("[AvatarFactory]: Handle initial appearance send for {0}", agentid); //Only set this if we actually have sent the wearables appearance.InitialHasWearablesBeenSent = true; // This agent just became root. We are going to tell everyone about it. appearance.SendAvatarDataToAllAgents(true); if (ValidateBakedTextureCache(sp.ControllingClient)) appearance.SendAppearanceToAgent(sp); else MainConsole.Instance.ErrorFormat("[AvatarFactory]: baked textures are NOT in the cache for {0}", sp.Name); sp.ControllingClient.SendWearables(appearance.Appearance.Wearables, appearance.Appearance.Serial); // If the avatars baked textures are all in the cache, then we have a // complete appearance... send it out, if not, then we'll send it when // the avatar finishes updating its appearance appearance.SendAppearanceToAllOtherAgents(); // This agent just became root. We are going to tell everyone about it. The process of // getting other avatars information was initiated in the constructor... don't do it // again here... appearance.SendAvatarDataToAllAgents(true); //Tell us about everyone else as well now that we are here appearance.SendOtherAgentsAppearanceToMe(); } #endregion #region Wearables //private Dictionary<UUID, UUID> incomingLinks = new Dictionary<UUID, UUID>(); public void NewAppearanceLink(InventoryItemBase item) { /*if (item.InvType == (int)InventoryType.Wearable) { incomingLinks[item.AssetID] = item.ID; }*/ } /// <summary> /// Tell the client for this scene presence what items it should be wearing now /// </summary> public void RequestWearables(IClientAPI client) { IScenePresence sp = m_scene.GetScenePresence(client.AgentId); if (sp == null) { MainConsole.Instance.WarnFormat("[AvatarFactory]: SendWearables unable to find presence for {0}", client.AgentId); return; } //Don't send the wearables immediately, make sure that everything is loaded first QueueInitialAppearanceSend(client.AgentId); //client.SendWearables(sp.Appearance.Wearables, sp.Appearance.Serial); } /// <summary> /// Update what the avatar is wearing using an item from their inventory. /// </summary> /// <param name = "client"></param> /// <param name = "e"></param> public void AvatarIsWearing(IClientAPI client, AvatarWearingArgs e) { IScenePresence sp = m_scene.GetScenePresence(client.AgentId); if (sp == null) { MainConsole.Instance.WarnFormat("[AvatarFactory]: AvatarIsWearing unable to find presence for {0}", client.AgentId); return; } MainConsole.Instance.DebugFormat("[AvatarFactory]: AvatarIsWearing called for {0}", client.AgentId); // operate on a copy of the appearance so we don't have to lock anything IAvatarAppearanceModule appearance = sp.RequestModuleInterface<IAvatarAppearanceModule>(); AvatarAppearance avatAppearance = new AvatarAppearance(appearance.Appearance, false); IOpenRegionSettingsModule module = m_scene.RequestModuleInterface<IOpenRegionSettingsModule>(); bool NeedsRebake = false; if (module != null && module.EnableTeenMode) { foreach (AvatarWearingArgs.Wearable wear in e.NowWearing) { if (wear.Type == 10 & wear.ItemID == UUID.Zero && module.DefaultUnderpants != UUID.Zero) { NeedsRebake = true; wear.ItemID = module.DefaultUnderpants; InventoryItemBase item = new InventoryItemBase(UUID.Random()) { InvType = (int) InventoryType.Wearable, AssetType = (int) AssetType.Clothing, Name = "Default Underpants", Folder = m_scene.InventoryService.GetFolderForType(client.AgentId, InventoryType. Wearable, AssetType. Clothing).ID, Owner = client.AgentId, CurrentPermissions = 0, CreatorId = UUID.Zero.ToString(), AssetID = module.DefaultUnderpants }; //Locked client.SendInventoryItemCreateUpdate(item, 0); } else if (wear.Type == 10 & wear.ItemID == UUID.Zero) { NeedsRebake = true; InventoryItemBase item = new InventoryItemBase(UUID.Random()) { InvType = (int) InventoryType.Wearable, AssetType = (int) AssetType.Clothing, Name = "Default Underpants", Folder = m_scene.InventoryService.GetFolderForType(client.AgentId, InventoryType. Wearable, AssetType. Clothing).ID, Owner = client.AgentId, CurrentPermissions = 0 }; //Locked if (m_underPantsUUID == UUID.Zero) { m_underPantsUUID = UUID.Random(); AssetBase asset = new AssetBase(m_underPantsUUID, "Default Underpants", AssetType.Clothing, UUID.Zero) {Data = Utils.StringToBytes(m_defaultUnderPants)}; asset.FillHash(); asset.ID = m_scene.AssetService.Store(asset); m_underPantsUUID = asset.ID; } item.CreatorId = UUID.Zero.ToString(); item.AssetID = m_underPantsUUID; m_scene.InventoryService.AddItemAsync(item, null); client.SendInventoryItemCreateUpdate(item, 0); wear.ItemID = item.ID; } if (wear.Type == 11 && wear.ItemID == UUID.Zero && module.DefaultUndershirt != UUID.Zero) { NeedsRebake = true; wear.ItemID = module.DefaultUndershirt; InventoryItemBase item = new InventoryItemBase(UUID.Random()) { InvType = (int) InventoryType.Wearable, AssetType = (int) AssetType.Clothing, Name = "Default Undershirt", Folder = m_scene.InventoryService.GetFolderForType(client.AgentId, InventoryType. Wearable, AssetType. Clothing).ID, Owner = client.AgentId, CurrentPermissions = 0, CreatorId = UUID.Zero.ToString(), AssetID = module.DefaultUndershirt }; //Locked client.SendInventoryItemCreateUpdate(item, 0); } else if (wear.Type == 11 & wear.ItemID == UUID.Zero) { NeedsRebake = true; InventoryItemBase item = new InventoryItemBase(UUID.Random()) { InvType = (int) InventoryType.Wearable, AssetType = (int) AssetType.Clothing, Name = "Default Undershirt", Folder = m_scene.InventoryService.GetFolderForType(client.AgentId, InventoryType. Wearable, AssetType. Clothing).ID, Owner = client.AgentId, CurrentPermissions = 0 }; //Locked if (m_underShirtUUID == UUID.Zero) { m_underShirtUUID = UUID.Random(); AssetBase asset = new AssetBase(m_underShirtUUID, "Default Undershirt", AssetType.Clothing, UUID.Zero) {Data = Utils.StringToBytes(m_defaultUnderShirt)}; asset.FillHash(); asset.ID = m_scene.AssetService.Store(asset); m_underShirtUUID = asset.ID; } item.CreatorId = UUID.Zero.ToString(); item.AssetID = m_underShirtUUID; m_scene.InventoryService.AddItemAsync(item, null); client.SendInventoryItemCreateUpdate(item, 0); wear.ItemID = item.ID; } } } foreach (AvatarWearingArgs.Wearable wear in e.NowWearing.Where(wear => wear.Type < AvatarWearable.MAX_WEARABLES)) { /*if (incomingLinks.ContainsKey (wear.ItemID)) { wear.ItemID = incomingLinks[wear.ItemID]; }*/ avatAppearance.Wearables[wear.Type].Add(wear.ItemID, UUID.Zero); } avatAppearance.GetAssetsFrom(appearance.Appearance); // This could take awhile since it needs to pull inventory SetAppearanceAssets(sp.UUID, e.NowWearing, appearance.Appearance, ref avatAppearance); // could get fancier with the locks here, but in the spirit of "last write wins" // this should work correctly, also, we don't need to send the appearance here // since the "iswearing" will trigger a new set of visual param and baked texture changes // when those complete, the new appearance will be sent appearance.Appearance = avatAppearance; if (NeedsRebake) { //Tell the client about the new things it is wearing sp.ControllingClient.SendWearables(appearance.Appearance.Wearables, appearance.Appearance.Serial); //Then forcefully tell it to rebake #if (!ISWIN) foreach (Primitive.TextureEntryFace t in appearance.Appearance.Texture.FaceTextures) { Primitive.TextureEntryFace face = (t); if (face != null) { sp.ControllingClient.SendRebakeAvatarTextures(face.TextureID); } } #else foreach (Primitive.TextureEntryFace face in appearance.Appearance.Texture.FaceTextures.Select(t => (t)).Where(face => face != null)) { sp.ControllingClient.SendRebakeAvatarTextures(face.TextureID); } #endif } QueueAppearanceSave(sp.UUID); //Send the wearables HERE so that the client knows what it is wearing //sp.ControllingClient.SendWearables(sp.Appearance.Wearables, sp.Appearance.Serial); //Do not save or send the appearance! The client loops back and sends a bunch of SetAppearance // (handled above) and that takes care of it } private void SetAppearanceAssets(UUID userID, List<AvatarWearingArgs.Wearable> nowWearing, AvatarAppearance oldAppearance, ref AvatarAppearance appearance) { IInventoryService invService = m_scene.InventoryService; for (int i = 0; i < AvatarWearable.MAX_WEARABLES; i++) { for (int j = 0; j < appearance.Wearables[j].Count; j++) { if (appearance.Wearables[i][j].ItemID == UUID.Zero) continue; // Ignore ruth's assets if (appearance.Wearables[i][j].ItemID == AvatarWearable.DefaultWearables[i][j].ItemID) { //MainConsole.Instance.ErrorFormat( // "[AvatarFactory]: Found an asset for the default avatar, itemID {0}, wearable {1}, asset {2}" + // ", setting to default asset {3}.", // appearance.Wearables[i][j].ItemID, (WearableType)i, appearance.Wearables[i][j].AssetID, // AvatarWearable.DefaultWearables[i][j].AssetID); appearance.Wearables[i].Add(appearance.Wearables[i][j].ItemID, appearance.Wearables[i][j].AssetID); continue; } if (nowWearing[i].ItemID == oldAppearance.Wearables[i][j].ItemID) continue;//Don't relookup items that are the same and have already been found earlier InventoryItemBase baseItem = new InventoryItemBase(appearance.Wearables[i][j].ItemID, userID); baseItem = invService.GetItem(baseItem); if (baseItem != null) { if (baseItem.AssetType == (int) AssetType.Link) { baseItem = new InventoryItemBase(baseItem.AssetID, userID); baseItem = invService.GetItem(baseItem); } appearance.Wearables[i].Add(baseItem.ID, baseItem.AssetID); } else { MainConsole.Instance.ErrorFormat( "[AvatarFactory]: Can't find inventory item {0} for {1}, setting to default", appearance.Wearables[i][j].ItemID, (WearableType) i); appearance.Wearables[i].RemoveItem(appearance.Wearables[i][j].ItemID); appearance.Wearables[i].Add(AvatarWearable.DefaultWearables[i][j].ItemID, AvatarWearable.DefaultWearables[i][j].AssetID); } } } } #endregion #region Console Commands public void ForceSendAvatarAppearance(UUID agentid) { //If the avatar changes appearance, then proptly logs out, this will break! IScenePresence sp = m_scene.GetScenePresence(agentid); if (sp == null || sp.IsChildAgent) { MainConsole.Instance.WarnFormat("[AvatarFactory]: Agent {0} no longer in the scene", agentid); return; } //Force send! IAvatarAppearanceModule appearance = sp.RequestModuleInterface<IAvatarAppearanceModule>(); sp.ControllingClient.SendWearables(appearance.Appearance.Wearables, appearance.Appearance.Serial); Thread.Sleep(100); appearance.SendAvatarDataToAllAgents(true); Thread.Sleep(100); appearance.SendAppearanceToAgent(sp); Thread.Sleep(100); appearance.SendAppearanceToAllOtherAgents(); MainConsole.Instance.Info("Resent appearance"); } private void HandleConsoleForceSendAppearance(string[] cmds) { //Make sure its set to the right region if (MainConsole.Instance.ConsoleScene != m_scene && MainConsole.Instance.ConsoleScene != null) return; if (cmds.Length != 5) { if(MainConsole.Instance.ConsoleScene != null) MainConsole.Instance.Info("Wrong number of commands."); return; } string firstName = cmds[3], lastName = cmds[4]; IScenePresence SP; if (m_scene.TryGetAvatarByName(firstName + " " + lastName, out SP)) { ForceSendAvatarAppearance(SP.UUID); } else MainConsole.Instance.Info("Could not find user's account."); } #endregion #region Nested type: AvatarApperanceModule public class AvatarApperanceModule : IAvatarAppearanceModule { private bool m_InitialHasWearablesBeenSent; protected AvatarAppearance m_appearance; public IScenePresence m_sp; public AvatarApperanceModule(IScenePresence sp) { m_sp = sp; m_sp.Scene.EventManager.OnMakeRootAgent += EventManager_OnMakeRootAgent; } #region IAvatarAppearanceModule Members public bool InitialHasWearablesBeenSent { get { return m_InitialHasWearablesBeenSent; } set { m_InitialHasWearablesBeenSent = value; } } /// <summary> /// Send this agent's avatar data to all other root and child agents in the scene /// This agent must be root. This avatar will receive its own update. /// </summary> public void SendAvatarDataToAllAgents(bool sendAppearance) { // only send update from root agents to other clients; children are only "listening posts" if (m_sp.IsChildAgent) { MainConsole.Instance.Warn("[SCENEPRESENCE] attempt to send avatar data from a child agent"); return; } int count = 0; m_sp.Scene.ForEachScenePresence(delegate(IScenePresence scenePresence) { SendAvatarDataToAgent(scenePresence, sendAppearance); count++; }); IAgentUpdateMonitor reporter = (IAgentUpdateMonitor) m_sp.Scene.RequestModuleInterface<IMonitorModule>().GetMonitor( m_sp.Scene.RegionInfo.RegionID.ToString(), MonitorModuleHelper.AgentUpdateCount); if (reporter != null) { reporter.AddAgentUpdates(count); } } /// <summary> /// Send avatar data to an agent. /// </summary> /// <param name = "avatar"></param> /// <param name="sendAppearance"></param> public void SendAvatarDataToAgent(IScenePresence avatar, bool sendAppearance) { //MainConsole.Instance.WarnFormat("[SP] Send avatar data from {0} to {1}",m_uuid,avatar.ControllingClient.AgentId); if (!sendAppearance) avatar.SceneViewer.SendPresenceFullUpdate(m_sp); else avatar.SceneViewer.QueuePresenceForFullUpdate(m_sp, false); } /// <summary> /// Send this agent's appearance to all other root and child agents in the scene /// This agent must be root. /// </summary> public void SendAppearanceToAllOtherAgents() { // only send update from root agents to other clients; children are only "listening posts" if (m_sp.IsChildAgent) { MainConsole.Instance.Warn("[SCENEPRESENCE] attempt to send avatar data from a child agent"); return; } int count = 0; m_sp.Scene.ForEachScenePresence(delegate(IScenePresence scenePresence) { if (scenePresence.UUID == m_sp.UUID) return; SendAppearanceToAgent(scenePresence); count++; }); IAgentUpdateMonitor reporter = (IAgentUpdateMonitor) m_sp.Scene.RequestModuleInterface<IMonitorModule>().GetMonitor( m_sp.Scene.RegionInfo.RegionID.ToString(), MonitorModuleHelper.AgentUpdateCount); if (reporter != null) { reporter.AddAgentUpdates(count); } } /// <summary> /// Send appearance from all other root agents to this agent. this agent /// can be either root or child /// </summary> public void SendOtherAgentsAppearanceToMe() { int count = 0; m_sp.Scene.ForEachScenePresence(delegate(IScenePresence scenePresence) { // only send information about root agents if (scenePresence.IsChildAgent) return; // only send information about other root agents if (scenePresence.UUID == m_sp.UUID) return; IAvatarAppearanceModule appearance = scenePresence.RequestModuleInterface <IAvatarAppearanceModule>(); if (appearance != null) appearance.SendAppearanceToAgent(m_sp); count++; }); IAgentUpdateMonitor reporter = (IAgentUpdateMonitor) m_sp.Scene.RequestModuleInterface<IMonitorModule>().GetMonitor( m_sp.Scene.RegionInfo.RegionID.ToString(), MonitorModuleHelper.AgentUpdateCount); if (reporter != null) { reporter.AddAgentUpdates(count); } } /// <summary> /// Send appearance data to an agent. /// </summary> /// <param name = "avatar"></param> public void SendAppearanceToAgent(IScenePresence avatar) { avatar.ControllingClient.SendAppearance( Appearance.Owner, Appearance.VisualParams, Appearance.Texture.GetBytes()); } public AvatarAppearance Appearance { get { return m_appearance; } set { m_appearance = value; } } #endregion public void Close() { m_sp.Scene.EventManager.OnMakeRootAgent -= EventManager_OnMakeRootAgent; m_sp = null; } private void EventManager_OnMakeRootAgent(IScenePresence presence) { if (m_sp != null && presence.UUID == m_sp.UUID) { //Send everyone to me! SendOtherAgentsAvatarDataToMe(); //Check to make sure that we have sent all the appearance info 10 seconds later Timer t = new Timer(10*1000); t.Elapsed += CheckToMakeSureWearablesHaveBeenSent; t.AutoReset = false; t.Start(); } } /// <summary> /// Send avatar data for all other root agents to this agent, this agent /// can be either a child or root /// </summary> public void SendOtherAgentsAvatarDataToMe() { int count = 0; m_sp.Scene.ForEachScenePresence(delegate(IScenePresence scenePresence) { // only send information about root agents if (scenePresence.IsChildAgent) return; // only send information about other root agents if (scenePresence.UUID == m_sp.UUID) return; IAvatarAppearanceModule appearance = scenePresence.RequestModuleInterface <IAvatarAppearanceModule>(); if (appearance != null) appearance.SendAvatarDataToAgent(m_sp, true); count++; }); IAgentUpdateMonitor reporter = (IAgentUpdateMonitor) m_sp.Scene.RequestModuleInterface<IMonitorModule>().GetMonitor( m_sp.Scene.RegionInfo.RegionID.ToString(), MonitorModuleHelper.AgentUpdateCount); if (reporter != null) { reporter.AddAgentUpdates(count); } } /// <summary> /// This makes sure that after the agent has entered the sim that they have their clothes and that they all exist /// </summary> /// <param name = "sender"></param> /// <param name = "e"></param> private void CheckToMakeSureWearablesHaveBeenSent(object sender, ElapsedEventArgs e) { if (m_sp == null) return; if (!m_InitialHasWearablesBeenSent) { //Force send! m_InitialHasWearablesBeenSent = true; MainConsole.Instance.Warn("[AvatarAppearanceModule]: Been 10 seconds since root agent " + m_sp.Name + " was added and appearance was not sent, force sending now."); m_sp.ControllingClient.SendWearables(Appearance.Wearables, Appearance.Serial); //Send rebakes if needed // NOTE: Do NOT send this! It seems to make the client become a cloud //sp.SendAppearanceToAgent(sp); // If the avatars baked textures are all in the cache, then we have a // complete appearance... send it out, if not, then we'll send it when // the avatar finishes updating its appearance SendAppearanceToAllOtherAgents(); // This agent just became roo t. We are going to tell everyone about it. The process of // getting other avatars information was initiated in the constructor... don't do it // again here... SendAvatarDataToAllAgents(true); //Tell us about everyone else as well now that we are here SendOtherAgentsAppearanceToMe(); } } } #endregion } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos/Networking/Responses/GetHatchedEggsResponse.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace POGOProtos.Networking.Responses { /// <summary>Holder for reflection information generated from POGOProtos/Networking/Responses/GetHatchedEggsResponse.proto</summary> public static partial class GetHatchedEggsResponseReflection { #region Descriptor /// <summary>File descriptor for POGOProtos/Networking/Responses/GetHatchedEggsResponse.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static GetHatchedEggsResponseReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjxQT0dPUHJvdG9zL05ldHdvcmtpbmcvUmVzcG9uc2VzL0dldEhhdGNoZWRF", "Z2dzUmVzcG9uc2UucHJvdG8SH1BPR09Qcm90b3MuTmV0d29ya2luZy5SZXNw", "b25zZXMijgEKFkdldEhhdGNoZWRFZ2dzUmVzcG9uc2USDwoHc3VjY2VzcxgB", "IAEoCBIWCgpwb2tlbW9uX2lkGAIgAygGQgIQARIaChJleHBlcmllbmNlX2F3", "YXJkZWQYAyADKAUSFQoNY2FuZHlfYXdhcmRlZBgEIAMoBRIYChBzdGFyZHVz", "dF9hd2FyZGVkGAUgAygFYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Networking.Responses.GetHatchedEggsResponse), global::POGOProtos.Networking.Responses.GetHatchedEggsResponse.Parser, new[]{ "Success", "PokemonId", "ExperienceAwarded", "CandyAwarded", "StardustAwarded" }, null, null, null) })); } #endregion } #region Messages public sealed partial class GetHatchedEggsResponse : pb::IMessage<GetHatchedEggsResponse> { private static readonly pb::MessageParser<GetHatchedEggsResponse> _parser = new pb::MessageParser<GetHatchedEggsResponse>(() => new GetHatchedEggsResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GetHatchedEggsResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Networking.Responses.GetHatchedEggsResponseReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetHatchedEggsResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetHatchedEggsResponse(GetHatchedEggsResponse other) : this() { success_ = other.success_; pokemonId_ = other.pokemonId_.Clone(); experienceAwarded_ = other.experienceAwarded_.Clone(); candyAwarded_ = other.candyAwarded_.Clone(); stardustAwarded_ = other.stardustAwarded_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetHatchedEggsResponse Clone() { return new GetHatchedEggsResponse(this); } /// <summary>Field number for the "success" field.</summary> public const int SuccessFieldNumber = 1; private bool success_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Success { get { return success_; } set { success_ = value; } } /// <summary>Field number for the "pokemon_id" field.</summary> public const int PokemonIdFieldNumber = 2; private static readonly pb::FieldCodec<ulong> _repeated_pokemonId_codec = pb::FieldCodec.ForFixed64(18); private readonly pbc::RepeatedField<ulong> pokemonId_ = new pbc::RepeatedField<ulong>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<ulong> PokemonId { get { return pokemonId_; } } /// <summary>Field number for the "experience_awarded" field.</summary> public const int ExperienceAwardedFieldNumber = 3; private static readonly pb::FieldCodec<int> _repeated_experienceAwarded_codec = pb::FieldCodec.ForInt32(26); private readonly pbc::RepeatedField<int> experienceAwarded_ = new pbc::RepeatedField<int>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<int> ExperienceAwarded { get { return experienceAwarded_; } } /// <summary>Field number for the "candy_awarded" field.</summary> public const int CandyAwardedFieldNumber = 4; private static readonly pb::FieldCodec<int> _repeated_candyAwarded_codec = pb::FieldCodec.ForInt32(34); private readonly pbc::RepeatedField<int> candyAwarded_ = new pbc::RepeatedField<int>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<int> CandyAwarded { get { return candyAwarded_; } } /// <summary>Field number for the "stardust_awarded" field.</summary> public const int StardustAwardedFieldNumber = 5; private static readonly pb::FieldCodec<int> _repeated_stardustAwarded_codec = pb::FieldCodec.ForInt32(42); private readonly pbc::RepeatedField<int> stardustAwarded_ = new pbc::RepeatedField<int>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<int> StardustAwarded { get { return stardustAwarded_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GetHatchedEggsResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GetHatchedEggsResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Success != other.Success) return false; if(!pokemonId_.Equals(other.pokemonId_)) return false; if(!experienceAwarded_.Equals(other.experienceAwarded_)) return false; if(!candyAwarded_.Equals(other.candyAwarded_)) return false; if(!stardustAwarded_.Equals(other.stardustAwarded_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Success != false) hash ^= Success.GetHashCode(); hash ^= pokemonId_.GetHashCode(); hash ^= experienceAwarded_.GetHashCode(); hash ^= candyAwarded_.GetHashCode(); hash ^= stardustAwarded_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Success != false) { output.WriteRawTag(8); output.WriteBool(Success); } pokemonId_.WriteTo(output, _repeated_pokemonId_codec); experienceAwarded_.WriteTo(output, _repeated_experienceAwarded_codec); candyAwarded_.WriteTo(output, _repeated_candyAwarded_codec); stardustAwarded_.WriteTo(output, _repeated_stardustAwarded_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Success != false) { size += 1 + 1; } size += pokemonId_.CalculateSize(_repeated_pokemonId_codec); size += experienceAwarded_.CalculateSize(_repeated_experienceAwarded_codec); size += candyAwarded_.CalculateSize(_repeated_candyAwarded_codec); size += stardustAwarded_.CalculateSize(_repeated_stardustAwarded_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GetHatchedEggsResponse other) { if (other == null) { return; } if (other.Success != false) { Success = other.Success; } pokemonId_.Add(other.pokemonId_); experienceAwarded_.Add(other.experienceAwarded_); candyAwarded_.Add(other.candyAwarded_); stardustAwarded_.Add(other.stardustAwarded_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Success = input.ReadBool(); break; } case 18: case 17: { pokemonId_.AddEntriesFrom(input, _repeated_pokemonId_codec); break; } case 26: case 24: { experienceAwarded_.AddEntriesFrom(input, _repeated_experienceAwarded_codec); break; } case 34: case 32: { candyAwarded_.AddEntriesFrom(input, _repeated_candyAwarded_codec); break; } case 42: case 40: { stardustAwarded_.AddEntriesFrom(input, _repeated_stardustAwarded_codec); break; } } } } } #endregion } #endregion Designer generated code
// 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 Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.as01.as01 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.as01.as01; // <Area>variance</Area> // <Title> As keyword in variance </Title> // <Description> Having a covariant delegate and assigning it to a bigger type through the as keyword</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success></Expects> // <Code> public class Animal { public virtual string speakName() { return "Animal"; } } public class Mammal : Animal { public override string speakName() { return "Mammal"; } } public class Tiger : Mammal { public override string speakName() { return "Tiger"; } } public class Giraffe : Mammal { public static explicit operator Tiger(Giraffe g) { return new Tiger(); } public override string speakName() { return "Giraffe"; } } public class C { public delegate T Foo<out T>(); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int result = 0; // scenario 1 dynamic f11 = (Foo<Tiger>)(() => { return new Tiger(); } ); Foo<Animal> f12 = f11 as Foo<Tiger>; Animal t1 = f12(); if (t1.speakName() != "Tiger") result++; // scenario 2 Foo<Tiger> f21 = () => { return new Tiger(); } ; dynamic f22 = (Foo<Animal>)(f21 as Foo<Tiger>); Animal t2 = f22(); if (t2.speakName() != "Tiger") result++; // scenario 3 dynamic f31 = (Foo<Tiger>)(() => { return new Tiger(); } ); dynamic f32 = (Foo<Animal>)(f31 as Foo<Tiger>); Animal t3 = f32(); if (t3.speakName() != "Tiger") result++; return result; } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.assignment01.assignment01 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.assignment01.assignment01; // <Area>variance</Area> // <Title> assignment with variance </Title> // <Description> assigning to a property type with an interface</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success></Expects> // <Code> public interface iVariance<out T> { T Boo(); } public class Variance<T> : iVariance<T> where T : new() { public T Boo() { return new T(); } } public class Animal { } public class Tiger : Animal { } public class C { public static iVariance<Animal> p1 { get; set; } public static dynamic p2 { get; set; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Variance<Tiger> v1 = new Variance<Tiger>(); dynamic v2 = new Variance<Tiger>(); try { p1 = v2; p1.Boo(); p2 = v1; p2.Boo(); p2 = v2; p2.Boo(); } catch (System.Exception) // should NOT throw out runtime exception so we needn't check the error message { return 1; } return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.assignment02.assignment02 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.assignment02.assignment02; // <Area>variance</Area> // <Title> assignment with variance </Title> // <Description> assigning to a property type with an interface</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success></Expects> // <Code> public interface iVariance<in T> { void Boo(T t); } public class Variance<T> : iVariance<T> { public void Boo(T t) { } } public class Animal { } public class Tiger : Animal { } public class C { public static iVariance<Tiger> p1 { get; set; } public static iVariance<Tiger> p2 { get; set; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Variance<Animal> v1 = new Variance<Animal>(); dynamic v2 = new Variance<Animal>(); try { p1 = v2; p1.Boo(new Tiger()); p2 = v1; p2.Boo(new Tiger()); p2 = v2; p2.Boo(new Tiger()); } catch (System.Exception) // should NOT throw out runtime exception so we needn't check the error message { return 1; } return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.assignment03.assignment03 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.assignment03.assignment03; // <Area>variance</Area> // <Title> Assignment to a property</Title> // <Description> basic contravariance on delegates assigning to a property </Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public class Animal { } public class Tiger : Animal { } public class C { public delegate void Foo<in T>(T t); public static Foo<Tiger> p1 { get; set; } public static dynamic p2 { get; set; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Foo<Animal> v1 = (Animal a) => { } ; dynamic v2 = (Foo<Animal>)((Animal a) => { } ); try { p1 = v2; p1(new Tiger()); p2 = v1; p2(new Tiger()); p2 = v2; p2(new Tiger()); } catch (System.Exception) // should NOT throw out runtime exception so we needn't check the error message { return 1; } return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.assignment04.assignment04 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.assignment04.assignment04; // <Area>variance</Area> // <Title> Assignment to an event </Title> // <Description> Having a covariant delegate and assigning it to an event</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public class Animal { } public class Tiger : Animal { } public class C { public delegate T Foo<out T>(); public static event Foo<Animal> e; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic f = (Foo<Tiger>)(() => { return new Tiger(); } ); e += f; Animal t = e(); return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.assignment05.assignment05 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.assignment05.assignment05; // <Area>variance</Area> // <Title> assignment of Contravariance to events</Title> // <Description> basic contravariance on delegates </Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public class Animal { } public class Tiger : Animal { } public class C { public delegate void Foo<in T>(T t); public static event Foo<Tiger> f2; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic f1 = (Foo<Animal>)((Animal a) => { } ); f2 += f1; f2(new Tiger()); return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.assignment06.assignment06 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.assignment06.assignment06; // <Area>variance</Area> // <Title> assignment of covariant types to an array</Title> // <Description> assignment of covariant types to an array </Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> //<Expects Status=warning>\(22,29\).*CS0649</Expects> public interface iVariance<out T> { T Boo(); } public class Variance<T> : iVariance<T> where T : new() { public T Boo() { return new T(); } } public class Animal { } public class Tiger : Animal { } public class C { public static iVariance<Animal>[] field1; public static dynamic[] field2; public static dynamic field3; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Variance<Tiger> v1 = new Variance<Tiger>(); dynamic v2 = new Variance<Tiger>(); field1 = new iVariance<Animal>[1]; field1[0] = v2; var x = field1[0].Boo(); //field2 = new iVariance<Animal>[1]; //field2[0] = v1; //field2[0].Boo(); //field2[0] = v2; //field2[0].Boo(); field3 = new iVariance<Animal>[1]; field3[0] = v1; field3[0].Boo(); field3[0] = v2; field3[0].Boo(); return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.assignment07.assignment07 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.assignment07.assignment07; // <Area>variance</Area> // <Title> assignment Contravariant delegates</Title> // <Description> contravariance on delegates assigned to arrays</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> //<Expects Status=warning>\(16,22\).*CS0169</Expects> public class Animal { } public class Tiger : Animal { } public class C { public delegate void Foo<in T>(T t); private static Foo<Tiger>[] s_array1; private static dynamic[] s_array2; private static dynamic s_array3; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Foo<Animal> f1 = (Animal a) => { } ; dynamic f2 = (Foo<Animal>)((Animal a) => { } ); s_array1 = new Foo<Tiger>[1]; s_array1[0] = f2; s_array1[0](new Tiger()); //array2 = new Foo<Tiger>[1]; //array2[0] = f1; //array2[0](new Tiger()); //array2[0] = f2; //array2[0](new Tiger()); s_array3 = new Foo<Tiger>[1]; s_array3[0] = f1; s_array3[0](new Tiger()); s_array3[0] = f2; s_array3[0](new Tiger()); return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.assignment08.assignment08 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.assignment08.assignment08; // <Area>variance</Area> // <Title> Basic covariance on delegate types passed to a function </Title> // <Description> Having a covariant delegate and passing it to a function</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public class Animal { } public class Tiger : Animal { } public class C { public delegate T Foo<out T>(); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Foo<Tiger> f1 = () => { return new Tiger(); } ; dynamic f2 = (Foo<Tiger>)(() => { return new Tiger(); } ); try { Bar1(f2); Bar2(f1); Bar2(f2); } catch (System.Exception) // should NOT throw out runtime exception so we needn't check the error message { return 1; } return 0; } public static void Bar1(Foo<Animal> f) { } public static void Bar2(dynamic f) { } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.assignment09.assignment09 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.assignment09.assignment09; // <Area>variance</Area> // <Title> contravariance on interfaces and passing to a method</Title> // <Description> calling methods with public interface contravariance </Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public interface iVariance<in T> { void Boo(T t); } public class Variance<T> : iVariance<T> { public void Boo(T t) { } } public class Animal { } public class Tiger : Animal { } public class C { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Variance<Animal> v1 = new Variance<Animal>(); dynamic v2 = new Variance<Animal>(); try { Bar1(v2); Bar2(v1); Bar2(v2); } catch (System.Exception) // should NOT throw out runtime exception so we needn't check the error message { return 1; } return 0; } public static void Bar1(iVariance<Tiger> f) { } public static void Bar2(dynamic f) { } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.assignment10.assignment10 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.assignment10.assignment10; // <Area>variance</Area> // <Title> contravariance on interfaces and passing to a method</Title> // <Description> calling methods with public interface contravariance </Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> using System; using System.Collections.Generic; public class B { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { IA<object> x = new A(); var y = new B(); y.Foo(x); dynamic z = y; z.Foo(x); return 0; } public void Foo(IA<string> x) { } } public interface IA<in T> { } public class A : IA<object> { } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.assignment11.assignment11 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.assignment11.assignment11; // <Area>variance</Area> // <Title> contravariance on interfaces and passing to a method</Title> // <Description> calling methods with public interface contravariance </Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> using System; using System.Collections.Generic; public class B { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { IA<dynamic> x = new A(); var y = new B(); y.Foo(x); dynamic z = y; z.Foo(x); return 0; } public void Foo(IA<string> x) { } } public interface IA<in T> { } public class A : IA<object> { } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.overload01.overload01 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.overload01.overload01; // <Area>variance</Area> // <Title> Operator overloading in variance </Title> // <Description> Having a covariant delegate and assigning it to a same level type with variance and implicit operator overloading</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success></Expects> // <Code> public class Animal { public virtual string speakName() { return "Animal"; } } public class Mammal : Animal { public override string speakName() { return "Mammal"; } } public class Tiger : Mammal { public override string speakName() { return "Tiger"; } } public class Giraffe : Mammal { public static implicit operator Tiger(Giraffe g) { return new Tiger(); } public override string speakName() { return "Giraffe"; } } public class C { public delegate T Foo<out T>(); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int result = 0, count = 0; dynamic f11 = (Foo<Giraffe>)(() => { return new Giraffe(); } ); try { result++; Foo<Tiger> f12 = f11; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { bool ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConv, ex.Message, "C.Foo<Giraffe>", "C.Foo<Tiger>"); if (ret) { result--; } } //Foo<Giraffe> f21 = () => { return new Giraffe(); }; //try //{ // result++; // dynamic f22 = (Foo<Tiger>)f21; //} //catch (System.InvalidCastException) //{ // result--; // System.Console.WriteLine("Scenario {0} passed.", ++count); //} dynamic f31 = (Foo<Giraffe>)(() => { return new Giraffe(); } ); try { result++; dynamic f32 = (Foo<Tiger>)f31; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { bool ret = ErrorVerifier.Verify(ErrorMessageId.NoExplicitConv, ex.Message, "C.Foo<Giraffe>", "C.Foo<Tiger>"); if (ret) { result--; } } return result; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.overload02.overload02 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.overload02.overload02; // <Area>variance</Area> // <Title> overload resolution</Title> // <Description> overload resolution in contravariant interfaces</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success></Expects> // <Code> public interface iVariance<in T> { void Boo(T t); } public class Variance<T> : iVariance<T> { public void Boo(T t) { } } public class Animal { } public class Mammal : Animal { } public class Tiger : Mammal { } public class Bear : Mammal { } public class C { public static int Bar(iVariance<Tiger> t) { return 2; } public static int Bar(iVariance<Bear> t) { return 1; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic v1 = new Variance<Animal>(); int result = 0; try { result = C.Bar(v1); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { bool ret = ErrorVerifier.Verify(ErrorMessageId.AmbigCall, ex.Message, "C.Bar(iVariance<Tiger>)", "C.Bar(iVariance<Bear>)"); if (ret) { return 0; } } //System.Console.WriteLine(result); return 1; } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.overload03.overload03 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.overload03.overload03; // <Area>variance</Area> // <Title> Operator overloading in variance </Title> // <Description> Having a contravariant delegate and assigning it to a bigger type with variance and explicit operator overloading</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success></Expects> // <Code> public class Animal { public virtual string speakName() { return "Animal"; } } public class Mammal : Animal { public override string speakName() { return "Mammal"; } } public class Tiger : Mammal { public override string speakName() { return "Tiger"; } } public class Giraffe : Mammal { public static explicit operator Tiger(Giraffe g) { return new Tiger(); } public override string speakName() { return "Giraffe"; } } public class C { public delegate void Foo<in T>(T t); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Foo<Animal> f10 = (Animal a) => { } ; dynamic f11 = (Foo<Tiger>)f10; Foo<Giraffe> f12 = (Foo<Giraffe>)f11; f11(new Tiger()); Foo<Animal> f20 = (Animal a) => { } ; dynamic f21 = (Foo<Tiger>)f20; dynamic f22 = (Foo<Giraffe>)f21; f22(new Tiger()); return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.overload04.overload04 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.overload04.overload04; // <Area>variance</Area> // <Title> Operator overloading in variance </Title> // <Description> Having a contravariant delegate and assigning it to a similar type with variance and implicit operator overloading</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success></Expects> // <Code> public class Animal { public virtual string speakName() { return "Animal"; } } public class Mammal : Animal { public override string speakName() { return "Mammal"; } } public class Tiger : Mammal { public override string speakName() { return "Tiger"; } } public class Giraffe : Mammal { public static implicit operator Tiger(Giraffe g) { return new Tiger(); } public override string speakName() { return "Giraffe"; } } public class C { public delegate void Foo<in T>(T t); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Foo<Animal> f = (Animal a) => { } ; dynamic f11 = (Foo<Tiger>)f; Foo<Giraffe> f12 = (Foo<Giraffe>)f11; f11(new Tiger()); dynamic f21 = (Foo<Tiger>)f; dynamic f22 = (Foo<Giraffe>)f21; f22(new Tiger()); return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.overload05.overload05 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.overload05.overload05; // <Area>variance</Area> // <Title> Operator overloading in variance </Title> // <Description> Having a contravariant public interface and assigning it to a similar type with variance and implicit operator overloading</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success></Expects> // <Code> public class Animal { public virtual string speakName() { return "Animal"; } } public class Mammal : Animal { public override string speakName() { return "Mammal"; } } public class Tiger : Mammal { public override string speakName() { return "Tiger"; } } public class Giraffe : Mammal { public static implicit operator Tiger(Giraffe g) { return new Tiger(); } public override string speakName() { return "Giraffe"; } } public interface iVariance<in T> { void Boo(T t); } public class Variance<T> : iVariance<T> { public void Boo(T t) { } } public class C { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int result = 0, count = 0; dynamic v11 = new Variance<Tiger>(); try { result++; iVariance<Giraffe> v12 = v11; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { bool ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, ex.Message, "Variance<Tiger>", "iVariance<Giraffe>"); if (ret) { result--; } } dynamic v21 = new Variance<Tiger>(); try { result++; dynamic v22 = (iVariance<Giraffe>)v21; } catch (System.InvalidCastException) { result--; } return result; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.resolution01.resolution01 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.resolution01.resolution01; // <Area>variance</Area> // <Title> overload resolution</Title> // <Description> overload resolution </Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public interface iVariance<out T> { T Boo(); } public class Variance<T> : iVariance<T> { public T Boo() { return default(T); } } public class Animal { } public class Mammal : Animal { } public class Tiger : Mammal { } public class C { public static int Bar(iVariance<Animal> t) { return 2; } public static int Bar(iVariance<Mammal> t) { return 1; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic v1 = (iVariance<Tiger>)new Variance<Tiger>(); int result = C.Bar(v1); if (result != 1) return 1; return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.resolution02.resolution02 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.resolution02.resolution02; // <Area>variance</Area> // <Title> overload resolution</Title> // <Description> overload resolution in contravariant interfaces</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success></Expects> // <Code> public interface iVariance<in T> { void Boo(T t); } public class Variance<T> : iVariance<T> { public void Boo(T t) { } } public class Animal { } public class Mammal : Animal { } public class Tiger : Mammal { } public class Bear : Mammal { } public class C { public static int Bar(iVariance<Tiger> t) { return 2; } public static int Bar(iVariance<Bear> t) { return 1; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic v1 = new Variance<Animal>(); int result = 0; try { result = C.Bar(v1); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) { return 0; } //System.Console.WriteLine(result); return 1; } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.resolution03.resolution03 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.resolution03.resolution03; // <Area>variance</Area> // <Title> overload resolution</Title> // <Description> overload resolution in contravariant interfaces</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success></Expects> // <Code> public interface iVariance<in T> { void Boo(T t); } public class Variance<T> : iVariance<T> { public void Boo(T t) { } } public class Animal { } public class Mammal : Animal { } public class Tiger : Mammal { } public class Bear : Mammal { } public class C { public static int Bar(iVariance<Tiger> t) { return 2; } public static int Bar(iVariance<Mammal> t) { return 1; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic v1 = (iVariance<Animal>)(new Variance<Animal>()); int result = C.Bar(v1); if (result == 1) return 0; return 1; } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.resolution04.resolution04 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.resolution04.resolution04; // <Area>variance</Area> // <Title> overload resolution</Title> // <Description> overload resolution </Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public interface iVariance<out T> { T Boo(); } public class Variance<T> : iVariance<T> { public T Boo() { return default(T); } } public class Animal { } public class Mammal : Animal { } public class Tiger : Mammal { } public class C { public int Bar(iVariance<Animal> t) { return 2; } public int Bar(iVariance<Mammal> t) { return 1; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic v1 = (iVariance<Tiger>)(new Variance<Tiger>()); dynamic c = new C(); var result = c.Bar(v1); if (result == 1) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.resolution05.resolution05 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.assign.resolution05.resolution05; // <Area>variance</Area> // <Title> overload resolution</Title> // <Description> overload resolution </Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public interface iVariance<out T> { T Boo(); } public class Variance<T> : iVariance<T> { public T Boo() { return default(T); } } public class Animal { } public class Mammal : Animal { } public class Tiger : Mammal { } public class B { public static int Bar(iVariance<Mammal> t) { return 1; } } public class C : B { public static int Bar(iVariance<Animal> t) { return 2; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic v1 = (iVariance<Tiger>)(new Variance<Tiger>()); var result = C.Bar(v1); if (result == 2) return 0; return 1; } } //</Code> }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.ComponentModel.EventBasedAsync.Tests { public class BackgroundWorkerTests { private const int TimeoutShort = 300; private const int TimeoutLong = 30000; [Fact] public void TestBackgroundWorkerBasic() { var orignal = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(null); const int expectedResult = 42; const int expectedReportCallsCount = 5; int actualReportCallsCount = 0; var worker = new BackgroundWorker() { WorkerReportsProgress = true }; var progressBarrier = new Barrier(2, barrier => ++actualReportCallsCount); var workerCompletedEvent = new ManualResetEventSlim(false); worker.DoWork += (sender, e) => { for (int i = 0; i < expectedReportCallsCount; i++) { worker.ReportProgress(i); progressBarrier.SignalAndWait(); } e.Result = expectedResult; }; worker.RunWorkerCompleted += (sender, e) => { try { Assert.Equal(expectedResult, (int)e.Result); Assert.False(worker.IsBusy); } finally { workerCompletedEvent.Set(); } }; worker.ProgressChanged += (sender, e) => { progressBarrier.SignalAndWait(); }; worker.RunWorkerAsync(); // wait for singal from WhenRunWorkerCompleted Assert.True(workerCompletedEvent.Wait(TimeoutLong)); Assert.False(worker.IsBusy); Assert.Equal(expectedReportCallsCount, actualReportCallsCount); } finally { SynchronizationContext.SetSynchronizationContext(orignal); } } #region TestCancelAsync private ManualResetEventSlim manualResetEvent3; [Fact] public void TestCancelAsync() { BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += DoWorkExpectCancel; bw.WorkerSupportsCancellation = true; manualResetEvent3 = new ManualResetEventSlim(false); bw.RunWorkerAsync("Message"); bw.CancelAsync(); bool ret = manualResetEvent3.Wait(TimeoutLong); Assert.True(ret); // there could be race condition between worker thread cancellation and completion which will set the CancellationPending to false // if it is completed already, we don't check cancellation if (bw.IsBusy) // not complete { if (!bw.CancellationPending) { for (int i = 0; i < 1000; i++) { Wait(TimeoutShort); if (bw.CancellationPending) { break; } } } // Check again if (bw.IsBusy) Assert.True(bw.CancellationPending, "Cancellation in Main thread"); } } private void DoWorkExpectCancel(object sender, DoWorkEventArgs e) { Assert.Equal("Message", e.Argument); var bw = sender as BackgroundWorker; if (bw.CancellationPending) { manualResetEvent3.Set(); return; } // we want to wait for cancellation - wait max (1000 * TimeoutShort) milliseconds for (int i = 0; i < 1000; i++) { Wait(TimeoutShort); if (bw.CancellationPending) { break; } } Assert.True(bw.CancellationPending, "Cancellation in Worker thread"); // signal no matter what, even if it's not cancelled by now manualResetEvent3.Set(); } #endregion [Fact] public void TestThrowExceptionInDoWork() { var original = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(null); const string expectedArgument = "Exception"; const string expectedExceptionMsg = "Exception from DoWork"; var bw = new BackgroundWorker(); var workerCompletedEvent = new ManualResetEventSlim(false); bw.DoWork += (sender, e) => { Assert.Same(bw, sender); Assert.Same(expectedArgument, e.Argument); throw new TestException(expectedExceptionMsg); }; bw.RunWorkerCompleted += (sender, e) => { try { TestException ex = Assert.Throws<TestException>(() => e.Result); Assert.Equal(expectedExceptionMsg, ex.Message); } finally { workerCompletedEvent.Set(); } }; bw.RunWorkerAsync(expectedArgument); Assert.True(workerCompletedEvent.Wait(TimeoutLong), "Background work timeout"); } finally { SynchronizationContext.SetSynchronizationContext(original); } } [Fact] public void CtorTest() { var bw = new BackgroundWorker(); Assert.False(bw.IsBusy); Assert.False(bw.WorkerReportsProgress); Assert.False(bw.WorkerSupportsCancellation); Assert.False(bw.CancellationPending); } [Fact] public void RunWorkerAsyncTwice() { var bw = new BackgroundWorker(); var barrier = new Barrier(2); bw.DoWork += (sender, e) => { barrier.SignalAndWait(); barrier.SignalAndWait(); }; bw.RunWorkerAsync(); barrier.SignalAndWait(); try { Assert.True(bw.IsBusy); Assert.Throws<InvalidOperationException>(() => bw.RunWorkerAsync()); } finally { barrier.SignalAndWait(); } } [Fact] public void TestCancelInsideDoWork() { var original = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(null); var bw = new BackgroundWorker() { WorkerSupportsCancellation = true }; var barrier = new Barrier(2); bw.DoWork += (sender, e) => { barrier.SignalAndWait(); barrier.SignalAndWait(); if (bw.CancellationPending) { e.Cancel = true; } }; bw.RunWorkerCompleted += (sender, e) => { Assert.True(e.Cancelled); barrier.SignalAndWait(); }; bw.RunWorkerAsync(); barrier.SignalAndWait(); bw.CancelAsync(); barrier.SignalAndWait(); Assert.True(barrier.SignalAndWait(TimeoutLong), "Background work timeout"); } finally { SynchronizationContext.SetSynchronizationContext(original); } } [Fact] public void TestCancelAsyncWithoutCancellationSupport() { var bw = new BackgroundWorker() { WorkerSupportsCancellation = false }; Assert.Throws<InvalidOperationException>(() => bw.CancelAsync()); } [Fact] public void TestReportProgressSync() { var bw = new BackgroundWorker() { WorkerReportsProgress = true }; var expectedProgress = new int[] { 1, 2, 3, 4, 5 }; var actualProgress = new List<int>(); bw.ProgressChanged += (sender, e) => { actualProgress.Add(e.ProgressPercentage); }; foreach (int i in expectedProgress) { bw.ReportProgress(i); } Assert.Equal(expectedProgress, actualProgress); } [Fact] public void TestReportProgressWithWorkerReportsProgressFalse() { var bw = new BackgroundWorker() { WorkerReportsProgress = false }; Assert.Throws<InvalidOperationException>(() => bw.ReportProgress(42)); } [Fact] public void DisposeTwiceShouldNotThrow() { var bw = new BackgroundWorker(); bw.Dispose(); bw.Dispose(); } [Fact] public void TestFinalization() { // BackgroundWorker has a finalizer that exists purely for backwards compatibility // with existing code that may override Dispose to clean up native resources. // https://github.com/dotnet/corefx/pull/752 ManualResetEventSlim mres = SetEventWhenFinalizedBackgroundWorker.CreateAndThrowAway(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Assert.True(mres.Wait(10000)); } private sealed class SetEventWhenFinalizedBackgroundWorker : BackgroundWorker { private ManualResetEventSlim _setWhenFinalized; internal static ManualResetEventSlim CreateAndThrowAway() { var mres = new ManualResetEventSlim(); new SetEventWhenFinalizedBackgroundWorker() { _setWhenFinalized = mres }; return mres; } protected override void Dispose(bool disposing) { _setWhenFinalized.Set(); } } private static void Wait(int milliseconds) { Task.Delay(milliseconds).Wait(); } } }
using Customer.Data.DB_Setup_AGV_BST1; using Customer.Data.DB_SpindlePos_BST1; using Dacs7.ReadWrite; using Insite.Customer.Data.DB_IPSC_Konfig; using Papper; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Xunit; namespace Dacs7.Papper.Tests { public class PapperConnectionTest { private Dacs7Client _client; private PlcDataMapper _mapper; [Theory] [InlineData("DB_SpindlePos_BST1", typeof(DB_SpindlePos_BST1))] [InlineData("DB_IPSC_Konfig", typeof(DB_IPSC_Konfig))] [InlineData("DB_Setup_AGV_BST1", typeof(DB_Setup_AGV_BST1))] public async Task TestMultiWrite(string mapping, Type type) { _client = new Dacs7Client("192.168.0.148:102,0,2", PlcConnectionType.Basic, 5000); await _client.ConnectAsync(); if (_client.IsConnected && (_mapper == null || _mapper.PduSize > _client.PduSize)) { var pduSize = _client.PduSize; _mapper = new PlcDataMapper(pduSize, Papper_OnRead, Papper_OnWrite, OptimizerType.Items); _mapper.AddMapping(type); } var data = await _mapper.ReadAsync(PlcReadReference.FromAddress($"{mapping}.This")); await _mapper.WriteAsync(PlcWriteReference.FromAddress($"{mapping}.This", data)); await _client.DisconnectAsync(); } private static void SetPropertyInExpandoObject(dynamic parent, string address, object value) => SetPropertyInExpandoObject(parent, address.Replace("[", ".[").Split('.'), value); private static void SetPropertyInExpandoObject(dynamic parent, IEnumerable<string> parts, object value) { var key = parts.First(); parts = parts.Skip(1); if (parent is IList<object> list) { var index = int.Parse(key.TrimStart('[').TrimEnd(']'), CultureInfo.InvariantCulture); if (parts.Any()) { SetPropertyInExpandoObject(list.ElementAt(index), parts, value); } else { list[index] = value; } } else { if (parent is IDictionary<string, object> dictionary) { if (parts.Any()) { SetPropertyInExpandoObject(dictionary[key], parts, value); } else { dictionary[key] = value; } } } } private static object GetPropertyInExpandoObject(dynamic parent, string address) => GetPropertyInExpandoObject(parent, address.Replace("[", ".[").Split('.')); private static object GetPropertyInExpandoObject(dynamic parent, IEnumerable<string> parts) { var key = parts.First(); parts = parts.Skip(1); if (parent is IList<object> list) { var index = int.Parse(key.TrimStart('[').TrimEnd(']'), CultureInfo.InvariantCulture); if (parts.Any()) { return GetPropertyInExpandoObject(list.ElementAt(index), parts); // TODO } else { return list.ElementAt(index); } } else { if (parent is IDictionary<string, object> dictionary) { if (parts.Any()) { return GetPropertyInExpandoObject(dictionary[key], parts); } else { return dictionary[key]; } } } return null; } private async Task Papper_OnRead(IEnumerable<DataPack> reads) { try { if (!reads.Any()) { return; } var readAddresses = reads.Select(w => ReadItem.Create<byte[]>(w.Selector, (ushort)w.Offset, (ushort)w.Length)).ToList(); var results = await _client.ReadAsync(readAddresses).ConfigureAwait(false); reads.AsParallel().Select((item, index) => { if (results != null) { var result = results.ElementAt(index); item.ApplyData(result.Data); item.ExecutionResult = result.ReturnCode == ItemResponseRetValue.Success ? ExecutionResult.Ok : ExecutionResult.Error; } else { item.ExecutionResult = ExecutionResult.Error; } return true; }).ToList(); } catch (Exception) { reads.AsParallel().Select((item, index) => { item.ExecutionResult = ExecutionResult.Error; return true; }).ToList(); } } private async Task Papper_OnWrite(IEnumerable<DataPack> writes) { try { var result = writes.ToList(); var results = await _client.WriteAsync(writes.SelectMany(BuildWritePackages)).ConfigureAwait(false); writes.AsParallel().Select((item, index) => { if (results != null) { item.ExecutionResult = results.ElementAt(index) == ItemResponseRetValue.Success ? ExecutionResult.Ok : ExecutionResult.Error; } else { item.ExecutionResult = ExecutionResult.Error; } return true; }).ToList(); } catch (Exception) { writes.AsParallel().Select((item, index) => { item.ExecutionResult = ExecutionResult.Error; return true; }).ToList(); } } private static IEnumerable<WriteItem> BuildWritePackages(DataPack w) { var result = new List<WriteItem>(); if (!w.HasBitMask) { result.Add(WriteItem.Create(w.Selector, (ushort)w.Offset, w.Data)); } else { if (w.Data.Length > 0) { SetupBitMask(w, result, end: false); } if (w.Data.Length > 2) { result.Add(WriteItem.Create(w.Selector, (w.Offset + 1), w.Data.Slice(1, w.Data.Length - 2))); } if (w.Data.Length > 1) { SetupBitMask(w, result, end: true); } } return result; } private static void SetupBitMask(DataPack w, List<WriteItem> result, bool end = false) { var bytePos = end ? w.Data.Length - 1 : 0; var bm = end ? w.BitMaskEnd : w.BitMaskBegin; var currentByte = w.Data.Span[bytePos]; var currentOffset = (w.Offset + bytePos) * 8; for (var j = 0; j < 8; j++) { if (bm.GetBit(j)) { var bitOffset = (currentOffset + j); result.Add(WriteItem.Create(w.Selector, bitOffset, currentByte.GetBit(j))); bm = bm.SetBit(j, false); if (bm == 0) { break; } } } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using NPOI.POIFS.Common; using NPOI.POIFS.Dev; using NPOI.POIFS.NIO; using NPOI.POIFS.Properties; using NPOI.POIFS.Storage; using NPOI.Util; using NPOI.POIFS.EventFileSystem; namespace NPOI.POIFS.FileSystem { /** * This is the main class of the POIFS system; it manages the entire * life cycle of the filesystem. * This is the new NIO version */ public class NPOIFSFileSystem : BlockStore, POIFSViewable //, Closeable Leon { private static POILogger _logger = POILogFactory.GetLogger(typeof(NPOIFSFileSystem)); /** * Convenience method for clients that want to avoid the auto-close behaviour of the constructor. */ public static Stream CreateNonClosingInputStream(Stream stream) { return new CloseIgnoringInputStream(stream); } private NPOIFSMiniStore _mini_store; private NPropertyTable _property_table; private List<BATBlock> _xbat_blocks; private List<BATBlock> _bat_blocks; private HeaderBlock _header; private DirectoryNode _root; private DataSource _data; /** * What big block size the file uses. Most files * use 512 bytes, but a few use 4096 */ private POIFSBigBlockSize bigBlockSize = POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS; public DataSource Data { get { return _data; } set { _data = value; } } private NPOIFSFileSystem(bool newFS) { _header = new HeaderBlock(bigBlockSize); _property_table = new NPropertyTable(_header); _mini_store = new NPOIFSMiniStore(this, _property_table.Root, new List<BATBlock>(), _header); _xbat_blocks = new List<BATBlock>(); _bat_blocks = new List<BATBlock>(); _root = null; if (newFS) { // Data needs to Initially hold just the header block, // a single bat block, and an empty properties section _data = new ByteArrayBackedDataSource(new byte[bigBlockSize.GetBigBlockSize() * 3]); } } /** * Constructor, intended for writing */ public NPOIFSFileSystem() : this(true) { // Mark us as having a single empty BAT at offset 0 _header.BATCount = 1; _header.BATArray = new int[] { 0 }; _bat_blocks.Add(BATBlock.CreateEmptyBATBlock(bigBlockSize, false)); SetNextBlock(0, POIFSConstants.FAT_SECTOR_BLOCK); // Now associate the properties with the empty block _property_table.StartBlock = 1; SetNextBlock(1, POIFSConstants.END_OF_CHAIN); } public NPOIFSFileSystem(FileStream channel) : this(channel, true) { } private NPOIFSFileSystem(FileStream channel, bool closeChannelOnError) : this(false) { try { // Get the header byte[] headerBuffer = new byte[POIFSConstants.SMALLER_BIG_BLOCK_SIZE]; IOUtils.ReadFully(channel, headerBuffer); // Have the header Processed _header = new HeaderBlock(headerBuffer); // Now process the various entries _data = new FileBackedDataSource(channel); ReadCoreContents(); channel.Close(); } catch (IOException e) { if (closeChannelOnError) { channel.Close(); } throw e; } catch (Exception e) { // Comes from Iterators etc. // TODO Decide if we can handle these better whilst // still sticking to the iterator contract if (closeChannelOnError) { channel.Close(); } throw e; } } /** * Create a POIFSFileSystem from an <tt>InputStream</tt>. Normally the stream is read until * EOF. The stream is always closed.<p/> * * Some streams are usable After reaching EOF (typically those that return <code>true</code> * for <tt>markSupported()</tt>). In the unlikely case that the caller has such a stream * <i>and</i> needs to use it After this constructor completes, a work around is to wrap the * stream in order to trap the <tt>close()</tt> call. A convenience method ( * <tt>CreateNonClosingInputStream()</tt>) has been provided for this purpose: * <pre> * InputStream wrappedStream = POIFSFileSystem.CreateNonClosingInputStream(is); * HSSFWorkbook wb = new HSSFWorkbook(wrappedStream); * is.Reset(); * doSomethingElse(is); * </pre> * Note also the special case of <tt>MemoryStream</tt> for which the <tt>close()</tt> * method does nothing. * <pre> * MemoryStream bais = ... * HSSFWorkbook wb = new HSSFWorkbook(bais); // calls bais.Close() ! * bais.Reset(); // no problem * doSomethingElse(bais); * </pre> * * @param stream the InputStream from which to read the data * * @exception IOException on errors Reading, or on invalid data */ public NPOIFSFileSystem(Stream stream) : this(false) { Stream channel = null; bool success = false; try { // Turn our InputStream into something NIO based channel = stream; // Get the header ByteBuffer headerBuffer = ByteBuffer.CreateBuffer(POIFSConstants.SMALLER_BIG_BLOCK_SIZE); IOUtils.ReadFully(channel, headerBuffer.Buffer); // Have the header Processed _header = new HeaderBlock(headerBuffer); // Sanity check the block count BlockAllocationTableReader.SanityCheckBlockCount(_header.BATCount); // We need to buffer the whole file into memory when // working with an InputStream. // The max possible size is when each BAT block entry is used int maxSize = BATBlock.CalculateMaximumSize(_header); //ByteBuffer data = ByteBuffer.allocate(maxSize); // byte[] data = new byte[maxSize]; //// Copy in the header //for(int i = 0; i < headerBuffer.Length; i++) //{ // data[i] = headerBuffer[i]; //} // byte[] temp = new byte[channel.Length]; // Now read the rest of the stream ByteBuffer data = ByteBuffer.CreateBuffer(maxSize); headerBuffer.Position = 0; data.Write(headerBuffer.Buffer); data.Position = headerBuffer.Length; //IOUtils.ReadFully(channel, data); data.Position += IOUtils.ReadFully(channel, data.Buffer, data.Position, (int)channel.Length); success = true; // Turn it into a DataSource _data = new ByteArrayBackedDataSource(data.Buffer, data.Position); } finally { // As per the constructor contract, always close the stream if (channel != null) channel.Close(); CloseInputStream(stream, success); } // Now process the various entries ReadCoreContents(); } /** * @param stream the stream to be closed * @param success <code>false</code> if an exception is currently being thrown in the calling method */ private void CloseInputStream(Stream stream, bool success) { try { stream.Close(); } catch (IOException e) { if (success) { throw new Exception(e.Message); } } } /** * Read and process the PropertiesTable and the * FAT / XFAT blocks, so that we're Ready to * work with the file */ private void ReadCoreContents() { // Grab the block size bigBlockSize = _header.BigBlockSize; // Each block should only ever be used by one of the // FAT, XFAT or Property Table. Ensure it does ChainLoopDetector loopDetector = GetChainLoopDetector(); // Read the FAT blocks foreach (int fatAt in _header.BATArray) { ReadBAT(fatAt, loopDetector); } // Work out how many FAT blocks remain in the XFATs int remainingFATs = _header.BATCount - _header.BATArray.Length; // Now read the XFAT blocks, and the FATs within them BATBlock xfat; int nextAt = _header.XBATIndex; for (int i = 0; i < _header.XBATCount; i++) { loopDetector.Claim(nextAt); ByteBuffer fatData = GetBlockAt(nextAt); xfat = BATBlock.CreateBATBlock(bigBlockSize, fatData); xfat.OurBlockIndex = nextAt; nextAt = xfat.GetValueAt(bigBlockSize.GetXBATEntriesPerBlock()); _xbat_blocks.Add(xfat); // Process all the (used) FATs from this XFAT int xbatFATs = Math.Min(remainingFATs, bigBlockSize.GetXBATEntriesPerBlock()); for(int j=0; j<xbatFATs; j++) { int fatAt = xfat.GetValueAt(j); if (fatAt == POIFSConstants.UNUSED_BLOCK || fatAt == POIFSConstants.END_OF_CHAIN) break; ReadBAT(fatAt, loopDetector); } remainingFATs -= xbatFATs; } // We're now able to load steams // Use this to read in the properties _property_table = new NPropertyTable(_header, this); // Finally read the Small Stream FAT (SBAT) blocks BATBlock sfat; List<BATBlock> sbats = new List<BATBlock>(); _mini_store = new NPOIFSMiniStore(this, _property_table.Root, sbats, _header); nextAt = _header.SBATStart; for (int i = 0; i < _header.SBATCount; i++) { loopDetector.Claim(nextAt); ByteBuffer fatData = GetBlockAt(nextAt); sfat = BATBlock.CreateBATBlock(bigBlockSize, fatData); sfat.OurBlockIndex = nextAt; sbats.Add(sfat); nextAt = GetNextBlock(nextAt); } } private void ReadBAT(int batAt, ChainLoopDetector loopDetector) { loopDetector.Claim(batAt); ByteBuffer fatData = GetBlockAt(batAt); // byte[] fatData = GetBlockAt(batAt); BATBlock bat = BATBlock.CreateBATBlock(bigBlockSize, fatData); bat.OurBlockIndex = batAt; _bat_blocks.Add(bat); } private BATBlock CreateBAT(int offset, bool isBAT) { // Create a new BATBlock BATBlock newBAT = BATBlock.CreateEmptyBATBlock(bigBlockSize, !isBAT); newBAT.OurBlockIndex = offset; // Ensure there's a spot in the file for it ByteBuffer buffer = ByteBuffer.CreateBuffer(bigBlockSize.GetBigBlockSize()); int WriteTo = (1 + offset) * bigBlockSize.GetBigBlockSize(); // Header isn't in BATs _data.Write(buffer, WriteTo); // All done return newBAT; } /** * Load the block at the given offset. */ public override ByteBuffer GetBlockAt(int offset) { // The header block doesn't count, so add one long startAt = (offset + 1) * bigBlockSize.GetBigBlockSize(); return _data.Read(bigBlockSize.GetBigBlockSize(), startAt); } /** * Load the block at the given offset, * extending the file if needed */ public override ByteBuffer CreateBlockIfNeeded(int offset) { try { return GetBlockAt(offset); } catch (IndexOutOfRangeException) { // The header block doesn't count, so add one long startAt = (offset + 1) * bigBlockSize.GetBigBlockSize(); // Allocate and write ByteBuffer buffer = ByteBuffer.CreateBuffer(GetBigBlockSize()); // byte[] buffer = new byte[GetBigBlockSize()]; _data.Write(buffer, startAt); // Retrieve the properly backed block return GetBlockAt(offset); } } /** * Returns the BATBlock that handles the specified offset, * and the relative index within it */ public override BATBlockAndIndex GetBATBlockAndIndex(int offset) { return BATBlock.GetBATBlockAndIndex(offset, _header, _bat_blocks); } /** * Works out what block follows the specified one. */ public override int GetNextBlock(int offset) { BATBlockAndIndex bai = GetBATBlockAndIndex(offset); return bai.Block.GetValueAt(bai.Index); } /** * Changes the record of what block follows the specified one. */ public override void SetNextBlock(int offset, int nextBlock) { BATBlockAndIndex bai = GetBATBlockAndIndex(offset); bai.Block.SetValueAt(bai.Index, nextBlock); } /** * Finds a free block, and returns its offset. * This method will extend the file if needed, and if doing * so, allocate new FAT blocks to Address the extra space. */ public override int GetFreeBlock() { // First up, do we have any spare ones? int offset = 0; for (int i = 0; i < _bat_blocks.Count; i++) { int numSectors = bigBlockSize.GetBATEntriesPerBlock(); // Check this one BATBlock temp = _bat_blocks[i]; if (temp.HasFreeSectors) { // Claim one of them and return it for (int j = 0; j < numSectors; j++) { int batValue = temp.GetValueAt(j); if (batValue == POIFSConstants.UNUSED_BLOCK) { // Bingo return offset + j; } } } // Move onto the next BAT offset += numSectors; } // If we Get here, then there aren't any free sectors // in any of the BATs, so we need another BAT BATBlock bat = CreateBAT(offset, true); bat.SetValueAt(0, POIFSConstants.FAT_SECTOR_BLOCK); _bat_blocks.Add(bat); // Now store a reference to the BAT in the required place if (_header.BATCount >= 109) { // Needs to come from an XBAT BATBlock xbat = null; foreach (BATBlock x in _xbat_blocks) { if (x.HasFreeSectors) { xbat = x; break; } } if (xbat == null) { // Oh joy, we need a new XBAT too... xbat = CreateBAT(offset + 1, false); xbat.SetValueAt(0, offset); bat.SetValueAt(1, POIFSConstants.DIFAT_SECTOR_BLOCK); // Will go one place higher as XBAT Added in offset++; // Chain it if (_xbat_blocks.Count == 0) { _header.XBATStart = offset; } else { _xbat_blocks[_xbat_blocks.Count - 1].SetValueAt( bigBlockSize.GetXBATEntriesPerBlock(), offset ); } _xbat_blocks.Add(xbat); _header.XBATCount = _xbat_blocks.Count; } // Allocate us in the XBAT for (int i = 0; i < bigBlockSize.GetXBATEntriesPerBlock(); i++) { if (xbat.GetValueAt(i) == POIFSConstants.UNUSED_BLOCK) { xbat.SetValueAt(i, offset); } } } else { // Store us in the header int[] newBATs = new int[_header.BATCount + 1]; Array.Copy(_header.BATArray, 0, newBATs, 0, newBATs.Length - 1); newBATs[newBATs.Length - 1] = offset; _header.BATArray = newBATs; } _header.BATCount = _bat_blocks.Count; // The current offset stores us, but the next one is free return offset + 1; } public override ChainLoopDetector GetChainLoopDetector() { return new ChainLoopDetector(_data.Size, this); } /** * For unit Testing only! Returns the underlying * properties table */ public NPropertyTable PropertyTable { get { return _property_table; } } /** * Returns the MiniStore, which performs a similar low * level function to this, except for the small blocks. */ public NPOIFSMiniStore GetMiniStore() { return _mini_store; } /** * add a new POIFSDocument to the FileSytem * * @param document the POIFSDocument being Added */ public void AddDocument(NPOIFSDocument document) { _property_table.AddProperty(document.DocumentProperty); } /** * add a new DirectoryProperty to the FileSystem * * @param directory the DirectoryProperty being Added */ public void AddDirectory(DirectoryProperty directory) { _property_table.AddProperty(directory); } /** * Create a new document to be Added to the root directory * * @param stream the InputStream from which the document's data * will be obtained * @param name the name of the new POIFSDocument * * @return the new DocumentEntry * * @exception IOException on error creating the new POIFSDocument */ public DocumentEntry CreateDocument(Stream stream, String name) { return Root.CreateDocument(name, stream); } /** * create a new DocumentEntry in the root entry; the data will be * provided later * * @param name the name of the new DocumentEntry * @param size the size of the new DocumentEntry * @param Writer the Writer of the new DocumentEntry * * @return the new DocumentEntry * * @exception IOException */ public DocumentEntry CreateDocument(String name, int size, POIFSWriterListener writer) { return Root.CreateDocument(name, size, writer); } /** * create a new DirectoryEntry in the root directory * * @param name the name of the new DirectoryEntry * * @return the new DirectoryEntry * * @exception IOException on name duplication */ public DirectoryEntry CreateDirectory(String name) { return Root.CreateDirectory(name); } /** * Write the filesystem out to the open file. Will thrown an * {@link ArgumentException} if opened from an * {@link InputStream}. * * @exception IOException thrown on errors writing to the stream */ public void WriteFilesystem() { if (_data is FileBackedDataSource) { // Good, correct type } else { throw new ArgumentException( "POIFS opened from an inputstream, so WriteFilesystem() may " + "not be called. Use WriteFilesystem(OutputStream) instead" ); } syncWithDataSource(); } /** * Write the filesystem out * * @param stream the OutputStream to which the filesystem will be * written * * @exception IOException thrown on errors writing to the stream */ public void WriteFilesystem(Stream stream) { // Have the datasource updated syncWithDataSource(); // Now copy the contents to the stream _data.CopyTo(stream); } /** * Has our in-memory objects write their state * to their backing blocks */ private void syncWithDataSource() { // HeaderBlock HeaderBlockWriter hbw = new HeaderBlockWriter(_header); hbw.WriteBlock(GetBlockAt(-1)); // BATs foreach (BATBlock bat in _bat_blocks) { ByteBuffer block = GetBlockAt(bat.OurBlockIndex); //byte[] block = GetBlockAt(bat.OurBlockIndex); BlockAllocationTableWriter.WriteBlock(bat, block); } // SBATs _mini_store.SyncWithDataSource(); // Properties _property_table.Write(new NPOIFSStream(this, _header.PropertyStart) ); } /** * Closes the FileSystem, freeing any underlying files, streams * and buffers. After this, you will be unable to read or * write from the FileSystem. */ public void close() { _data.Close(); } /** * Get the root entry * * @return the root entry */ public DirectoryNode Root { get { if (_root == null) { _root = new DirectoryNode(_property_table.Root, this, null); } return _root; } } /** * open a document in the root entry's list of entries * * @param documentName the name of the document to be opened * * @return a newly opened DocumentInputStream * * @exception IOException if the document does not exist or the * name is that of a DirectoryEntry */ public DocumentInputStream CreateDocumentInputStream(string documentName) { return Root.CreateDocumentInputStream(documentName); } /** * remove an entry * * @param entry to be Removed */ public void Remove(EntryNode entry) { _property_table.RemoveProperty(entry.Property); } /* ********** START begin implementation of POIFSViewable ********** */ /** * Get an array of objects, some of which may implement * POIFSViewable * * @return an array of Object; may not be null, but may be empty */ protected Object[] GetViewableArray() { if (PreferArray) { Array ar = ((POIFSViewable)Root).ViewableArray; Object[] rval = new Object[ar.Length]; for (int i = 0; i < ar.Length; i++) rval[i] = ar.GetValue(i); return rval; } return new Object[0]; } /** * Get an Iterator of objects, some of which may implement * POIFSViewable * * @return an Iterator; may not be null, but may have an empty * back end store */ protected IEnumerator GetViewableIterator() { if (!PreferArray) { return ((POIFSViewable)Root).ViewableIterator; } return null; } /** * Provides a short description of the object, to be used when a * POIFSViewable object has not provided its contents. * * @return short description */ protected String GetShortDescription() { return "POIFS FileSystem"; } /* ********** END begin implementation of POIFSViewable ********** */ /** * @return The Big Block size, normally 512 bytes, sometimes 4096 bytes */ public int GetBigBlockSize() { return bigBlockSize.GetBigBlockSize(); } /** * @return The Big Block size, normally 512 bytes, sometimes 4096 bytes */ public POIFSBigBlockSize GetBigBlockSizeDetails() { return bigBlockSize; } public override int GetBlockStoreBlockSize() { return GetBigBlockSize(); } #region POIFSViewable Members public bool PreferArray { get { return ((POIFSViewable)Root).PreferArray; } } public string ShortDescription { get { return GetShortDescription(); } } public Array ViewableArray { get { return GetViewableArray(); } } public IEnumerator ViewableIterator { get { return GetViewableIterator(); } } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using Nini.Config; using log4net; using System; using System.Reflection; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Serialization; using System.Collections.Generic; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Framework; using OpenSim.Framework.ServiceAuth; using OpenSim.Framework.Servers.HttpServer; using OpenMetaverse; namespace OpenSim.Server.Handlers.AgentPreferences { public class AgentPreferencesServerPostHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IAgentPreferencesService m_AgentPreferencesService; public AgentPreferencesServerPostHandler(IAgentPreferencesService service, IServiceAuth auth) : base("POST", "/agentprefs", auth) { m_AgentPreferencesService = service; } protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { StreamReader sr = new StreamReader(requestData); string body = sr.ReadToEnd(); sr.Close(); body = body.Trim(); //m_log.DebugFormat("[XXX]: query String: {0}", body); try { Dictionary<string, object> request = ServerUtils.ParseQueryString(body); if (!request.ContainsKey("METHOD")) return FailureResult(); string method = request["METHOD"].ToString(); switch (method) { case "getagentprefs": return GetAgentPrefs(request); case "setagentprefs": return SetAgentPrefs(request); case "getagentlang": return GetAgentLang(request); } m_log.DebugFormat("[AGENT PREFERENCES HANDLER]: unknown method request: {0}", method); } catch (Exception e) { m_log.DebugFormat("[AGENT PREFERENCES HANDLER]: Exception {0}", e); } return FailureResult(); } byte[] GetAgentPrefs(Dictionary<string, object> request) { if (!request.ContainsKey("UserID")) return FailureResult(); UUID userID; if (!UUID.TryParse(request["UserID"].ToString(), out userID)) return FailureResult(); AgentPrefs prefs = m_AgentPreferencesService.GetAgentPreferences(userID); Dictionary<string, object> result = new Dictionary<string, object>(); result = prefs.ToKeyValuePairs(); string xmlString = ServerUtils.BuildXmlResponse(result); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] SetAgentPrefs(Dictionary<string, object> request) { if (!request.ContainsKey("PrincipalID") || !request.ContainsKey("AccessPrefs") || !request.ContainsKey("HoverHeight") || !request.ContainsKey("Language") || !request.ContainsKey("LanguageIsPublic") || !request.ContainsKey("PermEveryone") || !request.ContainsKey("PermGroup") || !request.ContainsKey("PermNextOwner")) { return FailureResult(); } UUID userID; if (!UUID.TryParse(request["PrincipalID"].ToString(), out userID)) return FailureResult(); AgentPrefs data = new AgentPrefs(userID); data.AccessPrefs = request["AccessPrefs"].ToString(); data.HoverHeight = double.Parse(request["HoverHeight"].ToString()); data.Language = request["Language"].ToString(); data.LanguageIsPublic = bool.Parse(request["LanguageIsPublic"].ToString()); data.PermEveryone = int.Parse(request["PermEveryone"].ToString()); data.PermGroup = int.Parse(request["PermGroup"].ToString()); data.PermNextOwner = int.Parse(request["PermNextOwner"].ToString()); return m_AgentPreferencesService.StoreAgentPreferences(data) ? SuccessResult() : FailureResult(); } byte[] GetAgentLang(Dictionary<string, object> request) { if (!request.ContainsKey("UserID")) return FailureResult(); UUID userID; if (!UUID.TryParse(request["UserID"].ToString(), out userID)) return FailureResult(); string lang = "en-us"; AgentPrefs prefs = m_AgentPreferencesService.GetAgentPreferences(userID); if (prefs != null) { if (prefs.LanguageIsPublic) lang = prefs.Language; } Dictionary<string, object> result = new Dictionary<string, object>(); result["Language"] = lang; string xmlString = ServerUtils.BuildXmlResponse(result); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } private byte[] SuccessResult() { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "result", ""); result.AppendChild(doc.CreateTextNode("Success")); rootElement.AppendChild(result); return Util.DocToBytes(doc); } private byte[] FailureResult() { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "result", ""); result.AppendChild(doc.CreateTextNode("Failure")); rootElement.AppendChild(result); return Util.DocToBytes(doc); } } }
using System; using System.Collections.Generic; using System.Text; using System.Web.UI; using System.Web; using System.IO; using System.Windows.Forms; using System.Threading; namespace DP.Common { public static class LogHelper { /// <summary> /// /// </summary> /// <returns></returns> private static string DefaultLogName { get { return "Log_DP_DATA"; } } /// <summary> /// Writes the log. /// </summary> /// <param name="message">The message.</param> /// <returns></returns> public static bool WriteLog(string message) { string _message = String.Format("DateTime:{0}\nMessage:{1}\n\r", DateTime.Now, message); string logName = GetLogName(); if (String.IsNullOrEmpty(logName)) { return false; } return WriteFile(logName, _message); } public static bool WriteLog(string LogNamePre, string message) { string _message = String.Format("DateTime:{0}\nMessage:{1}\n\r", DateTime.Now, message); string logName = GetLogName(LogNamePre); if (String.IsNullOrEmpty(logName)) { return false; } return WriteFile(logName, _message); } public static void WriteLogAsync(string message) { Tuple<string, string> info = new Tuple<string, string>(DefaultLogName, message); ThreadPool.QueueUserWorkItem(new WaitCallback(WriteLog), info); } public static void WriteLogAsync(string LogNamePre, string message) { Tuple<string, string> info = new Tuple<string, string>(LogNamePre, message); ThreadPool.QueueUserWorkItem(new WaitCallback(WriteLog), info); } private static void WriteLog(object info) { Tuple<string, string> logInfo = info as Tuple<string, string>; if (logInfo != null) { string _message = String.Format("DateTime:{0}\nMessage:{1}\n\r", DateTime.Now, logInfo.Item2); string logName = GetLogName(logInfo.Item1); if (String.IsNullOrEmpty(logName)) { return; } WriteFile(logName, _message); } } /// <summary> /// Gets the name of the log. /// </summary> /// <returns></returns> public static string GetLogName(string logNamePre) { string fileFullName = string.Empty; try { string path = ""; if (HttpContext.Current == null) { path = System.Threading.Thread.GetDomain().BaseDirectory.ToString().TrimEnd('\\') + "\\Log\\" + logNamePre; } else { path = HttpContext.Current.Request.MapPath("~/Log/" + logNamePre).TrimEnd('/').TrimEnd('\\'); } if (!CreateDirectory(path)) { return string.Empty; } DateTime datetime = DateTime.Now; string fileName = logNamePre + "_" + datetime.ToString("yyyyMMdd") + ".log"; fileFullName = path + "\\" + fileName; if (!CreateFile(fileFullName)) { return string.Empty; } } catch { fileFullName = string.Empty; } return fileFullName; } public static string GetLogName() { return GetLogName(DefaultLogName); } /// <summary> /// Writes the file. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="message">The message.</param> /// <returns></returns> public static bool WriteFile(string fileName, string message) { bool rel = false; try { File.AppendAllText(fileName, message, Encoding.UTF8); rel = true; } catch { rel = false; } return rel; } /// <summary> /// Creates the directory. /// </summary> /// <param name="path">The path.</param> /// <returns></returns> public static bool CreateDirectory(string path) { bool rel = false; try { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } rel = true; } catch { rel = false; } return rel; } /// <summary> /// Creates the file. /// </summary> /// <param name="filename">The filename.</param> /// <returns></returns> public static bool CreateFile(string filename) { bool rel = false; try { if (!File.Exists(filename)) { StreamWriter sw = File.CreateText(filename); sw.Close(); } rel = true; } catch { rel = false; } return rel; } public static void Test(string filename, string message) { log4net.ILog log = log4net.LogManager.GetLogger(filename); log.Debug(message); log.Info(message); log.Warn(message); log.Error(message); log.Fatal(message); } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the AprFactorRiesgoEstiloVida class. /// </summary> [Serializable] public partial class AprFactorRiesgoEstiloVidaCollection : ActiveList<AprFactorRiesgoEstiloVida, AprFactorRiesgoEstiloVidaCollection> { public AprFactorRiesgoEstiloVidaCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>AprFactorRiesgoEstiloVidaCollection</returns> public AprFactorRiesgoEstiloVidaCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { AprFactorRiesgoEstiloVida o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the APR_FactorRiesgoEstiloVida table. /// </summary> [Serializable] public partial class AprFactorRiesgoEstiloVida : ActiveRecord<AprFactorRiesgoEstiloVida>, IActiveRecord { #region .ctors and Default Settings public AprFactorRiesgoEstiloVida() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public AprFactorRiesgoEstiloVida(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public AprFactorRiesgoEstiloVida(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public AprFactorRiesgoEstiloVida(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("APR_FactorRiesgoEstiloVida", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdFactorRiesgoEstiloVida = new TableSchema.TableColumn(schema); colvarIdFactorRiesgoEstiloVida.ColumnName = "idFactorRiesgoEstiloVida"; colvarIdFactorRiesgoEstiloVida.DataType = DbType.Int32; colvarIdFactorRiesgoEstiloVida.MaxLength = 0; colvarIdFactorRiesgoEstiloVida.AutoIncrement = true; colvarIdFactorRiesgoEstiloVida.IsNullable = false; colvarIdFactorRiesgoEstiloVida.IsPrimaryKey = true; colvarIdFactorRiesgoEstiloVida.IsForeignKey = false; colvarIdFactorRiesgoEstiloVida.IsReadOnly = false; colvarIdFactorRiesgoEstiloVida.DefaultSetting = @""; colvarIdFactorRiesgoEstiloVida.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdFactorRiesgoEstiloVida); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.AnsiString; colvarNombre.MaxLength = 50; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = false; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; colvarNombre.DefaultSetting = @""; colvarNombre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombre); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("APR_FactorRiesgoEstiloVida",schema); } } #endregion #region Props [XmlAttribute("IdFactorRiesgoEstiloVida")] [Bindable(true)] public int IdFactorRiesgoEstiloVida { get { return GetColumnValue<int>(Columns.IdFactorRiesgoEstiloVida); } set { SetColumnValue(Columns.IdFactorRiesgoEstiloVida, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } private DalSic.AprEstiloVidaCollection colAprEstiloVidaRecords; public DalSic.AprEstiloVidaCollection AprEstiloVidaRecords { get { if(colAprEstiloVidaRecords == null) { colAprEstiloVidaRecords = new DalSic.AprEstiloVidaCollection().Where(AprEstiloVida.Columns.IdFactorRiesgoEstiloVida, IdFactorRiesgoEstiloVida).Load(); colAprEstiloVidaRecords.ListChanged += new ListChangedEventHandler(colAprEstiloVidaRecords_ListChanged); } return colAprEstiloVidaRecords; } set { colAprEstiloVidaRecords = value; colAprEstiloVidaRecords.ListChanged += new ListChangedEventHandler(colAprEstiloVidaRecords_ListChanged); } } void colAprEstiloVidaRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colAprEstiloVidaRecords[e.NewIndex].IdFactorRiesgoEstiloVida = IdFactorRiesgoEstiloVida; } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varNombre) { AprFactorRiesgoEstiloVida item = new AprFactorRiesgoEstiloVida(); item.Nombre = varNombre; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdFactorRiesgoEstiloVida,string varNombre) { AprFactorRiesgoEstiloVida item = new AprFactorRiesgoEstiloVida(); item.IdFactorRiesgoEstiloVida = varIdFactorRiesgoEstiloVida; item.Nombre = varNombre; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdFactorRiesgoEstiloVidaColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[1]; } } #endregion #region Columns Struct public struct Columns { public static string IdFactorRiesgoEstiloVida = @"idFactorRiesgoEstiloVida"; public static string Nombre = @"nombre"; } #endregion #region Update PK Collections public void SetPKValues() { if (colAprEstiloVidaRecords != null) { foreach (DalSic.AprEstiloVida item in colAprEstiloVidaRecords) { if (item.IdFactorRiesgoEstiloVida != IdFactorRiesgoEstiloVida) { item.IdFactorRiesgoEstiloVida = IdFactorRiesgoEstiloVida; } } } } #endregion #region Deep Save public void DeepSave() { Save(); if (colAprEstiloVidaRecords != null) { colAprEstiloVidaRecords.SaveAll(); } } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using NUnit.Framework; using OpenSim.Framework; using System; using System.Data; using System.Data.Common; using System.IO; namespace OpenSim.Data.Tests { /// <summary>This is a base class for testing any Data service for any DBMS. /// Requires NUnit 2.5 or better (to support the generics). /// </summary> /// <remarks> /// FIXME: Should extend OpenSimTestCase but compile on mono 2.4.3 currently fails with /// AssetTests`2 : System.MemberAccessException : Cannot create an instance of OpenSim.Data.Tests.AssetTests`2[TConn,TAssetData] because Type.ContainsGenericParameters is true. /// and similar on EstateTests, InventoryTests and RegionTests. /// Runs fine with mono 2.10.8.1, so easiest thing is to wait until min Mono version uplifts. /// </remarks> /// <typeparam name="TConn"></typeparam> /// <typeparam name="TService"></typeparam> public class BasicDataServiceTest<TConn, TService> where TConn : DbConnection, new() where TService : class, new() { protected string m_connStr; private TService m_service; private string m_file; // TODO: Is this in the right place here? // Later: apparently it's not, but does it matter here? // protected static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected ILog m_log; // doesn't matter here that it's not static, init to correct type in instance .ctor public BasicDataServiceTest() : this("") { } public BasicDataServiceTest(string conn) { m_connStr = !String.IsNullOrEmpty(conn) ? conn : DefaultTestConns.Get(typeof(TConn)); m_log = LogManager.GetLogger(this.GetType()); OpenSim.Tests.Common.TestLogging.LogToConsole(); // TODO: Is that right? } /// <summary> /// To be overridden in derived classes. Do whatever init with the m_service, like setting the conn string to it. /// You'd probably want to to cast the 'service' to a more specific type and store it in a member var. /// This framework takes care of disposing it, if it's disposable. /// </summary> /// <param name="service">The service being tested</param> protected virtual void InitService(object service) { } [TestFixtureSetUp] public void Init() { // Sorry, some SQLite-specific stuff goes here (not a big deal, as its just some file ops) if (typeof(TConn).Name.StartsWith("Sqlite")) { // SQLite doesn't work on power or z linux if (Directory.Exists("/proc/ppc64") || Directory.Exists("/proc/dasd")) Assert.Ignore(); if (Util.IsWindows()) Util.LoadArchSpecificWindowsDll("sqlite3.dll"); // for SQLite, if no explicit conn string is specified, use a temp file if (String.IsNullOrEmpty(m_connStr)) { m_file = Path.GetTempFileName() + ".db"; m_connStr = "URI=file:" + m_file + ",version=3"; } } if (String.IsNullOrEmpty(m_connStr)) { string msg = String.Format("Connection string for {0} is not defined, ignoring tests", typeof(TConn).Name); m_log.Warn(msg); Assert.Ignore(msg); } // Try the connection, ignore tests if Open() fails using (TConn conn = new TConn()) { conn.ConnectionString = m_connStr; try { conn.Open(); conn.Close(); } catch { string msg = String.Format("{0} is unable to connect to the database, ignoring tests", typeof(TConn).Name); m_log.Warn(msg); Assert.Ignore(msg); } } // If we manage to connect to the database with the user // and password above it is our test database, and run // these tests. If anything goes wrong, ignore these // tests. try { m_service = new TService(); InitService(m_service); } catch (Exception e) { m_log.Error(e.ToString()); Assert.Ignore(); } } [TestFixtureTearDown] public void Cleanup() { if (m_service != null) { if (m_service is IDisposable) ((IDisposable)m_service).Dispose(); m_service = null; } if (!String.IsNullOrEmpty(m_file) && File.Exists(m_file)) File.Delete(m_file); } protected virtual DbConnection Connect() { DbConnection cnn = new TConn(); cnn.ConnectionString = m_connStr; cnn.Open(); return cnn; } protected virtual void ExecuteSql(string sql) { using (DbConnection dbcon = Connect()) { using (DbCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = sql; cmd.ExecuteNonQuery(); } } } protected delegate bool ProcessRow(IDataReader reader); protected virtual int ExecQuery(string sql, bool bSingleRow, ProcessRow action) { int nRecs = 0; using (DbConnection dbcon = Connect()) { using (DbCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = sql; CommandBehavior cb = bSingleRow ? CommandBehavior.SingleRow : CommandBehavior.Default; using (DbDataReader rdr = cmd.ExecuteReader(cb)) { while (rdr.Read()) { nRecs++; if (!action(rdr)) break; } } } } return nRecs; } /// <summary>Drop tables (listed as parameters). There is no "DROP IF EXISTS" syntax common for all /// databases, so we just DROP and ignore an exception. /// </summary> /// <param name="tables"></param> protected virtual void DropTables(params string[] tables) { foreach (string tbl in tables) { try { ExecuteSql("DROP TABLE " + tbl + ";"); } catch { } } } /// <summary>Clear tables listed as parameters (without dropping them). /// </summary> /// <param name="tables"></param> protected virtual void ResetMigrations(params string[] stores) { string lst = ""; foreach (string store in stores) { string s = "'" + store + "'"; if (lst == "") lst = s; else lst += ", " + s; } string sCond = stores.Length > 1 ? ("in (" + lst + ")") : ("=" + lst); try { ExecuteSql("DELETE FROM migrations where name " + sCond); } catch { } } /// <summary>Clear tables listed as parameters (without dropping them). /// </summary> /// <param name="tables"></param> protected virtual void ClearTables(params string[] tables) { foreach (string tbl in tables) { try { ExecuteSql("DELETE FROM " + tbl + ";"); } catch { } } } } }
// 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.Diagnostics.Contracts; using System.IO; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Net.Http { public abstract class HttpContent : IDisposable { private HttpContentHeaders _headers; private MemoryStream _bufferedContent; private bool _disposed; private Stream _contentReadStream; private bool _canCalculateLength; internal const long MaxBufferSize = Int32.MaxValue; internal static readonly Encoding DefaultStringEncoding = Encoding.UTF8; private const int UTF8CodePage = 65001; private const int UTF8PreambleLength = 3; private const byte UTF8PreambleByte0 = 0xEF; private const byte UTF8PreambleByte1 = 0xBB; private const byte UTF8PreambleByte2 = 0xBF; private const int UTF8PreambleFirst2Bytes = 0xEFBB; #if !NETNative // UTF32 not supported on Phone private const int UTF32CodePage = 12000; private const int UTF32PreambleLength = 4; private const byte UTF32PreambleByte0 = 0xFF; private const byte UTF32PreambleByte1 = 0xFE; private const byte UTF32PreambleByte2 = 0x00; private const byte UTF32PreambleByte3 = 0x00; #endif private const int UTF32OrUnicodePreambleFirst2Bytes = 0xFFFE; private const int UnicodeCodePage = 1200; private const int UnicodePreambleLength = 2; private const byte UnicodePreambleByte0 = 0xFF; private const byte UnicodePreambleByte1 = 0xFE; private const int BigEndianUnicodeCodePage = 1201; private const int BigEndianUnicodePreambleLength = 2; private const byte BigEndianUnicodePreambleByte0 = 0xFE; private const byte BigEndianUnicodePreambleByte1 = 0xFF; private const int BigEndianUnicodePreambleFirst2Bytes = 0xFEFF; #if DEBUG static HttpContent() { // Ensure the encoding constants used in this class match the actual data from the Encoding class AssertEncodingConstants(Encoding.UTF8, UTF8CodePage, UTF8PreambleLength, UTF8PreambleFirst2Bytes, UTF8PreambleByte0, UTF8PreambleByte1, UTF8PreambleByte2); #if !NETNative // UTF32 not supported on Phone AssertEncodingConstants(Encoding.UTF32, UTF32CodePage, UTF32PreambleLength, UTF32OrUnicodePreambleFirst2Bytes, UTF32PreambleByte0, UTF32PreambleByte1, UTF32PreambleByte2, UTF32PreambleByte3); #endif AssertEncodingConstants(Encoding.Unicode, UnicodeCodePage, UnicodePreambleLength, UTF32OrUnicodePreambleFirst2Bytes, UnicodePreambleByte0, UnicodePreambleByte1); AssertEncodingConstants(Encoding.BigEndianUnicode, BigEndianUnicodeCodePage, BigEndianUnicodePreambleLength, BigEndianUnicodePreambleFirst2Bytes, BigEndianUnicodePreambleByte0, BigEndianUnicodePreambleByte1); } private static void AssertEncodingConstants(Encoding encoding, int codePage, int preambleLength, int first2Bytes, params byte[] preamble) { Debug.Assert(encoding != null); Debug.Assert(preamble != null); Debug.Assert(codePage == encoding.CodePage, "Encoding code page mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.CodePage): {1}", codePage, encoding.CodePage); byte[] actualPreamble = encoding.GetPreamble(); Debug.Assert(preambleLength == actualPreamble.Length, "Encoding preamble length mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.GetPreamble().Length): {1}", preambleLength, actualPreamble.Length); Debug.Assert(actualPreamble.Length >= 2); int actualFirst2Bytes = actualPreamble[0] << 8 | actualPreamble[1]; Debug.Assert(first2Bytes == actualFirst2Bytes, "Encoding preamble first 2 bytes mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual: {1}", first2Bytes, actualFirst2Bytes); Debug.Assert(preamble.Length == actualPreamble.Length, "Encoding preamble mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.GetPreamble()): {1}", BitConverter.ToString(preamble), BitConverter.ToString(actualPreamble)); for (int i = 0; i < preamble.Length; i++) { Debug.Assert(preamble[i] == actualPreamble[i], "Encoding preamble mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.GetPreamble()): {1}", BitConverter.ToString(preamble), BitConverter.ToString(actualPreamble)); } } #endif public HttpContentHeaders Headers { get { if (_headers == null) { _headers = new HttpContentHeaders(GetComputedOrBufferLength); } return _headers; } } private bool IsBuffered { get { return _bufferedContent != null; } } #if NETNative internal void SetBuffer(byte[] buffer, int offset, int count) { _bufferedContent = new MemoryStream(buffer, offset, count, false, true); } internal bool TryGetBuffer(out ArraySegment<byte> buffer) { if (_bufferedContent == null) { return false; } return _bufferedContent.TryGetBuffer(out buffer); } #endif protected HttpContent() { // Log to get an ID for the current content. This ID is used when the content gets associated to a message. if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Http, this, ".ctor", null); // We start with the assumption that we can calculate the content length. _canCalculateLength = true; if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Http, this, ".ctor", null); } public Task<string> ReadAsStringAsync() { CheckDisposed(); var tcs = new TaskCompletionSource<string>(this); LoadIntoBufferAsync().ContinueWithStandard(tcs, (task, state) => { var innerTcs = (TaskCompletionSource<string>)state; var innerThis = (HttpContent)innerTcs.Task.AsyncState; if (HttpUtilities.HandleFaultsAndCancelation(task, innerTcs)) { return; } if (innerThis._bufferedContent.Length == 0) { innerTcs.TrySetResult(string.Empty); return; } // We don't validate the Content-Encoding header: If the content was encoded, it's the caller's // responsibility to make sure to only call ReadAsString() on already decoded content. E.g. if the // Content-Encoding is 'gzip' the user should set HttpClientHandler.AutomaticDecompression to get a // decoded response stream. Encoding encoding = null; int bomLength = -1; byte[] data = innerThis.GetDataBuffer(innerThis._bufferedContent); int dataLength = (int)innerThis._bufferedContent.Length; // Data is the raw buffer, it may not be full. // If we do have encoding information in the 'Content-Type' header, use that information to convert // the content to a string. if ((innerThis.Headers.ContentType != null) && (innerThis.Headers.ContentType.CharSet != null)) { try { encoding = Encoding.GetEncoding(innerThis.Headers.ContentType.CharSet); // Byte-order-mark (BOM) characters may be present even if a charset was specified. bomLength = GetPreambleLength(data, dataLength, encoding); } catch (ArgumentException e) { innerTcs.TrySetException(new InvalidOperationException(SR.net_http_content_invalid_charset, e)); return; } } // If no content encoding is listed in the ContentType HTTP header, or no Content-Type header present, // then check for a BOM in the data to figure out the encoding. if (encoding == null) { if (!TryDetectEncoding(data, dataLength, out encoding, out bomLength)) { // Use the default encoding (UTF8) if we couldn't detect one. encoding = DefaultStringEncoding; // We already checked to see if the data had a UTF8 BOM in TryDetectEncoding // and DefaultStringEncoding is UTF8, so the bomLength is 0. bomLength = 0; } } try { // Drop the BOM when decoding the data. string result = encoding.GetString(data, bomLength, dataLength - bomLength); innerTcs.TrySetResult(result); } catch (Exception ex) { innerTcs.TrySetException(ex); } }); return tcs.Task; } public Task<byte[]> ReadAsByteArrayAsync() { CheckDisposed(); var tcs = new TaskCompletionSource<byte[]>(this); LoadIntoBufferAsync().ContinueWithStandard(tcs, (task, state) => { var innerTcs = (TaskCompletionSource<byte[]>)state; var innerThis = (HttpContent)innerTcs.Task.AsyncState; if (!HttpUtilities.HandleFaultsAndCancelation(task, innerTcs)) { innerTcs.TrySetResult(innerThis._bufferedContent.ToArray()); } }); return tcs.Task; } public Task<Stream> ReadAsStreamAsync() { CheckDisposed(); TaskCompletionSource<Stream> tcs = new TaskCompletionSource<Stream>(this); if (_contentReadStream == null && IsBuffered) { byte[] data = this.GetDataBuffer(_bufferedContent); // We can cast bufferedContent.Length to 'int' since the length will always be in the 'int' range // The .NET Framework doesn't support array lengths > int.MaxValue. Debug.Assert(_bufferedContent.Length <= (long)int.MaxValue); _contentReadStream = new MemoryStream(data, 0, (int)_bufferedContent.Length, false); } if (_contentReadStream != null) { tcs.TrySetResult(_contentReadStream); return tcs.Task; } CreateContentReadStreamAsync().ContinueWithStandard(tcs, (task, state) => { var innerTcs = (TaskCompletionSource<Stream>)state; var innerThis = (HttpContent)innerTcs.Task.AsyncState; if (!HttpUtilities.HandleFaultsAndCancelation(task, innerTcs)) { innerThis._contentReadStream = task.Result; innerTcs.TrySetResult(innerThis._contentReadStream); } }); return tcs.Task; } protected abstract Task SerializeToStreamAsync(Stream stream, TransportContext context); public Task CopyToAsync(Stream stream, TransportContext context) { CheckDisposed(); if (stream == null) { throw new ArgumentNullException("stream"); } TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(); try { Task task = null; if (IsBuffered) { byte[] data = this.GetDataBuffer(_bufferedContent); task = stream.WriteAsync(data, 0, (int)_bufferedContent.Length); } else { task = SerializeToStreamAsync(stream, context); CheckTaskNotNull(task); } // If the copy operation fails, wrap the exception in an HttpRequestException() if appropriate. task.ContinueWithStandard(tcs, (copyTask, state) => { var innerTcs = (TaskCompletionSource<object>)state; if (copyTask.IsFaulted) { innerTcs.TrySetException(GetStreamCopyException(copyTask.Exception.GetBaseException())); } else if (copyTask.IsCanceled) { innerTcs.TrySetCanceled(); } else { innerTcs.TrySetResult(null); } }); } catch (IOException e) { tcs.TrySetException(GetStreamCopyException(e)); } catch (ObjectDisposedException e) { tcs.TrySetException(GetStreamCopyException(e)); } return tcs.Task; } public Task CopyToAsync(Stream stream) { return CopyToAsync(stream, null); } public Task LoadIntoBufferAsync() { return LoadIntoBufferAsync(MaxBufferSize); } // No "CancellationToken" parameter needed since canceling the CTS will close the connection, resulting // in an exception being thrown while we're buffering. // If buffering is used without a connection, it is supposed to be fast, thus no cancellation required. public Task LoadIntoBufferAsync(long maxBufferSize) { CheckDisposed(); if (maxBufferSize > HttpContent.MaxBufferSize) { // This should only be hit when called directly; HttpClient/HttpClientHandler // will not exceed this limit. throw new ArgumentOutOfRangeException("maxBufferSize", maxBufferSize, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_limit, HttpContent.MaxBufferSize)); } if (IsBuffered) { // If we already buffered the content, just return a completed task. return CreateCompletedTask(); } TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(); Exception error = null; MemoryStream tempBuffer = CreateMemoryStream(maxBufferSize, out error); if (tempBuffer == null) { // We don't throw in LoadIntoBufferAsync(): set the task as faulted and return the task. Debug.Assert(error != null); tcs.TrySetException(error); } else { try { Task task = SerializeToStreamAsync(tempBuffer, null); CheckTaskNotNull(task); task.ContinueWithStandard(copyTask => { try { if (copyTask.IsFaulted) { tempBuffer.Dispose(); // Cleanup partially filled stream. tcs.TrySetException(GetStreamCopyException(copyTask.Exception.GetBaseException())); return; } if (copyTask.IsCanceled) { tempBuffer.Dispose(); // Cleanup partially filled stream. tcs.TrySetCanceled(); return; } tempBuffer.Seek(0, SeekOrigin.Begin); // Rewind after writing data. _bufferedContent = tempBuffer; tcs.TrySetResult(null); } catch (Exception e) { // Make sure we catch any exception, otherwise the task will catch it and throw in the finalizer. tcs.TrySetException(e); if (NetEventSource.Log.IsEnabled()) NetEventSource.Exception(NetEventSource.ComponentType.Http, this, "LoadIntoBufferAsync", e); } }); } catch (IOException e) { tcs.TrySetException(GetStreamCopyException(e)); } catch (ObjectDisposedException e) { tcs.TrySetException(GetStreamCopyException(e)); } } return tcs.Task; } protected virtual Task<Stream> CreateContentReadStreamAsync() { var tcs = new TaskCompletionSource<Stream>(this); // By default just buffer the content to a memory stream. Derived classes can override this behavior // if there is a better way to retrieve the content as stream (e.g. byte array/string use a more efficient // way, like wrapping a read-only MemoryStream around the bytes/string) LoadIntoBufferAsync().ContinueWithStandard(tcs, (task, state) => { var innerTcs = (TaskCompletionSource<Stream>)state; var innerThis = (HttpContent)innerTcs.Task.AsyncState; if (!HttpUtilities.HandleFaultsAndCancelation(task, innerTcs)) { innerTcs.TrySetResult(innerThis._bufferedContent); } }); return tcs.Task; } // Derived types return true if they're able to compute the length. It's OK if derived types return false to // indicate that they're not able to compute the length. The transport channel needs to decide what to do in // that case (send chunked, buffer first, etc.). protected internal abstract bool TryComputeLength(out long length); private long? GetComputedOrBufferLength() { CheckDisposed(); if (IsBuffered) { return _bufferedContent.Length; } // If we already tried to calculate the length, but the derived class returned 'false', then don't try // again; just return null. if (_canCalculateLength) { long length = 0; if (TryComputeLength(out length)) { return length; } // Set flag to make sure next time we don't try to compute the length, since we know that we're unable // to do so. _canCalculateLength = false; } return null; } private MemoryStream CreateMemoryStream(long maxBufferSize, out Exception error) { Contract.Ensures((Contract.Result<MemoryStream>() != null) || (Contract.ValueAtReturn<Exception>(out error) != null)); error = null; // If we have a Content-Length allocate the right amount of buffer up-front. Also check whether the // content length exceeds the max. buffer size. long? contentLength = Headers.ContentLength; if (contentLength != null) { Debug.Assert(contentLength >= 0); if (contentLength > maxBufferSize) { error = new HttpRequestException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_exceeded, maxBufferSize)); return null; } // We can safely cast contentLength to (int) since we just checked that it is <= maxBufferSize. return new LimitMemoryStream((int)maxBufferSize, (int)contentLength); } // We couldn't determine the length of the buffer. Create a memory stream with an empty buffer. return new LimitMemoryStream((int)maxBufferSize, 0); } private byte[] GetDataBuffer(MemoryStream stream) { // TODO: Use TryGetBuffer() instead of ToArray(). return stream.ToArray(); } #region IDisposable Members protected virtual void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; if (_contentReadStream != null) { _contentReadStream.Dispose(); } if (IsBuffered) { _bufferedContent.Dispose(); } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion #region Helpers private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(this.GetType().ToString()); } } private void CheckTaskNotNull(Task task) { if (task == null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.PrintError(NetEventSource.ComponentType.Http, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_log_content_no_task_returned_copytoasync, this.GetType().ToString())); throw new InvalidOperationException(SR.net_http_content_no_task_returned); } } private static Task CreateCompletedTask() { TaskCompletionSource<object> completed = new TaskCompletionSource<object>(); bool resultSet = completed.TrySetResult(null); Debug.Assert(resultSet, "Can't set Task as completed."); return completed.Task; } private static Exception GetStreamCopyException(Exception originalException) { // HttpContent derived types should throw HttpRequestExceptions if there is an error. However, since the stream // provided by CopyToAsync() can also throw, we wrap such exceptions in HttpRequestException. This way custom content // types don't have to worry about it. The goal is that users of HttpContent don't have to catch multiple // exceptions (depending on the underlying transport), but just HttpRequestExceptions // Custom stream should throw either IOException or HttpRequestException. // We don't want to wrap other exceptions thrown by Stream (e.g. InvalidOperationException), since we // don't want to hide such "usage error" exceptions in HttpRequestException. // ObjectDisposedException is also wrapped, since aborting HWR after a request is complete will result in // the response stream being closed. Exception result = originalException; if ((result is IOException) || (result is ObjectDisposedException)) { result = new HttpRequestException(SR.net_http_content_stream_copy_error, result); } return result; } private static int GetPreambleLength(byte[] data, int dataLength, Encoding encoding) { Debug.Assert(data != null); Debug.Assert(dataLength <= data.Length); Debug.Assert(encoding != null); switch (encoding.CodePage) { case UTF8CodePage: return (dataLength >= UTF8PreambleLength && data[0] == UTF8PreambleByte0 && data[1] == UTF8PreambleByte1 && data[2] == UTF8PreambleByte2) ? UTF8PreambleLength : 0; #if !NETNative // UTF32 not supported on Phone case UTF32CodePage: return (dataLength >= UTF32PreambleLength && data[0] == UTF32PreambleByte0 && data[1] == UTF32PreambleByte1 && data[2] == UTF32PreambleByte2 && data[3] == UTF32PreambleByte3) ? UTF32PreambleLength : 0; #endif case UnicodeCodePage: return (dataLength >= UnicodePreambleLength && data[0] == UnicodePreambleByte0 && data[1] == UnicodePreambleByte1) ? UnicodePreambleLength : 0; case BigEndianUnicodeCodePage: return (dataLength >= BigEndianUnicodePreambleLength && data[0] == BigEndianUnicodePreambleByte0 && data[1] == BigEndianUnicodePreambleByte1) ? BigEndianUnicodePreambleLength : 0; default: byte[] preamble = encoding.GetPreamble(); return ByteArrayHasPrefix(data, dataLength, preamble) ? preamble.Length : 0; } } private static bool TryDetectEncoding(byte[] data, int dataLength, out Encoding encoding, out int preambleLength) { Debug.Assert(data != null); Debug.Assert(dataLength <= data.Length); if (dataLength >= 2) { int first2Bytes = data[0] << 8 | data[1]; switch (first2Bytes) { case UTF8PreambleFirst2Bytes: if (dataLength >= UTF8PreambleLength && data[2] == UTF8PreambleByte2) { encoding = Encoding.UTF8; preambleLength = UTF8PreambleLength; return true; } break; case UTF32OrUnicodePreambleFirst2Bytes: #if !NETNative // UTF32 not supported on Phone if (dataLength >= UTF32PreambleLength && data[2] == UTF32PreambleByte2 && data[3] == UTF32PreambleByte3) { encoding = Encoding.UTF32; preambleLength = UTF32PreambleLength; } else #endif { encoding = Encoding.Unicode; preambleLength = UnicodePreambleLength; } return true; case BigEndianUnicodePreambleFirst2Bytes: encoding = Encoding.BigEndianUnicode; preambleLength = BigEndianUnicodePreambleLength; return true; } } encoding = null; preambleLength = 0; return false; } private static bool ByteArrayHasPrefix(byte[] byteArray, int dataLength, byte[] prefix) { if (prefix == null || byteArray == null || prefix.Length > dataLength || prefix.Length == 0) return false; for (int i = 0; i < prefix.Length; i++) { if (prefix[i] != byteArray[i]) return false; } return true; } #endregion Helpers private class LimitMemoryStream : MemoryStream { private int _maxSize; public LimitMemoryStream(int maxSize, int capacity) : base(capacity) { _maxSize = maxSize; } public override void Write(byte[] buffer, int offset, int count) { CheckSize(count); base.Write(buffer, offset, count); } public override void WriteByte(byte value) { CheckSize(1); base.WriteByte(value); } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { CheckSize(count); return base.WriteAsync(buffer, offset, count, cancellationToken); } private void CheckSize(int countToAdd) { if (_maxSize - Length < countToAdd) { throw new HttpRequestException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_exceeded, _maxSize)); } } } } }
using System; using System.IO; namespace Platform.IO { /// <summary> /// A class that supports copying from one stream into another stream. /// </summary> public class StreamCopier : AbstractTask { public static readonly int DefaultBufferSize = 8192 * 8; #region Types public interface IStreamProvider { Stream GetSourceStream(); Stream GetDestinationStream(); long GetSourceLength(); long GetDestinationLength(); } public class StaticStreamProvider : IStreamProvider { private readonly Stream source; private readonly Stream destination; public StaticStreamProvider(Stream source, Stream destination) { this.source = source; this.destination = destination; } public virtual Stream GetSourceStream() { return source; } public virtual Stream GetDestinationStream() { return destination; } public virtual long GetSourceLength() { if (source.CanSeek) { return source.Length; } else { return Int64.MaxValue; } } public virtual long GetDestinationLength() { if (destination.CanSeek) { return destination.Length; } else { return Int64.MaxValue; } } } protected class BytesReadMeter : Meter { public BytesReadMeter(StreamCopier copier) : base(copier) { } public override object CurrentValue { get { lock (this.copier) { return this.copier.bytesRead; } } } public override object MaximumValue { get { lock (this.copier) { return this.copier.sourceLength; } } } } protected class BytesWrittenMeter : Meter { public BytesWrittenMeter(StreamCopier copier) : base(copier) { } public override object CurrentValue { get { lock (this.copier) { return this.copier.bytesWritten; } } } public override object MaximumValue { get { lock (this.copier) { return this.copier.streamProvider.GetSourceLength(); } } } } protected abstract class Meter : AbstractMeter { protected StreamCopier copier; protected Meter(StreamCopier copier) { this.copier = copier; } public override object Owner { get { return this.copier; } } public override object MinimumValue { get { return 0; } } public override string Units { get { return "bytes"; } } public virtual void RaiseValueChanged(long oldValue) { OnValueChanged(oldValue, this.CurrentValue); } public virtual void RaiseMajorChange() { OnValueChanged(this.CurrentValue, this.CurrentValue); OnMajorChange(); } } #endregion private readonly byte[] buffer; private long bytesRead = 0; private long bytesWritten = 0; private long sourceLength = -1; private Meter bytesReadMeter; private Meter bytesWrittenMeter; private readonly bool autoCloseSource; private readonly bool autoCloseDestination; private IStreamProvider streamProvider; protected IStreamProvider StreamProvider { get { return streamProvider; } set { streamProvider = value; } } public StreamCopier(Stream source, Stream destination) : this(source, destination, true, true) { } public StreamCopier(Stream source, Stream destination, int bufferSize) : this(source, destination, true, true, bufferSize) { } public StreamCopier(Stream source, Stream destination, bool autoCloseSource, bool autoCloseDestination) : this(source, destination, autoCloseSource, autoCloseDestination, -1) { } public StreamCopier(Stream source, Stream destination, bool autoCloseSource, bool autoCloseDestination, int bufferSize) : this(new StaticStreamProvider(source, destination), autoCloseSource, autoCloseDestination, bufferSize) { } public StreamCopier(IStreamProvider streamProvider, bool autoCloseSource, bool autoCloseDestination) : this(streamProvider, autoCloseSource, autoCloseDestination, -1) { } public StreamCopier(IStreamProvider streamProvider, bool autoCloseSource, bool autoCloseDestination, int bufferSize) { this.streamProvider = streamProvider; this.autoCloseSource = autoCloseSource; this.autoCloseDestination = autoCloseDestination; buffer = new byte[bufferSize > 0 ? bufferSize : DefaultBufferSize]; bytesReadMeter = new BytesReadMeter(this); bytesWrittenMeter = new BytesReadMeter(this); sourceLength = this.streamProvider.GetSourceLength(); } protected StreamCopier(bool autoCloseSource, bool autoCloseDestination, int bufferSize) { streamProvider = (IStreamProvider)this; this.autoCloseSource = autoCloseSource; this.autoCloseDestination = autoCloseDestination; buffer = new byte[bufferSize > 0 ? bufferSize : DefaultBufferSize]; } protected virtual void InitializePump() { bytesReadMeter = new BytesReadMeter(this); bytesWrittenMeter = new BytesReadMeter(this); sourceLength = streamProvider.GetSourceLength(); } public override IMeter Progress { get { return bytesWrittenMeter; } } public virtual IMeter WriteProgress { get { return bytesWrittenMeter; } } public virtual IMeter ReadProgress { get { return bytesReadMeter; } } public override void DoRun() { var finished = false; ProcessTaskStateRequest(); var source = this.streamProvider.GetSourceStream(); var destination = this.streamProvider.GetDestinationStream(); try { try { bytesReadMeter.RaiseValueChanged(0L); ProcessTaskStateRequest(); bytesWrittenMeter.RaiseValueChanged(0L); ProcessTaskStateRequest(); while (true) { var read = source.Read(buffer, 0, buffer.Length); if (read == 0) { if (sourceLength != bytesRead) { sourceLength = bytesRead; bytesReadMeter.RaiseMajorChange(); bytesWrittenMeter.RaiseMajorChange(); } break; } lock (this) { bytesRead += read; } if (bytesRead > sourceLength) { sourceLength = bytesRead; } bytesReadMeter.RaiseValueChanged(bytesRead - read); ProcessTaskStateRequest(); destination.Write(buffer, 0, read); lock (this) { bytesWritten += read; } bytesWrittenMeter.RaiseValueChanged(bytesWritten - read); ProcessTaskStateRequest(); } finished = true; } catch (StopRequestedException) { SetTaskState(TaskState.Stopped); } } finally { ActionUtils.IgnoreExceptions(destination.Flush); if (autoCloseSource) { ActionUtils.IgnoreExceptions(source.Close); } if (autoCloseDestination) { ActionUtils.IgnoreExceptions(destination.Close); } if (finished) { SetTaskState(TaskState.Finished); } else { SetTaskState(TaskState.Stopped); } } } public static void Copy(Stream inStream, Stream outStream) { new StreamCopier(inStream, outStream, true, true).Run(); } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Text; using Microsoft.MultiverseInterfaceStudio.FrameXml.Serialization; using System.Drawing; using System.Xml.Serialization; using System.Windows.Forms; namespace Microsoft.MultiverseInterfaceStudio.FrameXml.Controls { /// <summary> /// Represents the FontString control. /// </summary> #if AUTOSIZE [Designer(typeof(AutoSizeDesigner))] #endif [ToolboxBitmap(typeof(System.Windows.Forms.Label), "Label.bmp")] [ToolboxItemFilter("MultiverseInterfaceStudioFilter", ToolboxItemFilterType.Require)] public partial class FontString : GenericControl<FontStringType>, ILayerable { /// <summary> /// Initializes a new instance of the <see cref="FontString"/> class. /// </summary> public FontString() : base(CreateInnerControl()) { this.BackColor = Color.Transparent; this.LayerLevel = DRAWLAYER.ARTWORK; this.TypedSerializationObject.inherits = "GameFontNormalSmall"; #if AUTOSIZE // workarounding autosize this.InnerControl.Dock = System.Windows.Forms.DockStyle.None; this.InnerControl.SizeChanged += new EventHandler(InnerControl_SizeChanged); #endif this.text = this.name; this.DesignerDefaultValues["text"] = this.name; this.HasBorder = true; } /// <summary> /// Handles the SizeChanged event of the InnerControl control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void InnerControl_SizeChanged(object sender, EventArgs e) { this.Size = this.InnerControl.Size; } /// <summary> /// Called after the control has been added to another container. /// </summary> protected override void InitLayout() { base.InitLayout(); if (String.IsNullOrEmpty(this.text)) { this.text = this.name; this.DesignerDefaultValues["text"] = this.name; } ChangeJustify(); #if AUTOSIZE this.Size = this.InnerControl.Size; #endif } #if AUTOSIZE protected override void OnResize(EventArgs e) { base.OnResize(e); this.Size = this.InnerControl.Size; } #endif protected override bool DrawName { get { return String.IsNullOrEmpty(this.text); } } /// <summary> /// Creates the inner Label control and sets its visual properties /// </summary> /// <returns></returns> private static System.Windows.Forms.Control CreateInnerControl() { var innerControl = new System.Windows.Forms.Label(); innerControl.BackColor = Color.Transparent; innerControl.ForeColor = Color.Gold; #if AUTOSIZE innerControl.AutoSize = true; #endif innerControl.Location = new Point(); innerControl.Font = new System.Drawing.Font(innerControl.Font, FontStyle.Bold); return innerControl; } [Category("Appearance")] public string text { get { return TypedSerializationObject.text; } set { InnerControl.Text = value; TypedSerializationObject.text = value; } } protected override void OnUpdateControl() { base.OnUpdateControl(); // visual properties that should be reflected on the control this.text = TypedSerializationObject.text; } #region ILayerable Members [XmlIgnore] [Category("Layout")] public DRAWLAYER LayerLevel { get; set; } #endregion private static string[] inheritsList = new string[] { "MasterFont", "SystemFont", "GameFontNormal", "GameFontHighlight", "GameFontDisable", "GameFontGreen", "GameFontRed", "GameFontBlack", "GameFontWhite", "GameFontNormalSmall", "GameFontHighlightSmall", "GameFontDisableSmall", "GameFontDarkGraySmall", "GameFontGreenSmall", "GameFontRedSmall", "GameFontHighlightSmallOutline", "GameFontNormalLarge", "GameFontHighlightLarge", "GameFontDisableLarge", "GameFontGreenLarge", "GameFontRedLarge", "GameFontNormalHuge", "NumberFontNormal", "NumberFontNormalYellow", "NumberFontNormalSmall", "NumberFontNormalSmallGray", "NumberFontNormalLarge", "NumberFontNormalHuge", "ChatFontNormal", "ChatFontSmall", "QuestTitleFont", "QuestFont", "QuestFontNormalSmall", "QuestFontHighlight", "ItemTextFontNormal", "MailTextFontNormal", "SubSpellFont", "DialogButtonNormalText", "DialogButtonHighlightText", "ZoneTextFont", "SubZoneTextFont", "PVPInfoTextFont", "ErrorFont", "TextStatusBarText", "TextStatusBarTextSmall", "CombatLogFont", "GameTooltipText", "GameTooltipTextSmall", "GameTooltipHeaderText", "WorldMapTextFont", "InvoiceTextFontNormal", "InvoiceTextFontSmall", "CombatTextFont", }; public override List<string> InheritsList { get { List<string> list = base.InheritsList; list.AddRange(inheritsList); return list; } } public override void OnPropertyChanged(PropertyChangedEventArgs e) { base.OnPropertyChanged(e); switch (e.PropertyName) { case "justifyH": case "justifyV": ChangeJustify(); break; } } private void ChangeJustify() { Label label = InnerControl as Label; if (label == null) return; string justificationText = TypedSerializationObject.justifyV.ToString() + TypedSerializationObject.justifyH.ToString(); ContentAlignment alignment = (ContentAlignment)Enum.Parse(typeof(ContentAlignment), justificationText, true); label.TextAlign = alignment; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Reflection; namespace System.ServiceModel.Description { [DebuggerDisplay("Name={_name}, IsInitiating={_isInitiating}, IsTerminating={_isTerminating}")] public class OperationDescription { internal const string SessionOpenedAction = Channels.WebSocketTransportSettings.ConnectionOpenedAction; private XmlName _name; private bool _isInitiating; private bool _isTerminating; private bool _isSessionOpenNotificationEnabled; private ContractDescription _declaringContract; private FaultDescriptionCollection _faults; private MessageDescriptionCollection _messages; private KeyedByTypeCollection<IOperationBehavior> _behaviors; private Collection<Type> _knownTypes; private MethodInfo _beginMethod; private MethodInfo _endMethod; private MethodInfo _syncMethod; private MethodInfo _taskMethod; private bool _validateRpcWrapperName = true; private bool _hasNoDisposableParameters; public OperationDescription(string name, ContractDescription declaringContract) { if (name == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name"); } if (name.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("name", SR.SFxOperationDescriptionNameCannotBeEmpty)); } _name = new XmlName(name, true /*isEncoded*/); if (declaringContract == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("declaringContract"); } _declaringContract = declaringContract; _isInitiating = true; _isTerminating = false; _faults = new FaultDescriptionCollection(); _messages = new MessageDescriptionCollection(); _behaviors = new KeyedByTypeCollection<IOperationBehavior>(); _knownTypes = new Collection<Type>(); } internal OperationDescription(string name, ContractDescription declaringContract, bool validateRpcWrapperName) : this(name, declaringContract) { _validateRpcWrapperName = validateRpcWrapperName; } public KeyedCollection<Type, IOperationBehavior> OperationBehaviors { get { return this.Behaviors; } } [EditorBrowsable(EditorBrowsableState.Never)] public KeyedByTypeCollection<IOperationBehavior> Behaviors { get { return _behaviors; } } // Not serializable on purpose, metadata import/export cannot // produce it, only available when binding to runtime public MethodInfo TaskMethod { get { return _taskMethod; } set { _taskMethod = value; } } // Not serializable on purpose, metadata import/export cannot // produce it, only available when binding to runtime public MethodInfo SyncMethod { get { return _syncMethod; } set { _syncMethod = value; } } // Not serializable on purpose, metadata import/export cannot // produce it, only available when binding to runtime public MethodInfo BeginMethod { get { return _beginMethod; } set { _beginMethod = value; } } internal MethodInfo OperationMethod { get { if (this.SyncMethod == null) { return this.TaskMethod ?? this.BeginMethod; } else { return this.SyncMethod; } } } internal bool HasNoDisposableParameters { get { return _hasNoDisposableParameters; } set { _hasNoDisposableParameters = value; } } // Not serializable on purpose, metadata import/export cannot // produce it, only available when binding to runtime public MethodInfo EndMethod { get { return _endMethod; } set { _endMethod = value; } } public ContractDescription DeclaringContract { get { return _declaringContract; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("DeclaringContract"); } else { _declaringContract = value; } } } public FaultDescriptionCollection Faults { get { return _faults; } } public bool IsOneWay { get { return this.Messages.Count == 1; } } public bool IsInitiating { get { return _isInitiating; } set { _isInitiating = value; } } internal bool IsServerInitiated() { EnsureInvariants(); return Messages[0].Direction == MessageDirection.Output; } public bool IsTerminating { get { return _isTerminating; } set { _isTerminating = value; } } public Collection<Type> KnownTypes { get { return _knownTypes; } } // Messages[0] is the 'request' (first of MEP), and for non-oneway MEPs, Messages[1] is the 'response' (second of MEP) public MessageDescriptionCollection Messages { get { return _messages; } } internal XmlName XmlName { get { return _name; } } internal string CodeName { get { return _name.DecodedName; } } public string Name { get { return _name.EncodedName; } } internal bool IsValidateRpcWrapperName { get { return _validateRpcWrapperName; } } internal Type TaskTResult { get; set; } internal bool HasOutputParameters { get { // For non-oneway operations, Messages[1] is the 'response' return (this.Messages.Count > 1) && (this.Messages[1].Body.Parts.Count > 0); } } internal bool IsSessionOpenNotificationEnabled { get { return _isSessionOpenNotificationEnabled; } set { _isSessionOpenNotificationEnabled = value; } } internal void EnsureInvariants() { if (this.Messages.Count != 1 && this.Messages.Count != 2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new System.InvalidOperationException(SR.Format(SR.SFxOperationMustHaveOneOrTwoMessages, this.Name))); } } } }
using IfacesEnumsStructsClasses; using System; using System.Windows.Forms; namespace csExWB { //General delegates and event arguments #region WebBrowser public delegate void TitleChangeEventHandler(object sender, TitleChangeEventArgs e); public class TitleChangeEventArgs : System.EventArgs { public string title; public TitleChangeEventArgs() { } } public delegate void DocumentCompleteEventHandler(object sender, DocumentCompleteEventArgs e); public class DocumentCompleteEventArgs : System.EventArgs { public DocumentCompleteEventArgs() { } public void SetParameters(object Browser, string Url, bool IsTopLevel) { this.browser = Browser; this.url = Url; this.istoplevel = IsTopLevel; } public void Reset() { this.browser = null; this.url = string.Empty; this.istoplevel = false; } public object browser; public string url; public bool istoplevel; } public delegate void DocumentCompleteExEventHandler(object sender, DocumentCompleteExEventArgs e); public class DocumentCompleteExEventArgs : System.EventArgs { public DocumentCompleteExEventArgs() { } public void SetParameters(object Browser, string Url, bool IsTopLevel, string DocSource) { this.browser = Browser; this.url = Url; this.istoplevel = IsTopLevel; this.docsource = DocSource; } public void Reset() { this.browser = null; this.url = ""; this.istoplevel = false; this.docsource = ""; } public object browser; public string url; public bool istoplevel; public string docsource; } public delegate void StatusTextChangeEventHandler(object sender, StatusTextChangeEventArgs e); public class StatusTextChangeEventArgs : System.EventArgs { public StatusTextChangeEventArgs() { } public string text; } public delegate void ProgressChangeEventHandler(object sender, ProgressChangeEventArgs e); public class ProgressChangeEventArgs : System.EventArgs { public ProgressChangeEventArgs() { } public void SetParameters(int Progress, int ProgressMax) { this.progress = Progress; this.progressmax = ProgressMax; } public int progress; public int progressmax; } public delegate void CommandStateChangeEventHandler(object sender, CommandStateChangeEventArgs e); public class CommandStateChangeEventArgs : System.EventArgs { public CommandStateChangeEventArgs() { } public void SetParameters(int Command, bool Enable) { this.command = (CommandStateChangeConstants)Command; this.enable = Enable; } public CommandStateChangeConstants command; public bool enable; } public delegate void DownloadBeginEventHandler(object sender); public delegate void DownloadCompleteEventHandler(object sender); public delegate void PropertyChangeEventHandler(object sender, PropertyChangeEventArgs e); public class PropertyChangeEventArgs : System.EventArgs { public PropertyChangeEventArgs() { } public string szproperty; } public delegate void BeforeNavigate2EventHandler(object sender, BeforeNavigate2EventArgs e); public class BeforeNavigate2EventArgs : System.ComponentModel.CancelEventArgs { public BeforeNavigate2EventArgs() { } public void SetParameters(object Browser, string Url, object TargetFrameName, object PostData, object Headers, bool TopLevel) { this.browser = Browser; this.url = Url; if (TargetFrameName != null) this.targetframename = TargetFrameName.ToString(); else this.targetframename = string.Empty; this.postdata = PostData; if (Headers != null) this.headers = Headers.ToString(); else this.headers = string.Empty; this.Cancel = false; this.istoplevel = TopLevel; } public void Reset() { this.browser = null; this.url = string.Empty; this.targetframename = string.Empty; this.postdata = null; this.headers = string.Empty; this.Cancel = false; this.istoplevel = false; } public object browser; public string url; public string targetframename; public object postdata; public string headers; public bool istoplevel; } public delegate void NavigateComplete2EventHandler(object sender, NavigateComplete2EventArgs e); public class NavigateComplete2EventArgs : System.EventArgs { public NavigateComplete2EventArgs() { } public void SetParameters(object Browser, string Url) { this.browser = Browser; this.url = Url; } public void Reset() { this.browser = null; this.url = ""; } public object browser; public string url; } public delegate void NewWindow2EventHandler(object sender, NewWindow2EventArgs e); public class NewWindow2EventArgs : System.ComponentModel.CancelEventArgs { public NewWindow2EventArgs() { this.Cancel = false; } public void SetParameters() { this.Cancel = false; this.browser = null; } public object browser; } public delegate void NewWindow3EventHandler(object sender, NewWindow3EventArgs e); public class NewWindow3EventArgs : System.ComponentModel.CancelEventArgs { public NewWindow3EventArgs() { this.Cancel = false; } public void SetParameters(string UrlContext, string Url, NWMF Flags) { this.browser = null; this.urlcontext = UrlContext; this.url = Url; this.flags = Flags; this.Cancel = false; } public void Reset() { this.browser = null; this.urlcontext = ""; this.url = ""; this.Cancel = false; } public object browser; public string urlcontext; public string url; public NWMF flags; } public delegate void WindowSetResizableEventHandler(object sender, WindowSetResizableEventArgs e); public class WindowSetResizableEventArgs : System.EventArgs { public WindowSetResizableEventArgs() { } public bool resizable; } public delegate void WindowSetLeftEventHandler(object sender, WindowSetLeftEventArgs e); public class WindowSetLeftEventArgs : System.EventArgs { public WindowSetLeftEventArgs() { } public int left; } public delegate void WindowSetTopEventHandler(object sender, WindowSetTopEventArgs e); public class WindowSetTopEventArgs : System.EventArgs { public WindowSetTopEventArgs() { } public int top; } public delegate void WindowSetWidthEventHandler(object sender, WindowSetWidthEventArgs e); public class WindowSetWidthEventArgs : System.EventArgs { public WindowSetWidthEventArgs() { } public int width; } public delegate void WindowSetHeightEventHandler(object sender, WindowSetHeightEventArgs e); public class WindowSetHeightEventArgs : System.EventArgs { public WindowSetHeightEventArgs() { } public int height; } public delegate void WindowClosingEventHandler(object sender, WindowClosingEventArgs e); public class WindowClosingEventArgs : System.ComponentModel.CancelEventArgs { public WindowClosingEventArgs() { this.Cancel = false; } public void SetParameters(bool IsChildWindow) { this.Cancel = false; this.ischildwindow = IsChildWindow; } public bool ischildwindow; } public delegate void ClientToHostWindowEventHandler(object sender, ClientToHostWindowEventArgs e); public class ClientToHostWindowEventArgs : System.EventArgs { public ClientToHostWindowEventArgs() { } public void SetParameters(int CX, int CY) { this.cx = CX; this.cy = CY; this.handled = false; } public bool handled; public int cx; public int cy; } public delegate void SetSecureLockIconEventHandler(object sender, SetSecureLockIconEventArgs e); public class SetSecureLockIconEventArgs : System.EventArgs { public SetSecureLockIconEventArgs() { } public void SetParameters(int SecureLockIcon) { this.securelockicon = (SecureLockIconConstants)SecureLockIcon; } public SecureLockIconConstants securelockicon; } public delegate void FileDownloadEventHandler(object sender, FileDownloadEventArgs e); public class FileDownloadEventArgs : System.ComponentModel.CancelEventArgs { public FileDownloadEventArgs() { } public bool ActiveDocument = false; } public delegate void NavigateErrorEventHandler(object sender, NavigateErrorEventArgs e); public class NavigateErrorEventArgs : System.ComponentModel.CancelEventArgs { public NavigateErrorEventArgs() { } public void SetParameters(object Browser, string Url, string TargetFrame, int StatusCode) { this.browser = Browser; this.url = Url; this.targetframe = TargetFrame; this.statuscode = (WinInetErrors)StatusCode; this.Cancel = false; } public void Reset() { this.browser = null; this.url = string.Empty; this.targetframe = string.Empty; this.Cancel = false; } public object browser; public string url; public string targetframe; public WinInetErrors statuscode; } public delegate void PrintTemplateInstantiationEventHandler(object sender, PrintTemplateInstantiationEventArgs e); public class PrintTemplateInstantiationEventArgs : System.EventArgs { public PrintTemplateInstantiationEventArgs() { } public object browser; } public delegate void PrintTemplateTeardownEventHandler(object sender, PrintTemplateTeardownEventArgs e); public class PrintTemplateTeardownEventArgs : System.EventArgs { public PrintTemplateTeardownEventArgs() { } public object browser; } public delegate void UpdatePageStatusEventHandler(object sender, UpdatePageStatusEventArgs e); public class UpdatePageStatusEventArgs : System.EventArgs { public UpdatePageStatusEventArgs() { } public void SetParameters(object Browser, int Page, bool Done) { this.browser = Browser; this.page = Page; this.done = Done; } public void Reset() { this.browser = null; this.page = 0; this.done = false; } public object browser; public int page; public bool done; } public delegate void PrivacyImpactedStateChangeEventHandler(object sender, PrivacyImpactedStateChangeEventArgs e); public class PrivacyImpactedStateChangeEventArgs : System.EventArgs { public PrivacyImpactedStateChangeEventArgs() { } public bool impacted; } #endregion #region Webbrowser Extended public delegate void HTMLEditHostSnapRectEventHandler(object sender, HTMLEditHostSnapRectEventArgs e); public class HTMLEditHostSnapRectEventArgs : System.EventArgs { public HTMLEditHostSnapRectEventArgs() { } public void SetParameters(IHTMLElement _elem, tagRECT _rect, int _elemcorner) { Element = _elem; ElemRect = _rect; ElemCorner = (ELEMENT_CORNER)_elemcorner; } public IHTMLElement Element = null; public tagRECT ElemRect; public ELEMENT_CORNER ElemCorner = ELEMENT_CORNER.ELEMENT_CORNER_NONE; } public delegate void HTMLOMWindowServicesEventHandler(object sender, HTMLOMWindowServicesEventArgs e); public class HTMLOMWindowServicesEventArgs : System.EventArgs { public HTMLOMWindowServicesEventArgs() { } public void SetParameters(int _x, int _y) { this.X = _x; this.Y = _y; } public int X = 0; public int Y = 0; } public delegate void AllowFocusChangeEventHandler(object sender, AllowFocusChangeEventArgs e); public class AllowFocusChangeEventArgs : System.ComponentModel.CancelEventArgs { public AllowFocusChangeEventArgs() { } } public delegate void EvaluateNewWindowEventHandler(object sender, EvaluateNewWindowEventArgs e); public class EvaluateNewWindowEventArgs : System.ComponentModel.CancelEventArgs { public EvaluateNewWindowEventArgs() { } public void SetParameters(string Url, string Name, string UrlContext, string Features, bool Replace, int Flags, int UserActionTime) { this.url = Url; this.name = Name; this.urlcontext = UrlContext; this.features = Features; this.useractiontime = UserActionTime; this.replace = Replace; this.flags = (NWMF)Flags; this.Cancel = false; } public void Reset() { this.url = ""; this.name = ""; this.urlcontext = ""; this.features = ""; this.useractiontime = 0; this.replace = false; this.Cancel = false; } public string url; public string name; public string urlcontext; public string features; public bool replace; public NWMF flags; public int useractiontime; } public delegate void SecurityProblemEventHandler(object sender, SecurityProblemEventArgs e); public class SecurityProblemEventArgs : System.EventArgs { public SecurityProblemEventArgs() { } public void SetParameters(int Problem) { this.handled = false; this.problem = (WinInetErrors)Problem; this.retvalue = Hresults.S_FALSE; //1 } public WinInetErrors problem; public int retvalue; public bool handled; } public delegate void AuthenticateEventHandler(object sender, AuthenticateEventArgs e); public class AuthenticateEventArgs : System.EventArgs { public AuthenticateEventArgs() { } public void SetParameters() { this.handled = false; this.username = string.Empty; this.password = string.Empty; this.retvalue = 0; //Hresults.S_OK } public string username; public string password; public int retvalue; public bool handled; } public delegate void WBDragEnterEventHandler(object sender, WBDragEnterEventArgs e); public class WBDragEnterEventArgs : System.EventArgs { public WBDragEnterEventArgs() { } public void SetParameters(DataObject DropDataObject, uint KeyState, System.Drawing.Point pt, uint Effect) { this.keystate = KeyState; this.pt = pt; this.dropeffect = (DROPEFFECT)Effect; this.handled = false; this.dataobject = DropDataObject; } public uint keystate; public System.Drawing.Point pt; public DROPEFFECT dropeffect; public DataObject dataobject; public bool handled; } public delegate void WBDragOverEventHandler(object sender, WBDragOverEventArgs e); public class WBDragOverEventArgs : System.EventArgs { public WBDragOverEventArgs() { } public void SetParameters(uint KeyState, System.Drawing.Point pt, uint Effect) { this.keystate = KeyState; this.pt = pt; this.dropeffect = (DROPEFFECT)Effect; this.handled = false; } public uint keystate; public System.Drawing.Point pt; public DROPEFFECT dropeffect; public bool handled; } public delegate void WBDragLeaveEventHandler(object sender); public delegate void WBDropEventHandler(object sender, WBDropEventArgs e); public class WBDropEventArgs : System.EventArgs { public WBDropEventArgs() { } public void SetParameters(uint KeyState, System.Drawing.Point pt, DataObject DropDataObject, uint Effect) { this.handled = false; this.keystate = KeyState; this.pt = pt; this.dropeffect = (DROPEFFECT)Effect; this.dataobject = DropDataObject; } public uint keystate; public System.Drawing.Point pt; public DROPEFFECT dropeffect; public DataObject dataobject; public bool handled; } public delegate void ContextMenuEventHandler(object sender, ContextMenuEventArgs e); public class ContextMenuEventArgs : System.EventArgs { public ContextMenuEventArgs() { this.displaydefault = true; } public void SetParameters(WB_CONTEXTMENU_TYPES ContextMenuType, System.Drawing.Point pt, object DispCtxMenuObj) { this.displaydefault = true; this.contextmenutype = ContextMenuType; this.pt = pt; this.dispctxmenuobj = DispCtxMenuObj; } public WB_CONTEXTMENU_TYPES contextmenutype; public System.Drawing.Point pt; public object dispctxmenuobj; public bool displaydefault; } public delegate void DocHostShowUIShowMessageEventHandler(object sender, DocHostShowUIShowMessageEventArgs e); public class DocHostShowUIShowMessageEventArgs : System.EventArgs { public DocHostShowUIShowMessageEventArgs() { this.handled = false; } public void SetParameters(IntPtr Hwnd, string Text, string Caption, uint Type, string HelpFile, uint HelpContext, int Result) { this.handled = false; this.hwnd = Hwnd; this.text = Text; this.caption = Caption; this.type = Type; this.helpcontext = HelpContext; this.result = Result; } public void Reset() { this.handled = false; this.hwnd = IntPtr.Zero; this.text = string.Empty; this.caption = string.Empty; this.helpcontext = (uint)0; this.result = 0; //S_OK } public IntPtr hwnd; public string text; public string caption; public uint type; public string helpfile; public uint helpcontext; public int result; public bool handled; } public delegate void GetOptionKeyPathEventHandler(object sender, GetOptionKeyPathEventArgs e); public class GetOptionKeyPathEventArgs : System.EventArgs { public GetOptionKeyPathEventArgs() { this.handled = false; } public void SetParameters() { this.handled = false; this.keypath = ""; } public string keypath; public bool handled; } public delegate void WBKeyDownEventHandler(object sender, WBKeyDownEventArgs e); public class WBKeyDownEventArgs : System.EventArgs { public WBKeyDownEventArgs() { this.handled = false; } public void SetParameters(Keys KeyCode, Keys VirtualKey) { this.handled = false; this.keycode = KeyCode; this.virtualkey = VirtualKey; } public Keys keycode; public Keys virtualkey; public bool handled; } public delegate void WBKeyUpEventHandler(object sender, WBKeyUpEventArgs e); public class WBKeyUpEventArgs : System.EventArgs { public WBKeyUpEventArgs() { this.handled = false; } public void SetParameters(Keys KeyCode, Keys VirtualKey) { this.handled = false; this.keycode = KeyCode; this.virtualkey = VirtualKey; } public Keys keycode; public Keys virtualkey; public bool handled; } public delegate void ScriptErrorEventHandler(object sender, ScriptErrorEventArgs e); public class ScriptErrorEventArgs : System.EventArgs { public int lineNumber; public int characterNumber; public int errorCode; public string errorMessage; public string url; public bool continueScripts; public ScriptErrorEventArgs() { } public void SetParameters() { this.continueScripts = true; this.lineNumber = 0; this.characterNumber = 0; this.errorCode = 0; this.errorMessage = ""; this.url = ""; } } public delegate void RefreshBeginEventHandler(object sender); public delegate void RefreshEndEventHandler(object sender); public delegate void ProcessUrlActionEventHandler(object sender, ProcessUrlActionEventArgs e); public class ProcessUrlActionEventArgs : System.ComponentModel.CancelEventArgs { public bool handled; public bool hasContext; public string url; public URLACTION urlAction; public URLPOLICY urlPolicy; public Guid context; public ProcessUrlActionFlags flags; public ProcessUrlActionEventArgs() { } public void SetParameters(string surl, URLACTION action, URLPOLICY policy, Guid gcontext, ProcessUrlActionFlags puaf, bool bhascontext) { this.Cancel = false; this.handled = false; this.url = surl; this.urlAction = action; this.urlPolicy = policy; this.context = gcontext; this.flags = puaf; this.hasContext = bhascontext; } public void ResetParameters() { this.Cancel = false; this.handled = false; this.url = string.Empty; this.urlAction = URLACTION.MIN; this.urlPolicy = URLPOLICY.ALLOW; this.context = Guid.Empty; this.flags = ProcessUrlActionFlags.PUAF_DEFAULT; this.hasContext = false; } } #endregion #region Asynchronous pluggable protocols (APP) using COM component public delegate void ProtocolHandlerOnResponseEventHandler(object sender, ProtocolHandlerOnResponseEventArgs e); public class ProtocolHandlerOnResponseEventArgs : System.ComponentModel.CancelEventArgs { public ProtocolHandlerOnResponseEventArgs() { } public void SetParameters(string url, string responseheaders, string redirectedurl, string redirectedheaders) { this.Cancel = false; this.m_URL = url; this.m_ResponseHeaders = responseheaders; this.m_RedirectedUrl = redirectedurl; this.m_RedirectHeaders = redirectedheaders; } public void Reset() { this.Cancel = false; this.m_URL = string.Empty; this.m_ResponseHeaders = string.Empty; this.m_RedirectedUrl = string.Empty; this.m_RedirectHeaders = string.Empty; } public string m_URL = string.Empty; public string m_ResponseHeaders = string.Empty; public string m_RedirectedUrl = string.Empty; public string m_RedirectHeaders = string.Empty; } public delegate void ProtocolHandlerOnBeginTransactionEventHandler(object sender, ProtocolHandlerOnBeginTransactionEventArgs e); public class ProtocolHandlerOnBeginTransactionEventArgs : System.ComponentModel.CancelEventArgs { public ProtocolHandlerOnBeginTransactionEventArgs() { } public void SetParameters(string url, string requestheaders) { this.Cancel = false; this.m_URL = url; this.m_RequestHeaders = requestheaders; //Additional headers can be added to what is already //being send by Webbrowser control this.m_AdditionalHeadersToAdd = string.Empty; } public void Reset() { this.Cancel = false; this.m_URL = string.Empty; this.m_RequestHeaders = string.Empty; this.m_AdditionalHeadersToAdd = string.Empty; } public string m_URL = string.Empty; public string m_RequestHeaders = string.Empty; public string m_AdditionalHeadersToAdd = string.Empty; } #endregion #region FileDownloadEx using COM component public delegate void FileDownloadExErrorEventHandler(object sender, FileDownloadExErrorEventArgs e); public class FileDownloadExErrorEventArgs : System.EventArgs { public FileDownloadExErrorEventArgs() { } public void SetParameters(int uid, string url, string errormsg) { this.m_dlUID = uid; this.m_URL = url; m_ErrorMsg = errormsg; } public void Reset() { m_dlUID = 0; m_URL = string.Empty; m_ErrorMsg = string.Empty; } public int m_dlUID = 0; public string m_URL = string.Empty; public string m_ErrorMsg = string.Empty; } public delegate void FileDownloadExProgressEventHandler(object sender, FileDownloadExProgressEventArgs e); public class FileDownloadExProgressEventArgs : System.ComponentModel.CancelEventArgs { public FileDownloadExProgressEventArgs() { } public void SetParameters(int uid, string url, int progress, int progressmax) { this.Cancel = false; this.m_dlUID = uid; this.m_URL = url; this.m_Progress = progress; this.m_ProgressMax = progressmax; } public void Reset() { this.m_dlUID = 0; this.m_URL = string.Empty; this.m_Progress = 0; this.m_ProgressMax = 0; } public int m_dlUID = 0; public string m_URL = string.Empty; public int m_Progress = 0; public int m_ProgressMax = 0; } public delegate void FileDownloadExAuthenticateEventHandler(object sender, FileDownloadExAuthenticateEventArgs e); public class FileDownloadExAuthenticateEventArgs : System.ComponentModel.CancelEventArgs { public FileDownloadExAuthenticateEventArgs() { } public void SetParameters(int uid) { this.Cancel = true; this.m_dlUID = uid; this.username = string.Empty; this.password = string.Empty; } public void Reset() { m_dlUID = 0; this.username = string.Empty; this.password = string.Empty; } public int m_dlUID = 0; public string username; public string password; } public delegate void FileDownloadExEndEventHandler(object sender, FileDownloadExEndEventArgs e); public class FileDownloadExEndEventArgs : System.EventArgs { public FileDownloadExEndEventArgs() { } public void SetParameters(int uid, string url, string filename) { this.m_dlUID = uid; this.m_URL = url; this.m_SavedFileNamePath = filename; } public void Reset() { this.m_dlUID = 0; this.m_URL = string.Empty; this.m_SavedFileNamePath = string.Empty; } public int m_dlUID = 0; public string m_URL = string.Empty; public string m_SavedFileNamePath = string.Empty; } public delegate void FileDownloadExEventHandler(object sender, FileDownloadExEventArgs e); public class FileDownloadExEventArgs : System.ComponentModel.CancelEventArgs { public FileDownloadExEventArgs() { } public void SetParameters(int uid, string url, string filename, string ext, string filesize, string extraheaders, string redirectedurl) { this.Cancel = false; this.m_dlUID = uid; this.m_URL = url; this.m_Filename = filename; this.m_Ext = ext; this.m_FileSize = filesize; this.m_ExtraHeaders = extraheaders; this.m_RedirectedUrl = redirectedurl; this.m_PathToSave = string.Empty; this.m_SendProgressEvents = false; } public void Reset() { this.Cancel = false; this.m_dlUID = 0; this.m_URL = string.Empty; this.m_Filename = string.Empty; this.m_Ext = string.Empty; this.m_FileSize = string.Empty; this.m_ExtraHeaders = string.Empty; this.m_RedirectedUrl = string.Empty; this.m_PathToSave = string.Empty; this.m_SendProgressEvents = false; } public int m_dlUID = 0; public string m_URL = string.Empty; public string m_Filename = string.Empty; //somefile.zip public string m_Ext = string.Empty; //.zip public string m_FileSize = string.Empty; //in bytes public string m_ExtraHeaders = string.Empty; public string m_RedirectedUrl = string.Empty; public bool m_SendProgressEvents = false; //Cancel = false; public string m_PathToSave = string.Empty; //Drive:\Dir\filename.ext //or the file will be saved in the exe dir with the m_Filename } #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 Microsoft.Build.Framework; using Microsoft.Build.Utilities; using NuGet.Frameworks; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Microsoft.DotNet.Build.Tasks.Packaging { public class GeneratePackageReport : PackagingTask { private Dictionary<string, PackageItem> _targetPathToPackageItem; private AggregateNuGetAssetResolver _resolver; private Dictionary<NuGetFramework, string[]> _frameworks; private NuGetAssetResolver _resolverWithoutPlaceholders; private HashSet<string> _unusedTargetPaths; [Required] public string PackageId { get; set; } [Required] public string PackageVersion { get; set; } [Required] public ITaskItem[] Files { get; set; } /// <summary> /// Frameworks to evaluate. /// Identity: Framework /// RuntimeIDs: Semi-colon seperated list of runtime IDs /// </summary> [Required] public ITaskItem[] Frameworks { get; set; } /// <summary> /// Path to runtime.json that contains the runtime graph. /// </summary> [Required] public string RuntimeFile { get; set; } [Required] public ITaskItem[] PackageIndexes { get; set; } /// <summary> /// JSON file describing results of validation /// </summary> [Required] public string ReportFile { get; set; } public override bool Execute() { LoadFiles(); LoadFrameworks(); var report = new PackageReport() { Id = PackageId, Version = PackageVersion, SupportedFrameworks = new Dictionary<string, string>() }; string package = $"{PackageId}/{PackageVersion}"; foreach (var framework in _frameworks.OrderBy(f => f.Key.ToString())) { var fx = framework.Key; var runtimeIds = framework.Value; var compileAssets = _resolver.ResolveCompileAssets(fx, PackageId); bool hasCompileAsset, hasCompilePlaceHolder; NuGetAssetResolver.ExamineAssets(Log, "Compile", package, fx.ToString(), compileAssets, out hasCompileAsset, out hasCompilePlaceHolder); MarkUsed(compileAssets); // start by making sure it has some asset available for compile var isSupported = hasCompileAsset || hasCompilePlaceHolder; if (runtimeIds.All(rid => !String.IsNullOrEmpty(rid))) { // Add Framework only (compile) target if all RIDs are non-empty. // This acts as a compile target for a framework that requires a RID for runtime. var reportTarget = new Target() { Framework = fx.ToString(), RuntimeID = null, CompileAssets = compileAssets.Select(c => GetPackageAssetFromTargetPath(c)).ToArray() }; report.Targets.Add(fx.ToString(), reportTarget); } foreach (var runtimeId in runtimeIds) { string target = String.IsNullOrEmpty(runtimeId) ? fx.ToString() : $"{fx}/{runtimeId}"; var runtimeAssets = _resolver.ResolveRuntimeAssets(fx, runtimeId); bool hasRuntimeAsset, hasRuntimePlaceHolder; NuGetAssetResolver.ExamineAssets(Log, "Runtime", package, target, runtimeAssets, out hasRuntimeAsset, out hasRuntimePlaceHolder); MarkUsed(runtimeAssets); if (!FrameworkUtilities.IsGenerationMoniker(fx) && !fx.IsPCL) { // only look at runtime assets for runnable frameworks. isSupported &= (hasCompileAsset && hasRuntimeAsset) || // matching assets (hasCompilePlaceHolder && hasRuntimeAsset) || // private runtime (hasCompilePlaceHolder && hasRuntimePlaceHolder); // placeholders } var nativeAssets = _resolver.ResolveNativeAssets(fx, runtimeId); MarkUsed(nativeAssets); var reportTarget = new Target() { Framework = fx.ToString(), RuntimeID = runtimeId, CompileAssets = compileAssets.Select(c => GetPackageAssetFromTargetPath(c)).ToArray(), RuntimeAssets = runtimeAssets.Select(r => GetPackageAssetFromTargetPath(r)).ToArray(), NativeAssets = nativeAssets.Select(n => GetPackageAssetFromTargetPath(n)).ToArray() }; report.Targets[target] = reportTarget; } if (isSupported) { // Find version // first try the resolved compile asset for this package var refAssm = compileAssets.FirstOrDefault(r => !NuGetAssetResolver.IsPlaceholder(r))?.Substring(PackageId.Length + 1); if (refAssm == null) { // if we didn't have a compile asset it means this framework is supported inbox with a placeholder // resolve the assets without placeholders to pick up the netstandard reference assembly. compileAssets = _resolverWithoutPlaceholders.ResolveCompileAssets(fx); refAssm = compileAssets.FirstOrDefault(r => !NuGetAssetResolver.IsPlaceholder(r)); } var version = "unknown"; if (refAssm != null) { version = _targetPathToPackageItem[AggregateNuGetAssetResolver.AsPackageSpecificTargetPath(PackageId, refAssm)].Version?.ToString() ?? version; } report.SupportedFrameworks.Add(fx.ToString(), version); } } report.UnusedAssets = _unusedTargetPaths.Select(tp => GetPackageAssetFromTargetPath(tp)).ToArray(); report.Save(ReportFile); return !Log.HasLoggedErrors; } private static string[] s_noRids = new[] { string.Empty }; private static HashSet<string> s_ignoredFrameworks = new HashSet<string>() { FrameworkConstants.FrameworkIdentifiers.AspNet, FrameworkConstants.FrameworkIdentifiers.AspNetCore, FrameworkConstants.FrameworkIdentifiers.Dnx, FrameworkConstants.FrameworkIdentifiers.DnxCore, FrameworkConstants.FrameworkIdentifiers.DotNet, FrameworkConstants.FrameworkIdentifiers.NetPlatform, FrameworkConstants.FrameworkIdentifiers.NetStandardApp, FrameworkConstants.FrameworkIdentifiers.Silverlight, FrameworkConstants.FrameworkIdentifiers.Windows, FrameworkConstants.FrameworkIdentifiers.WinRT }; private void LoadFrameworks() { _frameworks = new Dictionary<NuGetFramework, string[]>(NuGetFramework.Comparer); // load the specified frameworks foreach(var framework in Frameworks) { var runtimeIds = framework.GetMetadata("RuntimeIDs")?.Split(';'); NuGetFramework fx; try { fx = FrameworkUtilities.ParseNormalized(framework.ItemSpec); } catch (Exception ex) { Log.LogError($"Could not parse Framework {framework.ItemSpec}. {ex}"); continue; } if (fx.Equals(NuGetFramework.UnsupportedFramework)) { Log.LogError($"Did not recognize {framework.ItemSpec} as valid Framework."); continue; } _frameworks.Add(fx, runtimeIds); } // inspect any TFMs explicitly targeted var fileFrameworks = _targetPathToPackageItem.Values.Select(f => f.TargetFramework).Distinct(NuGetFramework.Comparer).Where(f => f != null); foreach(var fileFramework in fileFrameworks) { if (!_frameworks.ContainsKey(fileFramework)) { _frameworks.Add(fileFramework, s_noRids); } } // inspect any TFMs inbox var index = PackageIndex.Load(PackageIndexes.Select(pi => pi.GetMetadata("FullPath"))); var inboxFrameworks = index.GetInboxFrameworks(PackageId).NullAsEmpty(); foreach (var inboxFramework in inboxFrameworks) { if (!_frameworks.ContainsKey(inboxFramework)) { _frameworks.Add(inboxFramework, s_noRids); } } // inspect for derived TFMs var expander = new FrameworkExpander(); foreach(var framework in _frameworks.Keys.ToArray()) { var derivedFxs = expander.Expand(framework); foreach (var derivedFx in derivedFxs) { if (derivedFx.IsDesktop() && derivedFx.HasProfile) { // skip desktop profiles continue; } if (derivedFx.Version.Major == 0 && derivedFx.Version.Minor == 0) { // skip unversioned frameworks continue; } if (s_ignoredFrameworks.Contains(derivedFx.Framework)) { continue; } if (!_frameworks.ContainsKey(derivedFx)) { _frameworks.Add(derivedFx, s_noRids); } } } } private void LoadFiles() { var packageItems = new Dictionary<string, List<PackageItem>>(); foreach (var file in Files) { try { var packageItem = new PackageItem(file); if (!packageItem.TargetPath.StartsWith("runtimes") && !packageItem.IsDll && !packageItem.IsPlaceholder) { continue; } if (String.IsNullOrWhiteSpace(packageItem.TargetPath)) { Log.LogError($"{packageItem.TargetPath} is missing TargetPath metadata"); } string packageId = packageItem.Package ?? PackageId; if (!packageItems.ContainsKey(packageId)) { packageItems[packageId] = new List<PackageItem>(); } packageItems[packageId].Add(packageItem); } catch (Exception ex) { Log.LogError($"Could not parse File {file.ItemSpec}. {ex}"); // skip it. } } // build a map to translate back to source file from resolved asset // we use package-specific paths since we're resolving a set of packages. _targetPathToPackageItem = new Dictionary<string, PackageItem>(); _unusedTargetPaths = new HashSet<string>(); foreach (var packageSpecificItems in packageItems) { foreach (PackageItem packageItem in packageSpecificItems.Value) { string packageSpecificTargetPath = AggregateNuGetAssetResolver.AsPackageSpecificTargetPath(packageSpecificItems.Key, packageItem.TargetPath); if (_targetPathToPackageItem.ContainsKey(packageSpecificTargetPath)) { Log.LogError($"Files {_targetPathToPackageItem[packageSpecificTargetPath].SourcePath} and {packageItem.SourcePath} have the same TargetPath {packageSpecificTargetPath}."); } _targetPathToPackageItem[packageSpecificTargetPath] = packageItem; _unusedTargetPaths.Add(packageSpecificTargetPath); } } _resolver = new AggregateNuGetAssetResolver(RuntimeFile); foreach (string packageId in packageItems.Keys) { _resolver.AddPackageItems(packageId, packageItems[packageId].Select(f => f.TargetPath)); } // create a resolver that can be used to determine the API version for inbox assemblies // since inbox assemblies are represented with placeholders we can remove the placeholders // and use the netstandard reference assembly to determine the API version if (packageItems.Any() && packageItems.ContainsKey(PackageId)) { var filesWithoutPlaceholders = packageItems[PackageId] .Select(pf => pf.TargetPath) .Where(f => !NuGetAssetResolver.IsPlaceholder(f)); _resolverWithoutPlaceholders = new NuGetAssetResolver(RuntimeFile, filesWithoutPlaceholders); } } private PackageAsset GetPackageAssetFromTargetPath(string targetPath) { PackageItem packageItem = null; if (!_targetPathToPackageItem.TryGetValue(targetPath, out packageItem)) { throw new ArgumentException($"Could not find source item for {targetPath}", nameof(targetPath)); } var packageAsset = new PackageAsset() { HarvestedFrom = packageItem.HarvestedFrom, LocalPath = packageItem.SourcePath, PackagePath = packageItem.TargetPath, TargetFramework = packageItem.TargetFramework, Version = packageItem.Version }; if (packageItem.SourceProject != null) { packageAsset.SourceProject = new BuildProject() { Project = packageItem.SourceProject, AdditionalProperties = packageItem.AdditionalProperties, UndefineProperties = packageItem.UndefineProperties }; } return packageAsset; } private void MarkUsed(IEnumerable<string> targetPaths) { foreach(var targetPath in targetPaths) { _unusedTargetPaths.Remove(targetPath); } } private class SupportFramework { private static readonly string[] s_nullRidList = new string[] { null }; public SupportFramework(NuGetFramework framework) { Framework = framework; RuntimeIds = s_nullRidList; } public NuGetFramework Framework { get; } public string[] RuntimeIds { get; set; } public string ShortName { get { return Framework.GetShortFolderName(); } } } } }
// // https://github.com/ServiceStack/ServiceStack.Redis/ // ServiceStack.Redis: ECMA CLI Binding to the Redis key-value storage system // // Authors: // Demis Bellot (demis.bellot@gmail.com) // // Copyright 2013 ServiceStack. // // Licensed under the same terms of Redis and ServiceStack: new BSD license. // using System; using System.Collections.Generic; namespace ServiceStack.Redis { public interface IRedisNativeClient : IDisposable { //Redis utility operations Dictionary<string, string> Info { get; } long Db { get; set; } long DbSize { get; } DateTime LastSave { get; } void Save(); void BgSave(); void Shutdown(); void BgRewriteAof(); void Quit(); void FlushDb(); void FlushAll(); bool Ping(); string Echo(string text); void SlaveOf(string hostname, int port); void SlaveOfNoOne(); byte[][] ConfigGet(string pattern); void ConfigSet(string item, byte[] value); void ConfigResetStat(); byte[][] Time(); void DebugSegfault(); byte[] Dump(string key); byte[] Restore(string key, long expireMs, byte[] dumpValue); void Migrate(string host, int port, int destinationDb, long timeoutMs); bool Move(string key, int db); long ObjectIdleTime(string key); //Common key-value Redis operations byte[][] Keys(string pattern); long Exists(string key); long StrLen(string key); void Set(string key, byte[] value); void SetEx(string key, int expireInSeconds, byte[] value); bool Persist(string key); void PSetEx(string key, long expireInMs, byte[] value); long SetNX(string key, byte[] value); void MSet(byte[][] keys, byte[][] values); void MSet(string[] keys, byte[][] values); bool MSetNx(byte[][] keys, byte[][] values); bool MSetNx(string[] keys, byte[][] values); byte[] Get(string key); byte[] GetSet(string key, byte[] value); byte[][] MGet(params byte[][] keysAndArgs); byte[][] MGet(params string[] keys); long Del(string key); long Del(params string[] keys); long Incr(string key); long IncrBy(string key, int incrBy); double IncrByFloat(string key, double incrBy); long Decr(string key); long DecrBy(string key, int decrBy); long Append(string key, byte[] value); [Obsolete("Was renamed to GetRange in 2.4")] byte[] Substr(string key, int fromIndex, int toIndex); byte[] GetRange(string key, int fromIndex, int toIndex); long SetRange(string key, int offset, byte[] value); long GetBit(string key, int offset); long SetBit(string key, int offset, int value); string RandomKey(); void Rename(string oldKeyname, string newKeyname); bool RenameNx(string oldKeyname, string newKeyname); bool Expire(string key, int seconds); bool PExpire(string key, long ttlMs); bool ExpireAt(string key, long unixTime); bool PExpireAt(string key, long unixTimeMs); long Ttl(string key); long PTtl(string key); //Redis Sort operation (works on lists, sets or hashes) byte[][] Sort(string listOrSetId, SortOptions sortOptions); //Redis List operations byte[][] LRange(string listId, int startingFrom, int endingAt); long RPush(string listId, byte[] value); long RPushX(string listId, byte[] value); long LPush(string listId, byte[] value); long LPushX(string listId, byte[] value); void LTrim(string listId, int keepStartingFrom, int keepEndingAt); long LRem(string listId, int removeNoOfMatches, byte[] value); long LLen(string listId); byte[] LIndex(string listId, int listIndex); void LInsert(string listId, bool insertBefore, byte[] pivot, byte[] value); void LSet(string listId, int listIndex, byte[] value); byte[] LPop(string listId); byte[] RPop(string listId); byte[][] BLPop(string listId, int timeOutSecs); byte[][] BLPop(string[] listIds, int timeOutSecs); byte[] BLPopValue(string listId, int timeOutSecs); byte[][] BLPopValue(string[] listIds, int timeOutSecs); byte[][] BRPop(string listId, int timeOutSecs); byte[][] BRPop(string[] listIds, int timeOutSecs); byte[] RPopLPush(string fromListId, string toListId); byte[] BRPopValue(string listId, int timeOutSecs); byte[][] BRPopValue(string[] listIds, int timeOutSecs); byte[] BRPopLPush(string fromListId, string toListId, int timeOutSecs); //Redis Set operations byte[][] SMembers(string setId); long SAdd(string setId, byte[] value); long SAdd(string setId, byte[][] values); long SRem(string setId, byte[] value); byte[] SPop(string setId); void SMove(string fromSetId, string toSetId, byte[] value); long SCard(string setId); long SIsMember(string setId, byte[] value); byte[][] SInter(params string[] setIds); void SInterStore(string intoSetId, params string[] setIds); byte[][] SUnion(params string[] setIds); void SUnionStore(string intoSetId, params string[] setIds); byte[][] SDiff(string fromSetId, params string[] withSetIds); void SDiffStore(string intoSetId, string fromSetId, params string[] withSetIds); byte[] SRandMember(string setId); //Redis Sorted Set operations long ZAdd(string setId, double score, byte[] value); long ZAdd(string setId, long score, byte[] value); long ZRem(string setId, byte[] value); double ZIncrBy(string setId, double incrBy, byte[] value); double ZIncrBy(string setId, long incrBy, byte[] value); long ZRank(string setId, byte[] value); long ZRevRank(string setId, byte[] value); byte[][] ZRange(string setId, int min, int max); byte[][] ZRangeWithScores(string setId, int min, int max); byte[][] ZRevRange(string setId, int min, int max); byte[][] ZRevRangeWithScores(string setId, int min, int max); byte[][] ZRangeByScore(string setId, double min, double max, int? skip, int? take); byte[][] ZRangeByScore(string setId, long min, long max, int? skip, int? take); byte[][] ZRangeByScoreWithScores(string setId, double min, double max, int? skip, int? take); byte[][] ZRangeByScoreWithScores(string setId, long min, long max, int? skip, int? take); byte[][] ZRevRangeByScore(string setId, double min, double max, int? skip, int? take); byte[][] ZRevRangeByScore(string setId, long min, long max, int? skip, int? take); byte[][] ZRevRangeByScoreWithScores(string setId, double min, double max, int? skip, int? take); byte[][] ZRevRangeByScoreWithScores(string setId, long min, long max, int? skip, int? take); long ZRemRangeByRank(string setId, int min, int max); long ZRemRangeByScore(string setId, double fromScore, double toScore); long ZRemRangeByScore(string setId, long fromScore, long toScore); long ZCard(string setId); double ZScore(string setId, byte[] value); long ZUnionStore(string intoSetId, params string[] setIds); long ZInterStore(string intoSetId, params string[] setIds); //Redis Hash operations long HSet(string hashId, byte[] key, byte[] value); void HMSet(string hashId, byte[][] keys, byte[][] values); long HSetNX(string hashId, byte[] key, byte[] value); long HIncrby(string hashId, byte[] key, int incrementBy); double HIncrbyFloat(string hashId, byte[] key, double incrementBy); byte[] HGet(string hashId, byte[] key); byte[][] HMGet(string hashId, params byte[][] keysAndArgs); long HDel(string hashId, byte[] key); long HExists(string hashId, byte[] key); long HLen(string hashId); byte[][] HKeys(string hashId); byte[][] HVals(string hashId); byte[][] HGetAll(string hashId); //Redis Pub/Sub operations void Watch(params string[] keys); void UnWatch(); long Publish(string toChannel, byte[] message); byte[][] Subscribe(params string[] toChannels); byte[][] UnSubscribe(params string[] toChannels); byte[][] PSubscribe(params string[] toChannelsMatchingPatterns); byte[][] PUnSubscribe(params string[] toChannelsMatchingPatterns); byte[][] ReceiveMessages(); //Redis LUA support long EvalInt(string luaBody, int numberOfKeys, params byte[][] keysAndArgs); long EvalShaInt(string sha1, int numberOfKeys, params byte[][] keysAndArgs); string EvalStr(string luaBody, int numberOfKeys, params byte[][] keysAndArgs); string EvalShaStr(string sha1, int numberOfKeys, params byte[][] keysAndArgs); byte[][] Eval(string luaBody, int numberOfKeys, params byte[][] keysAndArgs); byte[][] EvalSha(string sha1, int numberOfKeys, params byte[][] keysAndArgs); string CalculateSha1(string luaBody); byte[][] ScriptExists(params byte[][] sha1Refs); void ScriptFlush(); void ScriptKill(); byte[] ScriptLoad(string body); } }
// Licensed to the Apache Software Foundation(ASF) under one // or more contributor license agreements.See the NOTICE file // distributed with this work for additional information // regarding copyright ownership.The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. using System; using System.Text; using System.Threading; using System.Threading.Tasks; using Thrift.Protocol.Entities; using Thrift.Transport; namespace Thrift.Protocol { // ReSharper disable once InconsistentNaming public class TBinaryProtocol : TProtocol { protected const uint VersionMask = 0xffff0000; protected const uint Version1 = 0x80010000; protected bool StrictRead; protected bool StrictWrite; // minimize memory allocations by means of an preallocated bytes buffer // The value of 128 is arbitrarily chosen, the required minimum size must be sizeof(long) private byte[] PreAllocatedBuffer = new byte[128]; private static readonly TStruct AnonymousStruct = new TStruct(string.Empty); private static readonly TField StopField = new TField() { Type = TType.Stop }; public TBinaryProtocol(TTransport trans) : this(trans, false, true) { } public TBinaryProtocol(TTransport trans, bool strictRead, bool strictWrite) : base(trans) { StrictRead = strictRead; StrictWrite = strictWrite; } public override async Task WriteMessageBeginAsync(TMessage message, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return; } if (StrictWrite) { var version = Version1 | (uint) message.Type; await WriteI32Async((int) version, cancellationToken); await WriteStringAsync(message.Name, cancellationToken); await WriteI32Async(message.SeqID, cancellationToken); } else { await WriteStringAsync(message.Name, cancellationToken); await WriteByteAsync((sbyte) message.Type, cancellationToken); await WriteI32Async(message.SeqID, cancellationToken); } } public override async Task WriteMessageEndAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } public override async Task WriteStructBeginAsync(TStruct @struct, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } public override async Task WriteStructEndAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } public override async Task WriteFieldBeginAsync(TField field, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return; } await WriteByteAsync((sbyte) field.Type, cancellationToken); await WriteI16Async(field.ID, cancellationToken); } public override async Task WriteFieldEndAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } public override async Task WriteFieldStopAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return; } await WriteByteAsync((sbyte) TType.Stop, cancellationToken); } public override async Task WriteMapBeginAsync(TMap map, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return; } PreAllocatedBuffer[0] = (byte)map.KeyType; PreAllocatedBuffer[1] = (byte)map.ValueType; await Trans.WriteAsync(PreAllocatedBuffer, 0, 2, cancellationToken); await WriteI32Async(map.Count, cancellationToken); } public override async Task WriteMapEndAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } public override async Task WriteListBeginAsync(TList list, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return; } await WriteByteAsync((sbyte) list.ElementType, cancellationToken); await WriteI32Async(list.Count, cancellationToken); } public override async Task WriteListEndAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } public override async Task WriteSetBeginAsync(TSet set, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return; } await WriteByteAsync((sbyte) set.ElementType, cancellationToken); await WriteI32Async(set.Count, cancellationToken); } public override async Task WriteSetEndAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } public override async Task WriteBoolAsync(bool b, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return; } await WriteByteAsync(b ? (sbyte) 1 : (sbyte) 0, cancellationToken); } public override async Task WriteByteAsync(sbyte b, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return; } PreAllocatedBuffer[0] = (byte)b; await Trans.WriteAsync(PreAllocatedBuffer, 0, 1, cancellationToken); } public override async Task WriteI16Async(short i16, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return; } PreAllocatedBuffer[0] = (byte)(0xff & (i16 >> 8)); PreAllocatedBuffer[1] = (byte)(0xff & i16); await Trans.WriteAsync(PreAllocatedBuffer, 0, 2, cancellationToken); } public override async Task WriteI32Async(int i32, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return; } PreAllocatedBuffer[0] = (byte)(0xff & (i32 >> 24)); PreAllocatedBuffer[1] = (byte)(0xff & (i32 >> 16)); PreAllocatedBuffer[2] = (byte)(0xff & (i32 >> 8)); PreAllocatedBuffer[3] = (byte)(0xff & i32); await Trans.WriteAsync(PreAllocatedBuffer, 0, 4, cancellationToken); } public override async Task WriteI64Async(long i64, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return; } PreAllocatedBuffer[0] = (byte)(0xff & (i64 >> 56)); PreAllocatedBuffer[1] = (byte)(0xff & (i64 >> 48)); PreAllocatedBuffer[2] = (byte)(0xff & (i64 >> 40)); PreAllocatedBuffer[3] = (byte)(0xff & (i64 >> 32)); PreAllocatedBuffer[4] = (byte)(0xff & (i64 >> 24)); PreAllocatedBuffer[5] = (byte)(0xff & (i64 >> 16)); PreAllocatedBuffer[6] = (byte)(0xff & (i64 >> 8)); PreAllocatedBuffer[7] = (byte)(0xff & i64); await Trans.WriteAsync(PreAllocatedBuffer, 0, 8, cancellationToken); } public override async Task WriteDoubleAsync(double d, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return; } await WriteI64Async(BitConverter.DoubleToInt64Bits(d), cancellationToken); } public override async Task WriteBinaryAsync(byte[] bytes, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return; } await WriteI32Async(bytes.Length, cancellationToken); await Trans.WriteAsync(bytes, 0, bytes.Length, cancellationToken); } public override async ValueTask<TMessage> ReadMessageBeginAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return await Task.FromCanceled<TMessage>(cancellationToken); } var message = new TMessage(); var size = await ReadI32Async(cancellationToken); if (size < 0) { var version = (uint) size & VersionMask; if (version != Version1) { throw new TProtocolException(TProtocolException.BAD_VERSION, $"Bad version in ReadMessageBegin: {version}"); } message.Type = (TMessageType) (size & 0x000000ff); message.Name = await ReadStringAsync(cancellationToken); message.SeqID = await ReadI32Async(cancellationToken); } else { if (StrictRead) { throw new TProtocolException(TProtocolException.BAD_VERSION, "Missing version in ReadMessageBegin, old client?"); } message.Name = (size > 0) ? await ReadStringBodyAsync(size, cancellationToken) : string.Empty; message.Type = (TMessageType) await ReadByteAsync(cancellationToken); message.SeqID = await ReadI32Async(cancellationToken); } return message; } public override async Task ReadMessageEndAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } public override async ValueTask<TStruct> ReadStructBeginAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } return AnonymousStruct; } public override async Task ReadStructEndAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } public override async ValueTask<TField> ReadFieldBeginAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return await Task.FromCanceled<TField>(cancellationToken); } var type = (TType)await ReadByteAsync(cancellationToken); if (type == TType.Stop) { return StopField; } return new TField { Type = type, ID = await ReadI16Async(cancellationToken) }; } public override async Task ReadFieldEndAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } public override async ValueTask<TMap> ReadMapBeginAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return await Task.FromCanceled<TMap>(cancellationToken); } var map = new TMap { KeyType = (TType) await ReadByteAsync(cancellationToken), ValueType = (TType) await ReadByteAsync(cancellationToken), Count = await ReadI32Async(cancellationToken) }; return map; } public override async Task ReadMapEndAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } public override async ValueTask<TList> ReadListBeginAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return await Task.FromCanceled<TList>(cancellationToken); } var list = new TList { ElementType = (TType) await ReadByteAsync(cancellationToken), Count = await ReadI32Async(cancellationToken) }; return list; } public override async Task ReadListEndAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } public override async ValueTask<TSet> ReadSetBeginAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return await Task.FromCanceled<TSet>(cancellationToken); } var set = new TSet { ElementType = (TType) await ReadByteAsync(cancellationToken), Count = await ReadI32Async(cancellationToken) }; return set; } public override async Task ReadSetEndAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } public override async ValueTask<bool> ReadBoolAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return await Task.FromCanceled<bool>(cancellationToken); } return await ReadByteAsync(cancellationToken) == 1; } public override async ValueTask<sbyte> ReadByteAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return await Task.FromCanceled<sbyte>(cancellationToken); } await Trans.ReadAllAsync(PreAllocatedBuffer, 0, 1, cancellationToken); return (sbyte)PreAllocatedBuffer[0]; } public override async ValueTask<short> ReadI16Async(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return await Task.FromCanceled<short>(cancellationToken); } await Trans.ReadAllAsync(PreAllocatedBuffer, 0, 2, cancellationToken); var result = (short) (((PreAllocatedBuffer[0] & 0xff) << 8) | PreAllocatedBuffer[1] & 0xff); return result; } public override async ValueTask<int> ReadI32Async(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return await Task.FromCanceled<int>(cancellationToken); } await Trans.ReadAllAsync(PreAllocatedBuffer, 0, 4, cancellationToken); var result = ((PreAllocatedBuffer[0] & 0xff) << 24) | ((PreAllocatedBuffer[1] & 0xff) << 16) | ((PreAllocatedBuffer[2] & 0xff) << 8) | PreAllocatedBuffer[3] & 0xff; return result; } #pragma warning disable 675 protected internal long ReadI64FromPreAllocatedBuffer() { var result = ((long) (PreAllocatedBuffer[0] & 0xff) << 56) | ((long) (PreAllocatedBuffer[1] & 0xff) << 48) | ((long) (PreAllocatedBuffer[2] & 0xff) << 40) | ((long) (PreAllocatedBuffer[3] & 0xff) << 32) | ((long) (PreAllocatedBuffer[4] & 0xff) << 24) | ((long) (PreAllocatedBuffer[5] & 0xff) << 16) | ((long) (PreAllocatedBuffer[6] & 0xff) << 8) | PreAllocatedBuffer[7] & 0xff; return result; } #pragma warning restore 675 public override async ValueTask<long> ReadI64Async(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return await Task.FromCanceled<long>(cancellationToken); } await Trans.ReadAllAsync(PreAllocatedBuffer, 0, 8, cancellationToken); return ReadI64FromPreAllocatedBuffer(); } public override async ValueTask<double> ReadDoubleAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return await Task.FromCanceled<double>(cancellationToken); } var d = await ReadI64Async(cancellationToken); return BitConverter.Int64BitsToDouble(d); } public override async ValueTask<byte[]> ReadBinaryAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return await Task.FromCanceled<byte[]>(cancellationToken); } var size = await ReadI32Async(cancellationToken); var buf = new byte[size]; await Trans.ReadAllAsync(buf, 0, size, cancellationToken); return buf; } public override async ValueTask<string> ReadStringAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return await Task.FromCanceled<string>(cancellationToken); } var size = await ReadI32Async(cancellationToken); return size > 0 ? await ReadStringBodyAsync(size, cancellationToken) : string.Empty; } private async ValueTask<string> ReadStringBodyAsync(int size, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled<string>(cancellationToken); } if (size <= PreAllocatedBuffer.Length) { await Trans.ReadAllAsync(PreAllocatedBuffer, 0, size, cancellationToken); return Encoding.UTF8.GetString(PreAllocatedBuffer, 0, size); } var buf = new byte[size]; await Trans.ReadAllAsync(buf, 0, size, cancellationToken); return Encoding.UTF8.GetString(buf, 0, buf.Length); } public class Factory : TProtocolFactory { protected bool StrictRead; protected bool StrictWrite; public Factory() : this(false, true) { } public Factory(bool strictRead, bool strictWrite) { StrictRead = strictRead; StrictWrite = strictWrite; } public override TProtocol GetProtocol(TTransport trans) { return new TBinaryProtocol(trans, StrictRead, StrictWrite); } } } }
// <file> // <copyright see="prj:///doc/copyright.txt"/> // <license see="prj:///doc/license.txt"/> // <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/> // <version>$Revision: 3712 $</version> // </file> using System; using System.IO; using NUnit.Framework; using ICSharpCode.NRefactory.Parser; using ICSharpCode.NRefactory.Ast; using ICSharpCode.NRefactory.PrettyPrinter; namespace ICSharpCode.NRefactory.Tests.PrettyPrinter { [TestFixture] public class VBNetOutputTest { void TestProgram(string program) { IParser parser = ParserFactory.CreateParser(SupportedLanguage.VBNet, new StringReader(program)); parser.Parse(); Assert.AreEqual("", parser.Errors.ErrorOutput); VBNetOutputVisitor outputVisitor = new VBNetOutputVisitor(); outputVisitor.Options.OutputByValModifier = true; outputVisitor.VisitCompilationUnit(parser.CompilationUnit, null); Assert.AreEqual("", outputVisitor.Errors.ErrorOutput); Assert.AreEqual(StripWhitespace(program), StripWhitespace(outputVisitor.Text)); } string StripWhitespace(string text) { return text.Trim().Replace("\t", "").Replace("\r", "").Replace("\n", " ").Replace(" ", " "); } void TestTypeMember(string program) { TestProgram("Class A\n" + program + "\nEnd Class"); } void TestStatement(string statement) { TestTypeMember("Sub Method()\n" + statement + "\nEnd Sub"); } void TestExpression(string expression) { IParser parser = ParserFactory.CreateParser(SupportedLanguage.VBNet, new StringReader(expression)); Expression e = parser.ParseExpression(); Assert.AreEqual("", parser.Errors.ErrorOutput); VBNetOutputVisitor outputVisitor = new VBNetOutputVisitor(); e.AcceptVisitor(outputVisitor, null); Assert.AreEqual("", outputVisitor.Errors.ErrorOutput); Assert.AreEqual(StripWhitespace(expression), StripWhitespace(outputVisitor.Text)); } [Test] public void Field() { TestTypeMember("Private a As Integer"); } [Test] public void Method() { TestTypeMember("Sub Method()\nEnd Sub"); } [Test] public void EnumWithBaseType() { TestProgram("Public Enum Foo As UShort\nEnd Enum"); } [Test] public void PartialModifier() { TestProgram("Public Partial Class Foo\nEnd Class"); } [Test] public void MustInheritClass() { TestProgram("Public MustInherit Class Foo\nEnd Class"); } [Test] public void GenericClassDefinition() { TestProgram("Public Class Foo(Of T As {IDisposable, ICloneable})\nEnd Class"); } [Test] public void GenericClassDefinitionWithBaseType() { TestProgram("Public Class Foo(Of T As IDisposable)\nInherits BaseType\nEnd Class"); } [Test] public void GenericMethodDefinition() { TestTypeMember("Public Sub Foo(Of T As {IDisposable, ICloneable})(ByVal arg As T)\nEnd Sub"); } [Test] public void ArrayRank() { TestStatement("Dim a As Object(,,)"); } [Test] public void ArrayInitialization() { TestStatement("Dim a As Object() = New Object(10) {}"); TestTypeMember("Private MultiDim As Integer(,) = {{1, 2}, {1, 3}}"); TestExpression("New Integer(, ) {{1, 1}, {1, 1}}"); } [Test] public void MethodCallWithOptionalArguments() { TestExpression("M(, )"); } [Test] public void IfStatement() { TestStatement("If a Then\n" + "\tm1()\n" + "ElseIf b Then\n" + "\tm2()\n" + "Else\n" + "\tm3()\n" + "End If"); } [Test] public void ForNextLoop() { TestStatement("For i = 0 To 10\n" + "Next"); TestStatement("For i As Long = 10 To 0 Step -1\n" + "Next"); } [Test] public void DoLoop() { TestStatement("Do\n" + "Loop"); TestStatement("Do\n" + "Loop While Not (i = 10)"); } [Test] public void SelectCase() { TestStatement(@"Select Case i Case 0 Case 1 To 4 Case Else End Select"); } [Test] public void UsingStatement() { TestStatement(@"Using nf As New Font(), nf2 As New List(Of Font)(), nf3 = Nothing Bla(nf) End Using"); } [Test] public void UntypedVariable() { TestStatement("Dim x = 0"); } [Test] public void UntypedField() { TestTypeMember("Dim x = 0"); } [Test] public void Assignment() { TestExpression("a = b"); } [Test] public void SpecialIdentifiers() { // Assembly, Ansi and Until are contextual keywords // Custom is valid inside methods, but not valid for field names TestExpression("Assembly = Ansi * [For] + Until - [Custom]"); } [Test] public void DictionaryAccess() { TestExpression("c!key"); } [Test] public void GenericMethodInvocation() { TestExpression("GenericMethod(Of T)(arg)"); } [Test] public void SpecialIdentifierName() { TestExpression("[Class]"); } [Test] public void GenericDelegate() { TestProgram("Public Delegate Function Predicate(Of T)(ByVal item As T) As String"); } [Test] public void Enum() { TestProgram("Enum MyTest\nRed\n Green\n Blue\nYellow\n End Enum"); } [Test] public void EnumWithInitializers() { TestProgram("Enum MyTest\nRed = 1\n Green = 2\n Blue = 4\n Yellow = 8\n End Enum"); } [Test] public void SyncLock() { TestStatement("SyncLock a\nWork()\nEnd SyncLock"); } [Test] public void Using() { TestStatement("Using a As New A()\na.Work()\nEnd Using"); } [Test] public void Cast() { TestExpression("CType(a, T)"); } [Test] public void DirectCast() { TestExpression("DirectCast(a, T)"); } [Test] public void TryCast() { TestExpression("TryCast(a, T)"); } [Test] public void PrimitiveCast() { TestExpression("CStr(a)"); } [Test] public void TypeOfIs() { TestExpression("TypeOf a Is String"); } [Test] public void PropertyWithAccessorAccessModifiers() { TestTypeMember("Public Property ExpectsValue() As Boolean\n" + "\tPublic Get\n" + "\tEnd Get\n" + "\tProtected Set\n" + "\tEnd Set\n" + "End Property"); } [Test] public void AbstractProperty() { TestTypeMember("Public MustOverride Property ExpectsValue() As Boolean"); TestTypeMember("Public MustOverride ReadOnly Property ExpectsValue() As Boolean"); TestTypeMember("Public MustOverride WriteOnly Property ExpectsValue() As Boolean"); } [Test] public void AbstractMethod() { TestTypeMember("Public MustOverride Sub Run()"); TestTypeMember("Public MustOverride Function Run() As Boolean"); } [Test] public void InterfaceImplementingMethod() { TestTypeMember("Public Sub Run() Implements SomeInterface.Run\nEnd Sub"); TestTypeMember("Public Function Run() As Boolean Implements SomeInterface.Bla\nEnd Function"); } [Test] public void NamedAttributeArgument() { TestProgram("<Attribute(ArgName := \"value\")> _\n" + "Class Test\n" + "End Class"); } [Test] public void ReturnTypeAttribute() { TestTypeMember("Function A() As <Attribute> String\n" + "End Function"); } [Test] public void AssemblyAttribute() { TestProgram("<Assembly: CLSCompliant>"); } [Test] public void ModuleAttribute() { TestProgram("<Module: SuppressMessageAttribute>"); } [Test] public void Interface() { TestProgram("Interface ITest\n" + "Property GetterAndSetter() As Boolean\n" + "ReadOnly Property GetterOnly() As Boolean\n" + "WriteOnly Property SetterOnly() As Boolean\n" + "Sub InterfaceMethod()\n" + "Function InterfaceMethod2() As String\n" + "End Interface"); } [Test] public void OnErrorStatement() { TestStatement("On Error Resume Next"); } [Test] public void OverloadedConversionOperators() { TestTypeMember("Public Shared Narrowing Operator CType(ByVal xmlNode As XmlNode) As TheBug\nEnd Operator"); TestTypeMember("Public Shared Widening Operator CType(ByVal bugNode As TheBug) As XmlNode\nEnd Operator"); } [Test] public void OverloadedTrueFalseOperators() { TestTypeMember("Public Shared Operator IsTrue(ByVal a As TheBug) As Boolean\nEnd Operator"); TestTypeMember("Public Shared Operator IsFalse(ByVal a As TheBug) As Boolean\nEnd Operator"); } [Test] public void OverloadedOperators() { TestTypeMember("Public Shared Operator +(ByVal bugNode As TheBug, ByVal bugNode2 As TheBug) As TheBug\nEnd Operator"); TestTypeMember("Public Shared Operator >>(ByVal bugNode As TheBug, ByVal b As Integer) As TheBug\nEnd Operator"); } [Test] public void AttributeOnParameter() { TestTypeMember("Sub Main(ByRef one As Integer, ByRef two As Integer, <Out> ByRef three As Integer)\nEnd Sub"); } [Test] public void UsingStatementForExistingVariable() { TestStatement("Using obj\nEnd Using"); } [Test] public void ContinueFor() { TestStatement("Continue For"); } [Test] public void ForNextStatementWithFieldLoopVariable() { TestStatement("For Me.Field = 0 To 10\n" + "Next Me.Field"); } [Test] public void WithStatement() { TestStatement("With Ejes\n" + "\t.AddLine(New Point(Me.ClientSize.Width / 2, 0), (New Point(Me.ClientSize.Width / 2, Me.ClientSize.Height)))\n" + "End With"); } [Test] public void NewConstraint() { TestProgram("Public Class Rational(Of T, O As {IRationalMath(Of T), New})\nEnd Class"); } [Test] public void StructConstraint() { TestProgram("Public Class Rational(Of T, O As {IRationalMath(Of T), Structure})\nEnd Class"); } [Test] public void ClassConstraint() { TestProgram("Public Class Rational(Of T, O As {IRationalMath(Of T), Class})\nEnd Class"); } [Test] public void Integer() { TestExpression("16"); } [Test] public void HexadecimalInteger() { TestExpression("&H10"); } [Test] public void HexadecimalMinusOne() { TestExpression("&Hffffffff"); } } }
//------------------------------------------------------------------------------------------------- // <copyright company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR // CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. // </copyright> // // <summary> // // // // </summary> //------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Reactive; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Threading; using System.Threading.Tasks; using System.Web.Routing; using FUSE.Paxos; using FUSE.Paxos.Azure; using FUSE.Paxos.Esent; using FUSE.Weld.Azure; using FUSE.Weld.Base; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.ServiceRuntime; using Microsoft.WindowsAzure.StorageClient; using SignalR.Hubs; using ReverseProxy.Hubs; using System.Security.Cryptography.X509Certificates; namespace ReverseProxy { public class ProxyStateMachine : AdaptiveStateMachine<SerialilzableWebRequest, HttpStatusCode> { Dictionary<Guid, TaskCompletionSource<HttpWebResponse>> completions = new Dictionary<Guid, TaskCompletionSource<HttpWebResponse>>(); public Func<SerialilzableWebRequest, Task<HttpWebResponse>> GetResponse { get; set; } public string ServiceName { get; private set; } CloudStorageAccount cloudStorageAccount; public ProxyStateMachine(string self, IDictionary<string, Uri> endpoints, ISubject<Tuple<Uri, Message>> mesh, IStorage<string, SerialilzableWebRequest> storage, string serviceName, IEnumerable<string> preferedLeaders) : base(self, endpoints, mesh, storage, preferedLeaders) { this.ServiceName = serviceName; this.cloudStorageAccount = Utility.GetStorageAccount(true); } public Task<HttpWebResponse> SubmitAsync(SerialilzableWebRequest r) { var proposal = new Proposal<string, SerialilzableWebRequest>(r); var tcs = new TaskCompletionSource<HttpWebResponse>(); completions.Add(proposal.guid, tcs); return this.ReplicateAsync(proposal, CancellationToken.None).ContinueWith(ant => { ant.Wait(); return tcs.Task; }).Unwrap(); } public override Task<HttpStatusCode> ExecuteAsync(int instance, Proposal<string, SerialilzableWebRequest> command) { return Concurrency.Iterate<HttpStatusCode>(tcs => _executeAsync(tcs, instance, command)); } private IEnumerable<Task> _executeAsync(TaskCompletionSource<HttpStatusCode> tcs, int instance, Proposal<string, SerialilzableWebRequest> proposal) { Action<string> trace = s => FUSE.Paxos.Events.TraceInfo(s, proposal.guid, _paxos.Self, instance, proposal.value.Headers["x-ms-client-request-id"] ?? ""); trace("ExecuteAsync Enter"); var getResponseTask = Concurrency.RetryOnFaultOrCanceledAsync<HttpWebResponse>(() => GetResponse(proposal.value), t => ShouldRetryGetResponse(t, instance, proposal.guid), 1000); yield return getResponseTask; trace("ExecuteAsync ResponseReceived"); if (!proposal.value.Method.Equals("GET", StringComparison.InvariantCultureIgnoreCase)) { var logTask = Concurrency.RetryOnFaultOrCanceledAsync(() => LogResultAsync(instance), _ => true, 1000); yield return logTask; try { logTask.Wait(); trace("ExecuteAsync Logged"); } catch (Exception e) { Validation.TraceException(e, "Exception incrementing LSN"); } } TaskCompletionSource<HttpWebResponse> completion; if (completions.TryGetValue(proposal.guid, out completion)) { completion.SetFromTask(getResponseTask); completions.Remove(proposal.guid); } tcs.SetResult(GetStatusCode(getResponseTask)); trace("ExecuteAsync Exit"); } static HttpStatusCode GetStatusCode(Task<HttpWebResponse> task) { if (task.IsFaulted) { return Validation.HttpStatusCodes(task.Exception).Single(); } else { return task.Result.StatusCode; } } static IList<HttpStatusCode> RetryableHttpStatusCodes = new List<HttpStatusCode> { HttpStatusCode.RequestTimeout, HttpStatusCode.InternalServerError, HttpStatusCode.ServiceUnavailable, HttpStatusCode.GatewayTimeout }; private bool ShouldRetryGetResponse(Task<HttpWebResponse> task, int instance, Guid guid) { if (ShouldRetryGetResponse(task)) { FUSE.Paxos.Events.TraceInfo("ExecuteAsync Retry", guid, _paxos.Self, instance); return true; } else { return false; } } private bool ShouldRetryGetResponse(Task<HttpWebResponse> task) { if (task.IsCanceled) { return true; } else if (task.IsFaulted) { var httpStatusCodes = Validation.HttpStatusCodes(task.Exception).ToArray(); if (httpStatusCodes.Length == 1) { var httpStatusCode = httpStatusCodes[0]; if (RetryableHttpStatusCodes.Contains(httpStatusCode)) { return true; } else { return false; } } else { return true; } } else { throw new ArgumentException("Task must be in faulted or canceled state"); } } private Task LogResultAsync(int instance) { return Task.Factory.Iterate(_logOperation(instance)); } private IEnumerable<Task> _logOperation(int instance) { var container = cloudStorageAccount.CreateCloudBlobClient().GetContainerReference("root"); var blob = container.GetBlobReference(ServiceName + "LogPosition"); while (true) { using (var task = blob.UploadTextAsync((instance + 1).ToString())) { yield return task; if (task.Status == TaskStatus.RanToCompletion) { break; } else { Trace.Write("LogPositionUpload " + task.Exception.ToString()); yield return Task.Factory.StartNewDelayed(30 * 1000); continue; } } } } public static ProxyStateMachine New(string location, string serviceName) { ProxyStateMachine stateMachine; var nodeConfig = RoleEnvironment.GetConfigurationSettingValue(serviceName + ".Nodes"); var nodeDescriptors = nodeConfig.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); var nodes = new Dictionary<string, Uri>(); foreach (var d in nodeDescriptors) { var n = d.Split('='); try { nodes.Add(n[0], new UriBuilder() { Host = n[1] }.Uri); } catch (Exception x) { Trace.TraceError(x.ToString()); } } Uri host; if (nodes.TryGetValue(location, out host)) { var preferedLeaders = RoleEnvironment.GetConfigurationSettingValue(serviceName + ".PreferedActiveMembers").Split(';'); var localStorage = RoleEnvironment.GetLocalResource("LocalStorage").RootPath; var storagePath = Path.Combine(localStorage, serviceName); if (!Directory.Exists(storagePath)) { Directory.CreateDirectory(storagePath); } var storage = new EsentStorage<string, SerialilzableWebRequest>(storagePath, new Counters(location)); var configuration = new Configuration<string>(preferedLeaders, preferedLeaders, nodes.Keys); storage.TryInitialize(configuration); Trace.WriteLine("Local Storage Initialized"); var meshPath = serviceName + "Mesh.ashx"; var uri = new UriBuilder(host) { Path = meshPath }.Uri; X509Certificate2 cert = Utility.GetCert(); var mesh = new MeshHandler<Message>(uri, null, cert); RouteTable.Routes.Add(new Route(meshPath, new FuncRouteHandler(_ => mesh))); FUSE.Weld.Azure.Configuration.SetConfigurationSettingPublisher(); var s2 = Utility.GetStorageAccount(true); var container = s2.CreateCloudBlobClient().GetContainerReference("root"); container.CreateIfNotExist(); Trace.Write("Remote Storage Loaded"); stateMachine = new ProxyStateMachine(location, nodes, mesh, storage, serviceName, preferedLeaders); stateMachine.Paxos.WhenDiverged.Subscribe(d => { Utility.DisableService(stateMachine.ServiceName); }); Global.lastMessages[serviceName] = new Queue<Timestamped<Tuple<string, Message, string>>>(); Global.stateMachines[serviceName] = stateMachine; var o = stateMachine.Mesh .Where(m => Interesting(m.Item2)) .Where(m => stateMachine.EndpointUrisToNames.ContainsKey(m.Item1)) .Select(m => Tuple.Create(stateMachine.EndpointUrisToNames[m.Item1], m.Item2, "To")) .Timestamp(); var i = mesh .Where(m => Interesting(m.Item2)) .Where(m => stateMachine.EndpointUrisToNames.ContainsKey(m.Item1)) .Select(m => Tuple.Create(stateMachine.EndpointUrisToNames[m.Item1], m.Item2, "From")) .Timestamp(); i .Merge(o) .Subscribe(m => { try { lock (Global.lastMessages) { var lastMessages = Global.lastMessages[serviceName]; lastMessages.Enqueue(m); while (lastMessages.Count > 1000) { lastMessages.Dequeue(); } } } catch { } }); var enabled = false; var enabledState = container.GetBlobReference(serviceName + "EnabledState.txt"); try { enabled = Boolean.Parse(enabledState.DownloadText()); } catch { } mesh.enabled = enabled; return stateMachine; } else { throw new ArgumentException("Location not found"); } } static string GetConfigurationSettingValueIfPresent(string setting) { try { return RoleEnvironment.GetConfigurationSettingValue(setting); } catch (RoleEnvironmentException) { return null; } } static bool Interesting(Message m) { if (m is Message.Gossip) { return false; } if (m is Message.Query) { return false; } if (m is Message.Initiate<string, SerialilzableWebRequest>) { return false; } if (m is Message.RejectionHint<string>) { return false; } var p = m as Message.Propose<string, SerialilzableWebRequest>; if (p != null) { return p.proposal is ProposalConfiguration<string>; } var a = m as Message.Accepted<string, SerialilzableWebRequest>; if (a != null) { return a.proposal is ProposalConfiguration<string>; } var l = m as Message.Learn<string, SerialilzableWebRequest>; if (l != null) { return l.proposal is ProposalConfiguration<string>; } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; namespace System.Collections.Immutable { /// <summary> /// A thin wrapper around the <see cref="IDictionary{TKey, TValue}.Keys"/> or <see cref="IDictionary{TKey, TValue}.Values"/> enumerators so they look like a collection. /// </summary> /// <typeparam name="TKey">The type of key in the dictionary.</typeparam> /// <typeparam name="TValue">The type of value in the dictionary.</typeparam> /// <typeparam name="T">Either TKey or TValue.</typeparam> internal abstract class KeysOrValuesCollectionAccessor<TKey, TValue, T> : ICollection<T>, ICollection { /// <summary> /// The underlying wrapped dictionary. /// </summary> private readonly IImmutableDictionary<TKey, TValue> _dictionary; /// <summary> /// The key or value enumerable that this instance wraps. /// </summary> private readonly IEnumerable<T> _keysOrValues; /// <summary> /// Initializes a new instance of the <see cref="KeysOrValuesCollectionAccessor{TKey, TValue, T}"/> class. /// </summary> /// <param name="dictionary">The dictionary to base on.</param> /// <param name="keysOrValues">The keys or values enumeration to wrap as a collection.</param> protected KeysOrValuesCollectionAccessor(IImmutableDictionary<TKey, TValue> dictionary, IEnumerable<T> keysOrValues) { Requires.NotNull(dictionary, "dictionary"); Requires.NotNull(keysOrValues, "keysOrValues"); _dictionary = dictionary; _keysOrValues = keysOrValues; } /// <summary> /// See <see cref="ICollection{T}"/> /// </summary> public bool IsReadOnly { get { return true; } } /// <summary> /// See <see cref="ICollection{T}"/> /// </summary> /// <returns>The number of elements contained in the <see cref="ICollection{T}"/>.</returns> public int Count { get { return _dictionary.Count; } } /// <summary> /// Gets the wrapped dictionary. /// </summary> protected IImmutableDictionary<TKey, TValue> Dictionary { get { return _dictionary; } } /// <summary> /// See <see cref="ICollection{T}"/> /// </summary> public void Add(T item) { throw new NotSupportedException(); } /// <summary> /// See <see cref="ICollection{T}"/> /// </summary> public void Clear() { throw new NotSupportedException(); } /// <summary> /// See <see cref="ICollection{T}"/> /// </summary> public abstract bool Contains(T item); /// <summary> /// See <see cref="ICollection{T}"/> /// </summary> public void CopyTo(T[] array, int arrayIndex) { Requires.NotNull(array, "array"); Requires.Range(arrayIndex >= 0, "arrayIndex"); Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex"); foreach (T item in this) { array[arrayIndex++] = item; } } /// <summary> /// See <see cref="ICollection{T}"/> /// </summary> public bool Remove(T item) { throw new NotSupportedException(); } /// <summary> /// See <see cref="IEnumerable{T}"/> /// </summary> public IEnumerator<T> GetEnumerator() { return _keysOrValues.GetEnumerator(); } /// <summary> /// See <see cref="System.Collections.IEnumerable"/> /// </summary> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param> void ICollection.CopyTo(Array array, int arrayIndex) { Requires.NotNull(array, "array"); Requires.Range(arrayIndex >= 0, "arrayIndex"); Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex"); foreach (T item in this) { array.SetValue(item, arrayIndex++); } } /// <summary> /// Gets a value indicating whether access to the <see cref="ICollection"/> is synchronized (thread safe). /// </summary> /// <returns>true if access to the <see cref="ICollection"/> is synchronized (thread safe); otherwise, false.</returns> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection.IsSynchronized { get { return true; } } /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="ICollection"/>. /// </summary> /// <returns>An object that can be used to synchronize access to the <see cref="ICollection"/>.</returns> [DebuggerBrowsable(DebuggerBrowsableState.Never)] object ICollection.SyncRoot { get { return this; } } } /// <summary> /// A lightweight collection view over and IEnumerable of keys. /// </summary> internal class KeysCollectionAccessor<TKey, TValue> : KeysOrValuesCollectionAccessor<TKey, TValue, TKey> { /// <summary> /// Initializes a new instance of the <see cref="KeysCollectionAccessor{TKey, TValue}"/> class. /// </summary> internal KeysCollectionAccessor(IImmutableDictionary<TKey, TValue> dictionary) : base(dictionary, dictionary.Keys) { } /// <summary> /// See <see cref="ICollection{T}"/> /// </summary> public override bool Contains(TKey item) { return this.Dictionary.ContainsKey(item); } } /// <summary> /// A lightweight collection view over and IEnumerable of values. /// </summary> internal class ValuesCollectionAccessor<TKey, TValue> : KeysOrValuesCollectionAccessor<TKey, TValue, TValue> { /// <summary> /// Initializes a new instance of the <see cref="ValuesCollectionAccessor{TKey, TValue}"/> class. /// </summary> internal ValuesCollectionAccessor(IImmutableDictionary<TKey, TValue> dictionary) : base(dictionary, dictionary.Values) { } /// <summary> /// See <see cref="ICollection{T}"/> /// </summary> public override bool Contains(TValue item) { var sortedDictionary = this.Dictionary as ImmutableSortedDictionary<TKey, TValue>; if (sortedDictionary != null) { return sortedDictionary.ContainsValue(item); } var dictionary = this.Dictionary as IImmutableDictionaryInternal<TKey, TValue>; if (dictionary != null) { return dictionary.ContainsValue(item); } throw new NotSupportedException(); } } }
// 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.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Xml; using System.Collections.Generic; using System.Xml.Serialization; using System.Security; #if !NET_NATIVE using ExtensionDataObject = System.Object; #endif namespace System.Runtime.Serialization { #if USE_REFEMIT || NET_NATIVE public class XmlObjectSerializerWriteContext : XmlObjectSerializerContext #else internal class XmlObjectSerializerWriteContext : XmlObjectSerializerContext #endif { private ObjectReferenceStack _byValObjectsInScope = new ObjectReferenceStack(); private XmlSerializableWriter _xmlSerializableWriter; private const int depthToCheckCyclicReference = 512; private ObjectToIdCache _serializedObjects; private bool _isGetOnlyCollection; private readonly bool _unsafeTypeForwardingEnabled; protected bool serializeReadOnlyTypes; protected bool preserveObjectReferences; internal static XmlObjectSerializerWriteContext CreateContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) { return (serializer.PreserveObjectReferences || serializer.SerializationSurrogateProvider != null) ? new XmlObjectSerializerWriteContextComplex(serializer, rootTypeDataContract, dataContractResolver) : new XmlObjectSerializerWriteContext(serializer, rootTypeDataContract, dataContractResolver); } protected XmlObjectSerializerWriteContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver resolver) : base(serializer, rootTypeDataContract, resolver) { this.serializeReadOnlyTypes = serializer.SerializeReadOnlyTypes; // Known types restricts the set of types that can be deserialized _unsafeTypeForwardingEnabled = true; } internal XmlObjectSerializerWriteContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject) : base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject) { // Known types restricts the set of types that can be deserialized _unsafeTypeForwardingEnabled = true; } #if USE_REFEMIT || NET_NATIVE internal ObjectToIdCache SerializedObjects #else protected ObjectToIdCache SerializedObjects #endif { get { if (_serializedObjects == null) _serializedObjects = new ObjectToIdCache(); return _serializedObjects; } } internal override bool IsGetOnlyCollection { get { return _isGetOnlyCollection; } set { _isGetOnlyCollection = value; } } internal bool SerializeReadOnlyTypes { get { return this.serializeReadOnlyTypes; } } internal bool UnsafeTypeForwardingEnabled { get { return _unsafeTypeForwardingEnabled; } } #if USE_REFEMIT public void StoreIsGetOnlyCollection() #else internal void StoreIsGetOnlyCollection() #endif { _isGetOnlyCollection = true; } #if USE_REFEMIT public void InternalSerializeReference(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle) #else internal void InternalSerializeReference(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle) #endif { if (!OnHandleReference(xmlWriter, obj, true /*canContainCyclicReference*/)) InternalSerialize(xmlWriter, obj, isDeclaredType, writeXsiType, declaredTypeID, declaredTypeHandle); OnEndHandleReference(xmlWriter, obj, true /*canContainCyclicReference*/); } #if USE_REFEMIT public virtual void InternalSerialize(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle) #else internal virtual void InternalSerialize(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle) #endif { if (writeXsiType) { Type declaredType = Globals.TypeOfObject; SerializeWithXsiType(xmlWriter, obj, obj.GetType().TypeHandle, null/*type*/, -1, declaredType.TypeHandle, declaredType); } else if (isDeclaredType) { DataContract contract = GetDataContract(declaredTypeID, declaredTypeHandle); SerializeWithoutXsiType(contract, xmlWriter, obj, declaredTypeHandle); } else { RuntimeTypeHandle objTypeHandle = obj.GetType().TypeHandle; if (declaredTypeHandle.GetHashCode() == objTypeHandle.GetHashCode()) // semantically the same as Value == Value; Value is not available in SL { DataContract dataContract = (declaredTypeID >= 0) ? GetDataContract(declaredTypeID, declaredTypeHandle) : GetDataContract(declaredTypeHandle, null /*type*/); SerializeWithoutXsiType(dataContract, xmlWriter, obj, declaredTypeHandle); } else { SerializeWithXsiType(xmlWriter, obj, objTypeHandle, null /*type*/, declaredTypeID, declaredTypeHandle, Type.GetTypeFromHandle(declaredTypeHandle)); } } } internal void SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle declaredTypeHandle) { if (OnHandleIsReference(xmlWriter, dataContract, obj)) return; if (dataContract.KnownDataContracts != null) { scopedKnownTypes.Push(dataContract.KnownDataContracts); WriteDataContractValue(dataContract, xmlWriter, obj, declaredTypeHandle); scopedKnownTypes.Pop(); } else { WriteDataContractValue(dataContract, xmlWriter, obj, declaredTypeHandle); } } internal virtual void SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType) { bool verifyKnownType = false; Type declaredType = rootTypeDataContract.UnderlyingType; if (declaredType.GetTypeInfo().IsInterface && CollectionDataContract.IsCollectionInterface(declaredType)) { if (DataContractResolver != null) { WriteResolvedTypeInfo(xmlWriter, graphType, declaredType); } } else if (!declaredType.IsArray) //Array covariance is not supported in XSD. If declared type is array do not write xsi:type. Instead write xsi:type for each item { verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, rootTypeDataContract); } SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, originalDeclaredTypeHandle, declaredType); } protected virtual void SerializeWithXsiType(XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType) { bool verifyKnownType = false; #if !NET_NATIVE DataContract dataContract; if (declaredType.GetTypeInfo().IsInterface && CollectionDataContract.IsCollectionInterface(declaredType)) { dataContract = GetDataContractSkipValidation(DataContract.GetId(objectTypeHandle), objectTypeHandle, objectType); if (OnHandleIsReference(xmlWriter, dataContract, obj)) return; dataContract = GetDataContract(declaredTypeHandle, declaredType); #else DataContract dataContract = DataContract.GetDataContract(declaredType); if (dataContract.TypeIsInterface && dataContract.TypeIsCollectionInterface) { if (OnHandleIsReference(xmlWriter, dataContract, obj)) return; if (this.Mode == SerializationMode.SharedType && dataContract.IsValidContract(this.Mode)) dataContract = dataContract.GetValidContract(this.Mode); else dataContract = GetDataContract(declaredTypeHandle, declaredType); #endif if (!WriteClrTypeInfo(xmlWriter, dataContract) && DataContractResolver != null) { if (objectType == null) { objectType = Type.GetTypeFromHandle(objectTypeHandle); } WriteResolvedTypeInfo(xmlWriter, objectType, declaredType); } } else if (declaredType.IsArray)//Array covariance is not supported in XSD. If declared type is array do not write xsi:type. Instead write xsi:type for each item { // A call to OnHandleIsReference is not necessary here -- arrays cannot be IsReference dataContract = GetDataContract(objectTypeHandle, objectType); WriteClrTypeInfo(xmlWriter, dataContract); dataContract = GetDataContract(declaredTypeHandle, declaredType); } else { dataContract = GetDataContract(objectTypeHandle, objectType); if (OnHandleIsReference(xmlWriter, dataContract, obj)) return; if (!WriteClrTypeInfo(xmlWriter, dataContract)) { DataContract declaredTypeContract = (declaredTypeID >= 0) ? GetDataContract(declaredTypeID, declaredTypeHandle) : GetDataContract(declaredTypeHandle, declaredType); verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, declaredTypeContract); } } SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, declaredTypeHandle, declaredType); } internal bool OnHandleIsReference(XmlWriterDelegator xmlWriter, DataContract contract, object obj) { if (preserveObjectReferences || !contract.IsReference || _isGetOnlyCollection) { return false; } bool isNew = true; int objectId = SerializedObjects.GetId(obj, ref isNew); _byValObjectsInScope.EnsureSetAsIsReference(obj); if (isNew) { xmlWriter.WriteAttributeString(Globals.SerPrefix, DictionaryGlobals.IdLocalName, DictionaryGlobals.SerializationNamespace, string.Format(CultureInfo.InvariantCulture, "{0}{1}", "i", objectId)); return false; } else { xmlWriter.WriteAttributeString(Globals.SerPrefix, DictionaryGlobals.RefLocalName, DictionaryGlobals.SerializationNamespace, string.Format(CultureInfo.InvariantCulture, "{0}{1}", "i", objectId)); return true; } } protected void SerializeAndVerifyType(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, bool verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type declaredType) { bool knownTypesAddedInCurrentScope = false; if (dataContract.KnownDataContracts != null) { scopedKnownTypes.Push(dataContract.KnownDataContracts); knownTypesAddedInCurrentScope = true; } #if !NET_NATIVE if (verifyKnownType) { if (!IsKnownType(dataContract, declaredType)) { DataContract knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/); if (knownContract == null || knownContract.UnderlyingType != dataContract.UnderlyingType) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace))); } } } #endif WriteDataContractValue(dataContract, xmlWriter, obj, declaredTypeHandle); if (knownTypesAddedInCurrentScope) { scopedKnownTypes.Pop(); } } internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, DataContract dataContract) { return false; } internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, string clrTypeName, string clrAssemblyName) { return false; } internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, string clrTypeName, string clrAssemblyName) { return false; } #if USE_REFEMIT || NET_NATIVE public virtual void WriteAnyType(XmlWriterDelegator xmlWriter, object value) #else internal virtual void WriteAnyType(XmlWriterDelegator xmlWriter, object value) #endif { xmlWriter.WriteAnyType(value); } #if USE_REFEMIT || NET_NATIVE public virtual void WriteString(XmlWriterDelegator xmlWriter, string value) #else internal virtual void WriteString(XmlWriterDelegator xmlWriter, string value) #endif { xmlWriter.WriteString(value); } #if USE_REFEMIT || NET_NATIVE public virtual void WriteString(XmlWriterDelegator xmlWriter, string value, XmlDictionaryString name, XmlDictionaryString ns) #else internal virtual void WriteString(XmlWriterDelegator xmlWriter, string value, XmlDictionaryString name, XmlDictionaryString ns) #endif { if (value == null) WriteNull(xmlWriter, typeof(string), true/*isMemberTypeSerializable*/, name, ns); else { xmlWriter.WriteStartElementPrimitive(name, ns); xmlWriter.WriteString(value); xmlWriter.WriteEndElementPrimitive(); } } #if USE_REFEMIT || NET_NATIVE public virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value) #else internal virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value) #endif { xmlWriter.WriteBase64(value); } #if USE_REFEMIT || NET_NATIVE public virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value, XmlDictionaryString name, XmlDictionaryString ns) #else internal virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value, XmlDictionaryString name, XmlDictionaryString ns) #endif { if (value == null) WriteNull(xmlWriter, typeof(byte[]), true/*isMemberTypeSerializable*/, name, ns); else { xmlWriter.WriteStartElementPrimitive(name, ns); xmlWriter.WriteBase64(value); xmlWriter.WriteEndElementPrimitive(); } } #if USE_REFEMIT || NET_NATIVE public virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value) #else internal virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value) #endif { xmlWriter.WriteUri(value); } #if USE_REFEMIT || NET_NATIVE public virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value, XmlDictionaryString name, XmlDictionaryString ns) #else internal virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value, XmlDictionaryString name, XmlDictionaryString ns) #endif { if (value == null) WriteNull(xmlWriter, typeof(Uri), true/*isMemberTypeSerializable*/, name, ns); else { xmlWriter.WriteStartElementPrimitive(name, ns); xmlWriter.WriteUri(value); xmlWriter.WriteEndElementPrimitive(); } } #if USE_REFEMIT || NET_NATIVE public virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value) #else internal virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value) #endif { xmlWriter.WriteQName(value); } #if USE_REFEMIT || NET_NATIVE public virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value, XmlDictionaryString name, XmlDictionaryString ns) #else internal virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value, XmlDictionaryString name, XmlDictionaryString ns) #endif { if (value == null) WriteNull(xmlWriter, typeof(XmlQualifiedName), true/*isMemberTypeSerializable*/, name, ns); else { if (ns != null && ns.Value != null && ns.Value.Length > 0) xmlWriter.WriteStartElement(Globals.ElementPrefix, name, ns); else xmlWriter.WriteStartElement(name, ns); xmlWriter.WriteQName(value); xmlWriter.WriteEndElement(); } } internal void HandleGraphAtTopLevel(XmlWriterDelegator writer, object obj, DataContract contract) { writer.WriteXmlnsAttribute(Globals.XsiPrefix, DictionaryGlobals.SchemaInstanceNamespace); OnHandleReference(writer, obj, true /*canContainReferences*/); } internal virtual bool OnHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference) { if (xmlWriter.depth < depthToCheckCyclicReference) return false; if (canContainCyclicReference) { if (_byValObjectsInScope.Contains(obj)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotSerializeObjectWithCycles, DataContract.GetClrTypeFullName(obj.GetType())))); _byValObjectsInScope.Push(obj); } return false; } internal virtual void OnEndHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference) { if (xmlWriter.depth < depthToCheckCyclicReference) return; if (canContainCyclicReference) { _byValObjectsInScope.Pop(obj); } } #if USE_REFEMIT public void WriteNull(XmlWriterDelegator xmlWriter, Type memberType, bool isMemberTypeSerializable) #else internal void WriteNull(XmlWriterDelegator xmlWriter, Type memberType, bool isMemberTypeSerializable) #endif { CheckIfTypeSerializable(memberType, isMemberTypeSerializable); WriteNull(xmlWriter); } internal void WriteNull(XmlWriterDelegator xmlWriter, Type memberType, bool isMemberTypeSerializable, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteStartElement(name, ns); WriteNull(xmlWriter, memberType, isMemberTypeSerializable); xmlWriter.WriteEndElement(); } #if USE_REFEMIT public void IncrementArrayCount(XmlWriterDelegator xmlWriter, Array array) #else internal void IncrementArrayCount(XmlWriterDelegator xmlWriter, Array array) #endif { IncrementCollectionCount(xmlWriter, array.GetLength(0)); } #if USE_REFEMIT public void IncrementCollectionCount(XmlWriterDelegator xmlWriter, ICollection collection) #else internal void IncrementCollectionCount(XmlWriterDelegator xmlWriter, ICollection collection) #endif { IncrementCollectionCount(xmlWriter, collection.Count); } #if USE_REFEMIT public void IncrementCollectionCountGeneric<T>(XmlWriterDelegator xmlWriter, ICollection<T> collection) #else internal void IncrementCollectionCountGeneric<T>(XmlWriterDelegator xmlWriter, ICollection<T> collection) #endif { IncrementCollectionCount(xmlWriter, collection.Count); } private void IncrementCollectionCount(XmlWriterDelegator xmlWriter, int size) { IncrementItemCount(size); WriteArraySize(xmlWriter, size); } internal virtual void WriteArraySize(XmlWriterDelegator xmlWriter, int size) { } #if USE_REFEMIT public static bool IsMemberTypeSameAsMemberValue(object obj, Type memberType) #else internal static bool IsMemberTypeSameAsMemberValue(object obj, Type memberType) #endif { if (obj == null || memberType == null) return false; return obj.GetType().TypeHandle.Equals(memberType.TypeHandle); } #if USE_REFEMIT public static T GetDefaultValue<T>() #else internal static T GetDefaultValue<T>() #endif { return default(T); } #if USE_REFEMIT public static T GetNullableValue<T>(Nullable<T> value) where T : struct #else internal static T GetNullableValue<T>(Nullable<T> value) where T : struct #endif { // value.Value will throw if hasValue is false return value.Value; } #if USE_REFEMIT public static void ThrowRequiredMemberMustBeEmitted(string memberName, Type type) #else internal static void ThrowRequiredMemberMustBeEmitted(string memberName, Type type) #endif { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(SR.RequiredMemberMustBeEmitted, memberName, type.FullName))); } #if USE_REFEMIT public static bool GetHasValue<T>(Nullable<T> value) where T : struct #else internal static bool GetHasValue<T>(Nullable<T> value) where T : struct #endif { return value.HasValue; } internal void WriteIXmlSerializable(XmlWriterDelegator xmlWriter, object obj) { if (_xmlSerializableWriter == null) _xmlSerializableWriter = new XmlSerializableWriter(); WriteIXmlSerializable(xmlWriter, obj, _xmlSerializableWriter); } internal static void WriteRootIXmlSerializable(XmlWriterDelegator xmlWriter, object obj) { WriteIXmlSerializable(xmlWriter, obj, new XmlSerializableWriter()); } private static void WriteIXmlSerializable(XmlWriterDelegator xmlWriter, object obj, XmlSerializableWriter xmlSerializableWriter) { xmlSerializableWriter.BeginWrite(xmlWriter.Writer, obj); IXmlSerializable xmlSerializable = obj as IXmlSerializable; if (xmlSerializable != null) xmlSerializable.WriteXml(xmlSerializableWriter); else { XmlElement xmlElement = obj as XmlElement; if (xmlElement != null) xmlElement.WriteTo(xmlSerializableWriter); else { XmlNode[] xmlNodes = obj as XmlNode[]; if (xmlNodes != null) foreach (XmlNode xmlNode in xmlNodes) xmlNode.WriteTo(xmlSerializableWriter); else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.UnknownXmlType, DataContract.GetClrTypeFullName(obj.GetType())))); } } xmlSerializableWriter.EndWrite(); } protected virtual void WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle declaredTypeHandle) { dataContract.WriteXmlValue(xmlWriter, obj, this); } protected virtual void WriteNull(XmlWriterDelegator xmlWriter) { XmlObjectSerializer.WriteNull(xmlWriter); } private void WriteResolvedTypeInfo(XmlWriterDelegator writer, Type objectType, Type declaredType) { XmlDictionaryString typeName, typeNamespace; if (ResolveType(objectType, declaredType, out typeName, out typeNamespace)) { WriteTypeInfo(writer, typeName, typeNamespace); } } private bool ResolveType(Type objectType, Type declaredType, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace) { if (!DataContractResolver.TryResolveType(objectType, declaredType, KnownTypeResolver, out typeName, out typeNamespace)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ResolveTypeReturnedFalse, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType)))); } if (typeName == null) { if (typeNamespace == null) { return false; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ResolveTypeReturnedNull, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType)))); } } if (typeNamespace == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ResolveTypeReturnedNull, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType)))); } return true; } protected virtual bool WriteTypeInfo(XmlWriterDelegator writer, DataContract contract, DataContract declaredContract) { if (!XmlObjectSerializer.IsContractDeclared(contract, declaredContract)) { if (DataContractResolver == null) { WriteTypeInfo(writer, contract.Name, contract.Namespace); return true; } else { WriteResolvedTypeInfo(writer, contract.OriginalUnderlyingType, declaredContract.OriginalUnderlyingType); return false; } } return false; } protected virtual void WriteTypeInfo(XmlWriterDelegator writer, string dataContractName, string dataContractNamespace) { writer.WriteAttributeQualifiedName(Globals.XsiPrefix, DictionaryGlobals.XsiTypeLocalName, DictionaryGlobals.SchemaInstanceNamespace, dataContractName, dataContractNamespace); } protected virtual void WriteTypeInfo(XmlWriterDelegator writer, XmlDictionaryString dataContractName, XmlDictionaryString dataContractNamespace) { writer.WriteAttributeQualifiedName(Globals.XsiPrefix, DictionaryGlobals.XsiTypeLocalName, DictionaryGlobals.SchemaInstanceNamespace, dataContractName, dataContractNamespace); } #if !NET_NATIVE public void WriteExtensionData(XmlWriterDelegator xmlWriter, ExtensionDataObject extensionData, int memberIndex) { // Needed by the code generator, but not called. } #endif } }
#region license // Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // // DO NOT EDIT THIS FILE! // // This file was generated automatically by astgen.boo. // namespace Boo.Lang.Compiler.Ast { using System.Collections; using System.Runtime.Serialization; [System.Serializable] public partial class Slice : Node { protected Expression _begin; protected Expression _end; protected Expression _step; [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public Slice CloneNode() { return (Slice)Clone(); } /// <summary> /// <see cref="Node.CleanClone"/> /// </summary> [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public Slice CleanClone() { return (Slice)base.CleanClone(); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public NodeType NodeType { get { return NodeType.Slice; } } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public void Accept(IAstVisitor visitor) { visitor.OnSlice(this); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Matches(Node node) { if (node == null) return false; if (NodeType != node.NodeType) return false; var other = ( Slice)node; if (!Node.Matches(_begin, other._begin)) return NoMatch("Slice._begin"); if (!Node.Matches(_end, other._end)) return NoMatch("Slice._end"); if (!Node.Matches(_step, other._step)) return NoMatch("Slice._step"); return true; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Replace(Node existing, Node newNode) { if (base.Replace(existing, newNode)) { return true; } if (_begin == existing) { this.Begin = (Expression)newNode; return true; } if (_end == existing) { this.End = (Expression)newNode; return true; } if (_step == existing) { this.Step = (Expression)newNode; return true; } return false; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public object Clone() { Slice clone = (Slice)FormatterServices.GetUninitializedObject(typeof(Slice)); clone._lexicalInfo = _lexicalInfo; clone._endSourceLocation = _endSourceLocation; clone._documentation = _documentation; clone._isSynthetic = _isSynthetic; clone._entity = _entity; if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone(); if (null != _begin) { clone._begin = _begin.Clone() as Expression; clone._begin.InitializeParent(clone); } if (null != _end) { clone._end = _end.Clone() as Expression; clone._end.InitializeParent(clone); } if (null != _step) { clone._step = _step.Clone() as Expression; clone._step.InitializeParent(clone); } return clone; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override internal void ClearTypeSystemBindings() { _annotations = null; _entity = null; if (null != _begin) { _begin.ClearTypeSystemBindings(); } if (null != _end) { _end.ClearTypeSystemBindings(); } if (null != _step) { _step.ClearTypeSystemBindings(); } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Expression Begin { get { return _begin; } set { if (_begin != value) { _begin = value; if (null != _begin) { _begin.InitializeParent(this); } } } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Expression End { get { return _end; } set { if (_end != value) { _end = value; if (null != _end) { _end.InitializeParent(this); } } } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Expression Step { get { return _step; } set { if (_step != value) { _step = value; if (null != _step) { _step.InitializeParent(this); } } } } } }
#nullable enable using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; using MudBlazor; using System.Text; using System.Threading; using Microsoft.Extensions.Logging; using NLog; using System.Diagnostics; namespace LionFire.Blazor.Components.MudBlazor_ { public partial class AutoRefreshButton { public int Count = 0; #region Parameters [Parameter] public bool Auto { get => auto; set { if (auto == value) return; auto = value; if (auto) { if((DateTimeOffset.UtcNow - LastRefresh).TotalMilliseconds > Interval / 2.0) { Logger.LogInformation("Enabled timer but it hasn't been refreshed recently. Refreshing now."); Refresh().AndForget(); } } } } private bool auto = false; [Parameter] public double Interval { get; set; } = 5000; [Parameter] public Func<Task>? OnRefresh { get; set; } = null; #endregion public string Tooltip { get { var sb = new StringBuilder(); if(LastRefreshElapsed != null) { sb.Append($"Last refresh: {LastRefreshElapsed.ElapsedMilliseconds}ms"); } return sb.ToString(); } } Stopwatch LastRefreshElapsed; #region Initialization protected override Task OnInitializedAsync() { UpdateTimer(); if (Auto && OnRefresh != null) { Refresh().AndForget(); } return base.OnInitializedAsync(); } #endregion #region State protected System.Timers.Timer? Timer { get; set; } protected bool Refreshing => refreshing == 1; volatile int refreshing = 0; DateTimeOffset LastRefresh = default; #region Derived public bool CanRefresh => OnRefresh != null; public bool Errored => Error != null; #endregion public Exception? Error { get => error; set { if (error != value) { error = value; InvokeAsync(StateHasChanged); } } } private Exception? error; #endregion private void UpdateTimer() { if (Auto && !Errored) { Logger.LogTrace($"Enabling timer for {Interval}ms"); if (Timer == null) { Timer = new System.Timers.Timer(); Timer.Elapsed += OnTimer; Timer.AutoReset = false; } else { Timer.Stop(); } Error = null; Timer.Interval = Interval; Timer.Start(); } else { Logger.LogInformation($"Disabling timer{(Errored ? " (ERRORED)" : "")}"); if (Timer != null) { Timer.Stop(); Timer.Elapsed -= OnTimer; Timer.Dispose(); Timer = null; } } } public async Task Refresh() { Count++; if (Interlocked.CompareExchange(ref refreshing, 1, 0) != 0) { Logger.LogWarning("OnTimer: already refreshing. Skipping."); return; } try { if (OnRefresh != null) { var shc = InvokeAsync(StateHasChanged); // Updates Refreshing Task refreshTask; try { LastRefresh = DateTimeOffset.UtcNow; var sw = Stopwatch.StartNew(); refreshTask = InvokeAsync(() => OnRefresh()); await refreshTask.ConfigureAwait(false); sw.Stop(); Logger.LogInformation($"Refresh took {sw.ElapsedMilliseconds}ms"); LastRefreshElapsed = sw; } catch (Exception ex) { Logger.LogError(ex, "[Parameter] OnRefresh() method threw Exception"); Error = ex; } UpdateTimer(); await shc.ConfigureAwait(false); } } finally { refreshing = 0; await InvokeAsync(StateHasChanged); } } private async void OnTimer(object? sender, System.Timers.ElapsedEventArgs args) { try { Logger.LogTrace($"OnTimer"); await Refresh(); } catch (Exception ex) { Logger.LogError(ex, "OnTimer failed"); Error = ex; UpdateTimer(); } } private void OnToggleRefresh() { Auto ^= true; if (!CanRefresh) { Error = new Exception("No handler registered with OnRefresh parameter"); } else { if (Errored) { Logger.LogInformation("Clearing error."); Error = null; } } UpdateTimer(); } private void OnContextMenu() { Logger.LogInformation("OnContextMenu"); } void IDisposable.Dispose() { Auto = false; UpdateTimer(); } } }
#if UNITY_STANDALONE || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX #define COHERENT_UNITY_STANDALONE #endif #if UNITY_EDITOR || COHERENT_UNITY_STANDALONE using UnityEngine; using System.Collections; namespace Coherent.UI { public class IMEHandler : MonoBehaviour { public enum ViewPlane { VP_XpositiveYpositive, VP_XnegativeYpositive, VP_YpositiveZnegative, VP_YpositiveZpositive, VP_XnegativeZpositive, VP_XnegativeZnegative } // Use this for initialization void Start () { m_View = gameObject.GetComponent<CoherentUIView>(); m_View.Listener.ViewCreated += this.OnViewCreated; SubscribeForIMEEvents(); } // Update is called once per frame void Update () { if(m_View.View != null && m_View.ReceivesInput && Input.imeCompositionMode == IMECompositionMode.On) { OnCaretRectChanged( m_LastCaretRectPosX, m_LastCaretRectPosY, m_LastCaretRectWidth, m_LastCaretRectHeight); } } void OnDisable() { m_View.EnableIME = false; var view = m_View.View; if(view == null) { if(m_View.Listener != null) { m_View.Listener.ViewCreated -= this.OnViewCreated; } if(m_View.ReceivesInput) { Input.imeCompositionMode = IMECompositionMode.Off; } } else { view.IMEActivate(false); } UnsubscribeForIMEEvents(); } void OnEnable() { if(m_View == null) { m_View = gameObject.GetComponent<CoherentUIView>(); } m_View.EnableIME = true; var view = m_View.View; if(view == null) { if(m_View.Listener != null) { m_View.Listener.ViewCreated += this.OnViewCreated; } if(m_View.ReceivesInput) { Input.imeCompositionMode = IMECompositionMode.On; } } else { view.IMEActivate(true); } SubscribeForIMEEvents(); } void OnGUI() { View view = m_View.View; Event currentEvent = Event.current; if(!m_View.ReceivesInput && view != null && currentEvent != null && currentEvent.type == EventType.MouseDown) { var mouseEventData = Coherent.UI.InputManager.ProcessMouseEvent( currentEvent); mouseEventData.Type = MouseEventData.EventType.MouseDown; mouseEventData.X = -1; mouseEventData.Y = -1; view.MouseEvent(mouseEventData); } } void OnDestroy() { if(m_View == null) { return; } UnsubscribeForIMEEvents(); } public delegate Vector3 CalculateIMECandidateListPositionHandler( uint x, uint y, uint width, uint height); public CalculateIMECandidateListPositionHandler CalculateIMECandidateListPosition; private void OnViewCreated(View view) { view.IMEActivate(true); } void OnCaretRectChanged(uint x, uint y, uint width, uint height) { m_LastCaretRectPosX = x; m_LastCaretRectPosY = y; m_LastCaretRectWidth = width; m_LastCaretRectHeight = height; if (CalculateIMECandidateListPosition != null) { Input.compositionCursorPos = CalculateIMECandidateListPosition( x, y, width, height); return; } Vector3 caretPosition = new Vector3(); if(gameObject.camera == null) { caretPosition = GetCaretPositionInWorldSpace(x, y); caretPosition = Camera.main.WorldToScreenPoint(caretPosition); caretPosition.y = Screen.height - caretPosition.y; } else { caretPosition.x = x; caretPosition.y = y; caretPosition.z = 0; if(!m_View.UseCameraDimensions) { caretPosition.x *= (gameObject.camera.pixelWidth / m_View.Width); caretPosition.y *= (gameObject.camera.pixelHeight / m_View.Height); } } caretPosition.y += height; Input.compositionCursorPos = caretPosition; } void OnIMEShouldCancelComposition() { Input.imeCompositionMode = IMECompositionMode.Off; } void OnTextInputTypeChanged( TextInputControlType type, bool canComposeInline) { if(type != TextInputControlType.TICT_None && type != TextInputControlType.TICT_Password && canComposeInline && m_View.ReceivesInput) { Input.imeCompositionMode = IMECompositionMode.On; } else { Input.imeCompositionMode = IMECompositionMode.Off; } } private Vector3 GetCaretPositionInWorldSpace(uint x, uint y) { float xRatio = (float)(x) / m_View.Width; float yRatio = 1 - (float)(y) / m_View.Height; Bounds bounds = gameObject.collider.bounds; Vector3 extents = bounds.extents; Vector3 caretPosition = bounds.center - extents; ViewPlane planeOrientation = GetViewPlaneOrientation(); switch(planeOrientation) { case ViewPlane.VP_XpositiveYpositive: caretPosition.x += xRatio * bounds.size.x; caretPosition.y += yRatio * bounds.size.y; break; case ViewPlane.VP_YpositiveZpositive: caretPosition.y += yRatio * bounds.size.y; caretPosition.z += xRatio * bounds.size.z; break; case ViewPlane.VP_XnegativeZnegative: caretPosition.x += (1 - xRatio) * bounds.size.x; caretPosition.z += (1 - yRatio) * bounds.size.z; break; case ViewPlane.VP_XnegativeYpositive: caretPosition.x += (1 - xRatio) * bounds.size.x; caretPosition.y += yRatio * bounds.size.y; break; case ViewPlane.VP_YpositiveZnegative: caretPosition.y += yRatio * bounds.size.y; caretPosition.z += (1 - xRatio) * bounds.size.z; break; case ViewPlane.VP_XnegativeZpositive: caretPosition.x += (1 - xRatio) * bounds.size.x; caretPosition.z += yRatio * bounds.size.z; break; } return caretPosition; } private ViewPlane GetViewPlaneOrientation() { MeshCollider meshCollider = gameObject.GetComponent<MeshCollider>(); Vector3 normal = meshCollider.sharedMesh.normals[0]; float xAbs = Mathf.Abs(normal.x); float yAbs = Mathf.Abs(normal.y); float zAbs = Mathf.Abs(normal.z); if(xAbs > yAbs && xAbs > zAbs) { return (normal.x > 0) ? ViewPlane.VP_YpositiveZpositive : ViewPlane.VP_YpositiveZnegative; } if(yAbs > xAbs && yAbs > zAbs) { return (normal.y > 0) ? ViewPlane.VP_XnegativeZnegative : ViewPlane.VP_XnegativeZpositive; } return (normal.z > 0) ? ViewPlane.VP_XnegativeYpositive : ViewPlane.VP_XpositiveYpositive; } private void SubscribeForIMEEvents() { if(m_View.Listener != null && !m_SubscribedForEvents) { m_View.Listener.CaretRectChanged += this.OnCaretRectChanged; m_View.Listener.TextInputTypeChanged += this.OnTextInputTypeChanged; m_View.Listener.IMEShouldCancelComposition += this.OnIMEShouldCancelComposition; m_SubscribedForEvents = true; } } private void UnsubscribeForIMEEvents() { if(m_View.Listener != null && m_SubscribedForEvents) { m_View.Listener.CaretRectChanged -= this.OnCaretRectChanged; m_View.Listener.TextInputTypeChanged -= this.OnTextInputTypeChanged; m_View.Listener.IMEShouldCancelComposition -= this.OnIMEShouldCancelComposition; m_SubscribedForEvents = false; } } private uint m_LastCaretRectPosX = 0; private uint m_LastCaretRectPosY = 0; private uint m_LastCaretRectWidth = 0; private uint m_LastCaretRectHeight = 0; private CoherentUIView m_View; bool m_SubscribedForEvents = false; } } #endif
#region License /* The MIT License * * Copyright (c) 2011 Red Badger Consulting * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion namespace RedBadger.Xpf { using System; using System.Diagnostics; using RedBadger.Xpf.Internal; /// <summary> /// A structure representing a Rectangle in 2D space /// </summary> [DebuggerDisplay("{X}, {Y} : {Width} x {Height}")] public struct Rect : IEquatable<Rect> { /// <summary> /// The Height of the <see cref = "Rect">Rect</see>. /// </summary> public double Height; /// <summary> /// The Width of the <see cref = "Rect">Rect</see>. /// </summary> public double Width; /// <summary> /// The X coordinate of the top left corner of the <see cref = "Rect">Rect</see>. /// </summary> public double X; /// <summary> /// The Y coordinate of the top left corner of the <see cref = "Rect">Rect</see>. /// </summary> public double Y; static Rect() { Empty = new Rect { X = double.PositiveInfinity, Y = double.PositiveInfinity, Width = double.NegativeInfinity, Height = double.NegativeInfinity }; } /// <summary> /// Initializes a new <see cref = "Rect">Rect</see> struct from a <see cref = "Size">Size</see>. /// </summary> /// <param name = "size">The <see cref = "Size">Size</see> of the <see cref = "Rect">Rect</see>.</param> public Rect(Size size) : this(new Point(), size) { } /// <summary> /// Initializes a new <see cref = "Rect">Rect</see> struct from a <see cref = "Point">Point</see> and a <see cref = "Size">Size</see>. /// </summary> /// <param name = "position">The position of the top left corner of the <see cref = "Rect">Rect</see>.</param> /// <param name = "size">The <see cref = "Size">Size</see> of the <see cref = "Rect">Rect</see>.</param> public Rect(Point position, Size size) : this(position.X, position.Y, size.Width, size.Height) { } /// <summary> /// Initializes a new <see cref = "Rect">Rect</see> struct with the specified coordinates, width and height. /// </summary> /// <param name = "x">The x-coordinate of the top left corner of the <see cref = "Rect">Rect</see>.</param> /// <param name = "y">The y-coordinate of the top left corner of the <see cref = "Rect">Rect</see>.</param> /// <param name = "width">The width of the <see cref = "Rect">Rect</see>.</param> /// <param name = "height">The height of the <see cref = "Rect">Rect</see>.</param> public Rect(double x, double y, double width, double height) { if (width < 0d || height < 0d) { throw new ArgumentException("width and height cannot be negative"); } this.X = x; this.Y = y; this.Width = width; this.Height = height; } /// <summary> /// Initializes a new <see cref = "Rect">Rect</see> that is just large enough to encompass the two specified <see cref = "Point">Point</see>s. /// </summary> /// <param name = "point1">The first <see cref = "Point">Point</see> to encompass.</param> /// <param name = "point2">The second <see cref = "Point">Point</see> to encompass.</param> public Rect(Point point1, Point point2) { this.X = Math.Min(point1.X, point2.X); this.Y = Math.Min(point1.Y, point2.Y); this.Width = (Math.Max(point1.X, point2.X) - this.X).EnsurePositive(); this.Height = (Math.Max(point1.Y, point2.Y) - this.Y).EnsurePositive(); } /// <summary> /// An empty <see cref = "Rect">Rect</see>. Empty Rects have positive infinity coordinates and negative infinity size. /// </summary> public static Rect Empty { get; private set; } /// <summary> /// Gets the bottom side of the <see cref = "Rect">Rect</see>. /// </summary> public double Bottom { get { if (this.IsEmpty) { return double.NegativeInfinity; } return this.Y + this.Height; } } /// <summary> /// Determines if the <see cref = "Rect">Rect</see> is empty - i.e. has positive infinity coordinates and negative infinity size. /// </summary> public bool IsEmpty { get { return this.Width < 0d; } } /// <summary> /// Gets the left side of the <see cref = "Rect">Rect</see>. /// </summary> public double Left { get { return this.X; } } /// <summary> /// Gets the location of the top left corner of the <see cref = "Rect">Rect</see> in 2D space. /// </summary> public Point Location { get { return new Point(this.X, this.Y); } } /// <summary> /// Gets the right side of the <see cref = "Rect">Rect</see>. /// </summary> public double Right { get { if (this.IsEmpty) { return double.NegativeInfinity; } return this.X + this.Width; } } /// <summary> /// Gets the size of the <see cref = "Rect">Rect</see>. /// </summary> public Size Size { get { return new Size(this.Width, this.Height); } } /// <summary> /// Gets the top side of the <see cref = "Rect">Rect</see>. /// </summary> public double Top { get { return this.Y; } } /// <summary> /// Compares two <see cref = "Rect">Rect</see>s for equality. /// </summary> /// <param name = "left">The left <see cref = "Rect">Rect</see>.</param> /// <param name = "right">The right <see cref = "Rect">Rect</see>.</param> /// <returns>true if the two <see cref = "Rect">Rect</see>s are equal.</returns> public static bool operator ==(Rect left, Rect right) { return left.Equals(right); } /// <summary> /// Compares two <see cref = "Rect">Rect</see>s for inequality. /// </summary> /// <param name = "left">The left <see cref = "Rect">Rect</see>.</param> /// <param name = "right">The right <see cref = "Rect">Rect</see>.</param> /// <returns>true if the two <see cref = "Rect">Rect</see>s are not equal.</returns> public static bool operator !=(Rect left, Rect right) { return !left.Equals(right); } /// <summary> /// Tests if the <see cref = "Rect">Rect</see> contains the specified <see cref = "Point">Point</see>. /// </summary> /// <param name = "point">The <see cref = "Point">Point</see> to test.</param> /// <returns>True if the <see cref = "Rect">Rect</see> contains the specified <see cref = "Point">Point</see>.</returns> public bool Contains(Point point) { return this.Contains(point.X, point.Y); } /// <summary> /// Tests if the <see cref = "Rect">Rect</see> contains the point described by the specified x and y coordinates. /// </summary> /// <param name = "x">The x coordinate of the point.</param> /// <param name = "y">The y coordinate of the point.</param> /// <returns>True if the <see cref = "Rect">Rect</see> contains the point described by the specified x and y coordinates.</returns> public bool Contains(double x, double y) { if (this.IsEmpty) { return false; } return x >= this.X && x - this.Width <= this.X && y >= this.Y && y - this.Height <= this.Y; } /// <summary> /// Displaces this instance of the <see cref = "Rect">Rect</see> by the specified <see cref = "Vector">Vector</see>. /// </summary> /// <param name = "vector">The <see cref = "Vector">Vector</see> by which to displace the <see cref = "Rect">Rect</see>.</param> public void Displace(Vector vector) { if (!this.IsEmpty) { this.X += vector.X; this.Y += vector.Y; } } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (obj.GetType() != typeof(Rect)) { return false; } return this.Equals((Rect)obj); } public override int GetHashCode() { if (this.IsEmpty) { return 0; } unchecked { int result = this.Height.GetHashCode(); result = (result * 397) ^ this.Width.GetHashCode(); result = (result * 397) ^ this.X.GetHashCode(); result = (result * 397) ^ this.Y.GetHashCode(); return result; } } /// <summary> /// Changes this <see cref = "Rect">Rect</see> so that it represents its intersection with the specified Rect. /// If intersection does not occur, this Rect will become <see cref = "Empty">Empty</see>. /// </summary> /// <param name = "rect">The <see cref = "Rect">Rect</see> to intersect with.</param> public void Intersect(Rect rect) { if (!this.IntersectsWith(rect)) { this = Empty; } else { double x = Math.Max(this.X, rect.X); double y = Math.Max(this.Y, rect.Y); this.Width = (Math.Min(this.X + this.Width, rect.X + rect.Width) - x).EnsurePositive(); this.Height = (Math.Min(this.Y + this.Height, rect.Y + rect.Height) - y).EnsurePositive(); this.X = x; this.Y = y; } } /// <summary> /// Tests whether this <see cref = "Rect">Rect</see> instersects with the specified Rect. /// </summary> /// <param name = "rect">The <see cref = "Rect">Rect</see> to intersect with.</param> /// <returns>True if this <see cref = "Rect">Rect</see> instersects with the specified Rect.</returns> public bool IntersectsWith(Rect rect) { if (this.IsEmpty || rect.IsEmpty) { return false; } return (((rect.X <= (this.X + this.Width)) && ((rect.X + rect.Width) >= this.X)) && (rect.Y <= (this.Y + this.Height))) && ((rect.Y + rect.Height) >= this.Y); } public override string ToString() { return string.Format("{0}, {1} : {2} x {3}", this.X, this.Y, this.Width, this.Height); } /// <summary> /// Expands this <see cref = "Rect">Rect</see> to encompass the specified Rect. /// </summary> /// <param name = "rect">The <see cref = "Rect">Rect</see> to encompass.</param> public void Union(Rect rect) { if (this.IsEmpty) { this = rect; } else if (!rect.IsEmpty) { double x = Math.Min(this.Left, rect.Left); double y = Math.Min(this.Top, rect.Top); this.Width = rect.Width == double.PositiveInfinity || this.Width == double.PositiveInfinity ? double.PositiveInfinity : (Math.Max(this.Right, rect.Right) - x).EnsurePositive(); this.Height = rect.Height == double.PositiveInfinity || this.Height == double.PositiveInfinity ? double.PositiveInfinity : (Math.Max(this.Bottom, rect.Bottom) - y).EnsurePositive(); this.X = x; this.Y = y; } } /// <summary> /// Expands this <see cref = "Rect">Rect</see> to encompass the specified <see cref = "Point">Point</see>. /// </summary> /// <param name = "point">The <see cref = "Point">Point</see> to include.</param> public void Union(Point point) { this.Union(new Rect(point, point)); } public bool Equals(Rect other) { if (other.IsEmpty) { return this.IsEmpty; } return other.Height.IsCloseTo(this.Height) && other.Width.IsCloseTo(this.Width) && other.X.IsCloseTo(this.X) && other.Y.IsCloseTo(this.Y); } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Text; using System.Diagnostics; namespace AgreementTrac { class CDealInfo { // ATDealInfo Fields private SqlConnection m_SqlConn = null; private Guid m_guidDealIdx; private string m_sComputerName = string.Empty; private string m_sIPAddress = string.Empty; private string m_sManagerName = string.Empty; private string m_sDealNumber = string.Empty; private string m_sDealershipName = string.Empty; private DateTime m_dtTransactionDate; private bool m_bVscChecked = false; private bool m_bAHChecked = false; private bool m_bEtchChecked = false; private bool m_bGapChecked = false; private bool m_bMaintChecked = false; private string m_sNotes = string.Empty; public CCustInfo customerInfo = null; public CVehicleInfo vehicleInfo = null; public CVideoInfo videoInfo = null; public CDealInfo(string sConnString, string sManagerName, string sDatabaseName) { m_guidDealIdx = Guid.NewGuid(); m_sManagerName = sManagerName; m_SqlConn = new SqlConnection(sConnString); Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tCreating CCustInfo object."); customerInfo = new CCustInfo(); Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tCCustInfo object created successfully."); Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tCreating CVehicle object."); vehicleInfo = new CVehicleInfo(); Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tCVehicle object created successfully."); Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tCreating CVideoInfo object."); videoInfo = new CVideoInfo(); Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tCVideoInfo object created successfully."); } public string ExecuteSQLInserts(string sDatabaseName) { string sResult = string.Empty; Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "Entered ExecuteSQLInserts() method."); try { // Open the connection and switch to correct database Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tOpen SQL Connection."); m_SqlConn.Open(); Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tSQL Connection opened successfully."); Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tChanging database context to :" + sDatabaseName); m_SqlConn.ChangeDatabase(sDatabaseName); Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tDatabase change successful."); // ATCustInfo Insert Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tStarting Insert to ATCustInfo table."); string strInsertQuery; strInsertQuery = "INSERT INTO ATCustInfo (CustomerIdx,FName,LName,Address,City,State,Zip,Phone)\n" + "VALUES(@CustomerIdx, @FName, @LName, @Address, @City, @State, @Zip, @Phone);"; SqlCommand sqlCommand = new SqlCommand(strInsertQuery, m_SqlConn); // Add the parameters sqlCommand.Parameters.AddWithValue("@CustomerIdx", customerInfo.CustomerIdx); sqlCommand.Parameters.AddWithValue("@FName", customerInfo.FirstName); sqlCommand.Parameters.AddWithValue("@LName", customerInfo.LastName); sqlCommand.Parameters.AddWithValue("@Address", customerInfo.Address); sqlCommand.Parameters.AddWithValue("@City", customerInfo.City); sqlCommand.Parameters.AddWithValue("@State", customerInfo.State); sqlCommand.Parameters.AddWithValue("@Zip", customerInfo.Zip); sqlCommand.Parameters.AddWithValue("@Phone", customerInfo.Phone); sqlCommand.ExecuteScalar(); // execute the query Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tInsert to ATCustInfo table successful."); // ATVehicleInfo Insert Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tStarting Insert to ATVehicleInfo table."); sqlCommand.CommandText = "INSERT INTO ATVehicleInfo(VehicleIdx,StockNo,Make,Model,VehYear,Vin)\n" + "VALUES(@VehicleIdx, @StockNo, @Make, @Model, @VehYear, @Vin);"; sqlCommand.Parameters.AddWithValue("@VehicleIdx", vehicleInfo.VehicleIdx); sqlCommand.Parameters.AddWithValue("@StockNo", vehicleInfo.StockNumber); sqlCommand.Parameters.AddWithValue("@Make", vehicleInfo.Make); sqlCommand.Parameters.AddWithValue("@Model", vehicleInfo.Model); sqlCommand.Parameters.AddWithValue("@VehYear", vehicleInfo.Year); sqlCommand.Parameters.AddWithValue("@Vin", vehicleInfo.VIN); sqlCommand.ExecuteNonQuery(); // execute the query Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tInsert to ATVehicleInfo table successful."); // ATVideoInfo Insert Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tStarting Insert to ATVideoInfo table."); sqlCommand.CommandText = "INSERT INTO ATVideoInfo(VideoIdx, vidFileLength, vidSaveDir, vidFileName, vidFileSize)\n" + "VALUES(@VideoIdx, @vidFileLength, @vidSaveDir, @vidFileName, @vidFileSize);"; sqlCommand.Parameters.AddWithValue("@VideoIdx", videoInfo.VideoIdx); sqlCommand.Parameters.AddWithValue("@vidFileLength", videoInfo.VidFileLength); sqlCommand.Parameters.AddWithValue("@vidSaveDir", videoInfo.VidSaveDir); sqlCommand.Parameters.AddWithValue("@vidFileName", videoInfo.VidFileName); sqlCommand.Parameters.AddWithValue("@vidFileSize", videoInfo.VidFileSize); sqlCommand.ExecuteNonQuery(); // execute the query Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tInsert to ATVideoInfo table successful."); // ATDealInfo Insert Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tStarting Insert to ATDealInfo table."); sqlCommand.CommandText = "INSERT INTO ATDealInfo(DealIdx, ComputerName, DealershipName, TransactionDate, IPAddress, MgrName, CustomerIdx, VideoIdx, VehicleIdx, DealNumber,\n" + "VSC, AH, ETCH, GAP, MAINT, Notes) VALUES (@DealIdx, @ComputerName, @DealershipName, @TransactionDate, @IPAddress, @MgrName, @CustomerIdxFK, @VideoIdxFK, @VehicleIdxFK,\n" + "@DealNumber, @VSC, @AH, @ETCH, @GAP, @MAINT, @Notes);"; sqlCommand.Parameters.AddWithValue("@DealIdx", this.m_guidDealIdx); sqlCommand.Parameters.AddWithValue("@ComputerName", this.ComputerName); sqlCommand.Parameters.AddWithValue("@DealershipName", this.DealershipName); sqlCommand.Parameters.AddWithValue("@TransactionDate", this.TransactionDate); sqlCommand.Parameters.AddWithValue("@IPAddress", this.IP_Address); sqlCommand.Parameters.AddWithValue("@MgrName", this.m_sManagerName); sqlCommand.Parameters.AddWithValue("@CustomerIdxFK", customerInfo.CustomerIdx); sqlCommand.Parameters.AddWithValue("@VideoIdxFK", videoInfo.VideoIdx); sqlCommand.Parameters.AddWithValue("@VehicleIdxFK", vehicleInfo.VehicleIdx); sqlCommand.Parameters.AddWithValue("@DealNumber", this.DealNumber); sqlCommand.Parameters.AddWithValue("@VSC", Convert.ToInt32(this.VSC)); sqlCommand.Parameters.AddWithValue("@AH", Convert.ToInt32(this.AH)); sqlCommand.Parameters.AddWithValue("@ETCH", Convert.ToInt32(this.ETCH)); sqlCommand.Parameters.AddWithValue("@GAP", Convert.ToInt32(this.GAP)); sqlCommand.Parameters.AddWithValue("@MAINT", Convert.ToInt32(this.MAINT)); sqlCommand.Parameters.AddWithValue("@Notes", this.Notes); sqlCommand.ExecuteNonQuery(); sResult = "Save Successful."; Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tInsert to ATDealInfo table successful."); } catch (Exception ex) { Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tError occurred during inserts. Message text: " + ex.Message); sResult = ex.Message; } finally { m_SqlConn.Close(); } Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "Exiting ExecuteSQLInserts() method."); return sResult; } #region Public Properties public string DealNumber { get { return m_sDealNumber; } set { m_sDealNumber = value; } } public string DealershipName { get { return m_sDealershipName; } set { m_sDealershipName = value; } } public DateTime TransactionDate { get { return m_dtTransactionDate; } set { m_dtTransactionDate = value; } } public string Notes { get { return m_sNotes; } set { m_sNotes = value; } } public bool VSC { get { return m_bVscChecked; } set { m_bVscChecked = value; } } public bool AH { get { return m_bAHChecked; } set { m_bAHChecked = value; } } public bool ETCH { get { return m_bEtchChecked; } set { m_bEtchChecked = value; } } public bool GAP { get { return m_bGapChecked; } set { m_bGapChecked = value; } } public bool MAINT { get { return m_bMaintChecked; } set { m_bMaintChecked = value; } } // System Information properties public string ComputerName { get { return m_sComputerName; } set { m_sComputerName = value; } } public string IP_Address { get { return m_sIPAddress; } set { m_sIPAddress = value; } } #endregion } }
using System; using System.Diagnostics; using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Math.EC { public abstract class ECFieldElement { public abstract BigInteger ToBigInteger(); public abstract string FieldName { get; } public abstract int FieldSize { get; } public abstract ECFieldElement Add(ECFieldElement b); public abstract ECFieldElement Subtract(ECFieldElement b); public abstract ECFieldElement Multiply(ECFieldElement b); public abstract ECFieldElement Divide(ECFieldElement b); public abstract ECFieldElement Negate(); public abstract ECFieldElement Square(); public abstract ECFieldElement Invert(); public abstract ECFieldElement Sqrt(); public override bool Equals( object obj) { if (obj == this) return true; ECFieldElement other = obj as ECFieldElement; if (other == null) return false; return Equals(other); } protected bool Equals( ECFieldElement other) { return ToBigInteger().Equals(other.ToBigInteger()); } public override int GetHashCode() { return ToBigInteger().GetHashCode(); } public override string ToString() { return this.ToBigInteger().ToString(2); } } public class FpFieldElement : ECFieldElement { private readonly BigInteger q, x; public FpFieldElement( BigInteger q, BigInteger x) { if (x.CompareTo(q) >= 0) throw new ArgumentException("x value too large in field element"); this.q = q; this.x = x; } public override BigInteger ToBigInteger() { return x; } /** * return the field name for this field. * * @return the string "Fp". */ public override string FieldName { get { return "Fp"; } } public override int FieldSize { get { return q.BitLength; } } public BigInteger Q { get { return q; } } public override ECFieldElement Add( ECFieldElement b) { return new FpFieldElement(q, x.Add(b.ToBigInteger()).Mod(q)); } public override ECFieldElement Subtract( ECFieldElement b) { return new FpFieldElement(q, x.Subtract(b.ToBigInteger()).Mod(q)); } public override ECFieldElement Multiply( ECFieldElement b) { return new FpFieldElement(q, x.Multiply(b.ToBigInteger()).Mod(q)); } public override ECFieldElement Divide( ECFieldElement b) { return new FpFieldElement(q, x.Multiply(b.ToBigInteger().ModInverse(q)).Mod(q)); } public override ECFieldElement Negate() { return new FpFieldElement(q, x.Negate().Mod(q)); } public override ECFieldElement Square() { return new FpFieldElement(q, x.Multiply(x).Mod(q)); } public override ECFieldElement Invert() { return new FpFieldElement(q, x.ModInverse(q)); } // D.1.4 91 /** * return a sqrt root - the routine verifies that the calculation * returns the right value - if none exists it returns null. */ public override ECFieldElement Sqrt() { if (!q.TestBit(0)) throw Platform.CreateNotImplementedException("even value of q"); // p mod 4 == 3 if (q.TestBit(1)) { // TODO Can this be optimised (inline the Square?) // z = g^(u+1) + p, p = 4u + 3 ECFieldElement z = new FpFieldElement(q, x.ModPow(q.ShiftRight(2).Add(BigInteger.One), q)); return this.Equals(z.Square()) ? z : null; } // p mod 4 == 1 BigInteger qMinusOne = q.Subtract(BigInteger.One); BigInteger legendreExponent = qMinusOne.ShiftRight(1); if (!(x.ModPow(legendreExponent, q).Equals(BigInteger.One))) return null; BigInteger u = qMinusOne.ShiftRight(2); BigInteger k = u.ShiftLeft(1).Add(BigInteger.One); BigInteger Q = this.x; BigInteger fourQ = Q.ShiftLeft(2).Mod(q); BigInteger U, V; do { Random rand = new Random(); BigInteger P; do { P = new BigInteger(q.BitLength, rand); } while (P.CompareTo(q) >= 0 || !(P.Multiply(P).Subtract(fourQ).ModPow(legendreExponent, q).Equals(qMinusOne))); BigInteger[] result = fastLucasSequence(q, P, Q, k); U = result[0]; V = result[1]; if (V.Multiply(V).Mod(q).Equals(fourQ)) { // Integer division by 2, mod q if (V.TestBit(0)) { V = V.Add(q); } V = V.ShiftRight(1); Debug.Assert(V.Multiply(V).Mod(q).Equals(x)); return new FpFieldElement(q, V); } } while (U.Equals(BigInteger.One) || U.Equals(qMinusOne)); return null; // BigInteger qMinusOne = q.Subtract(BigInteger.One); // // BigInteger legendreExponent = qMinusOne.ShiftRight(1); // if (!(x.ModPow(legendreExponent, q).Equals(BigInteger.One))) // return null; // // Random rand = new Random(); // BigInteger fourX = x.ShiftLeft(2); // // BigInteger r; // do // { // r = new BigInteger(q.BitLength, rand); // } // while (r.CompareTo(q) >= 0 // || !(r.Multiply(r).Subtract(fourX).ModPow(legendreExponent, q).Equals(qMinusOne))); // // BigInteger n1 = qMinusOne.ShiftRight(2); // BigInteger n2 = n1.Add(BigInteger.One); // // BigInteger wOne = WOne(r, x, q); // BigInteger wSum = W(n1, wOne, q).Add(W(n2, wOne, q)).Mod(q); // BigInteger twoR = r.ShiftLeft(1); // // BigInteger root = twoR.ModPow(q.Subtract(BigInteger.Two), q) // .Multiply(x).Mod(q) // .Multiply(wSum).Mod(q); // // return new FpFieldElement(q, root); } // private static BigInteger W(BigInteger n, BigInteger wOne, BigInteger p) // { // if (n.Equals(BigInteger.One)) // return wOne; // // bool isEven = !n.TestBit(0); // n = n.ShiftRight(1); // if (isEven) // { // BigInteger w = W(n, wOne, p); // return w.Multiply(w).Subtract(BigInteger.Two).Mod(p); // } // BigInteger w1 = W(n.Add(BigInteger.One), wOne, p); // BigInteger w2 = W(n, wOne, p); // return w1.Multiply(w2).Subtract(wOne).Mod(p); // } // // private BigInteger WOne(BigInteger r, BigInteger x, BigInteger p) // { // return r.Multiply(r).Multiply(x.ModPow(q.Subtract(BigInteger.Two), q)).Subtract(BigInteger.Two).Mod(p); // } private static BigInteger[] fastLucasSequence( BigInteger p, BigInteger P, BigInteger Q, BigInteger k) { // TODO Research and apply "common-multiplicand multiplication here" int n = k.BitLength; int s = k.GetLowestSetBit(); Debug.Assert(k.TestBit(s)); BigInteger Uh = BigInteger.One; BigInteger Vl = BigInteger.Two; BigInteger Vh = P; BigInteger Ql = BigInteger.One; BigInteger Qh = BigInteger.One; for (int j = n - 1; j >= s + 1; --j) { Ql = Ql.Multiply(Qh).Mod(p); if (k.TestBit(j)) { Qh = Ql.Multiply(Q).Mod(p); Uh = Uh.Multiply(Vh).Mod(p); Vl = Vh.Multiply(Vl).Subtract(P.Multiply(Ql)).Mod(p); Vh = Vh.Multiply(Vh).Subtract(Qh.ShiftLeft(1)).Mod(p); } else { Qh = Ql; Uh = Uh.Multiply(Vl).Subtract(Ql).Mod(p); Vh = Vh.Multiply(Vl).Subtract(P.Multiply(Ql)).Mod(p); Vl = Vl.Multiply(Vl).Subtract(Ql.ShiftLeft(1)).Mod(p); } } Ql = Ql.Multiply(Qh).Mod(p); Qh = Ql.Multiply(Q).Mod(p); Uh = Uh.Multiply(Vl).Subtract(Ql).Mod(p); Vl = Vh.Multiply(Vl).Subtract(P.Multiply(Ql)).Mod(p); Ql = Ql.Multiply(Qh).Mod(p); for (int j = 1; j <= s; ++j) { Uh = Uh.Multiply(Vl).Mod(p); Vl = Vl.Multiply(Vl).Subtract(Ql.ShiftLeft(1)).Mod(p); Ql = Ql.Multiply(Ql).Mod(p); } return new BigInteger[]{ Uh, Vl }; } // private static BigInteger[] verifyLucasSequence( // BigInteger p, // BigInteger P, // BigInteger Q, // BigInteger k) // { // BigInteger[] actual = fastLucasSequence(p, P, Q, k); // BigInteger[] plus1 = fastLucasSequence(p, P, Q, k.Add(BigInteger.One)); // BigInteger[] plus2 = fastLucasSequence(p, P, Q, k.Add(BigInteger.Two)); // // BigInteger[] check = stepLucasSequence(p, P, Q, actual, plus1); // // Debug.Assert(check[0].Equals(plus2[0])); // Debug.Assert(check[1].Equals(plus2[1])); // // return actual; // } // // private static BigInteger[] stepLucasSequence( // BigInteger p, // BigInteger P, // BigInteger Q, // BigInteger[] backTwo, // BigInteger[] backOne) // { // return new BigInteger[] // { // P.Multiply(backOne[0]).Subtract(Q.Multiply(backTwo[0])).Mod(p), // P.Multiply(backOne[1]).Subtract(Q.Multiply(backTwo[1])).Mod(p) // }; // } public override bool Equals( object obj) { if (obj == this) return true; FpFieldElement other = obj as FpFieldElement; if (other == null) return false; return Equals(other); } protected bool Equals( FpFieldElement other) { return q.Equals(other.q) && base.Equals(other); } public override int GetHashCode() { return q.GetHashCode() ^ base.GetHashCode(); } } // /** // * Class representing the Elements of the finite field // * <code>F<sub>2<sup>m</sup></sub></code> in polynomial basis (PB) // * representation. Both trinomial (Tpb) and pentanomial (Ppb) polynomial // * basis representations are supported. Gaussian normal basis (GNB) // * representation is not supported. // */ // public class F2mFieldElement // : ECFieldElement // { // /** // * Indicates gaussian normal basis representation (GNB). Number chosen // * according to X9.62. GNB is not implemented at present. // */ // public const int Gnb = 1; // // /** // * Indicates trinomial basis representation (Tpb). Number chosen // * according to X9.62. // */ // public const int Tpb = 2; // // /** // * Indicates pentanomial basis representation (Ppb). Number chosen // * according to X9.62. // */ // public const int Ppb = 3; // // /** // * Tpb or Ppb. // */ // private int representation; // // /** // * The exponent <code>m</code> of <code>F<sub>2<sup>m</sup></sub></code>. // */ // private int m; // // /** // * Tpb: The integer <code>k</code> where <code>x<sup>m</sup> + // * x<sup>k</sup> + 1</code> represents the reduction polynomial // * <code>f(z)</code>.<br/> // * Ppb: The integer <code>k1</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br/> // */ // private int k1; // // /** // * Tpb: Always set to <code>0</code><br/> // * Ppb: The integer <code>k2</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br/> // */ // private int k2; // // /** // * Tpb: Always set to <code>0</code><br/> // * Ppb: The integer <code>k3</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br/> // */ // private int k3; // // /** // * Constructor for Ppb. // * @param m The exponent <code>m</code> of // * <code>F<sub>2<sup>m</sup></sub></code>. // * @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>. // * @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>. // * @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>. // * @param x The BigInteger representing the value of the field element. // */ // public F2mFieldElement( // int m, // int k1, // int k2, // int k3, // BigInteger x) // : base(x) // { // if ((k2 == 0) && (k3 == 0)) // { // this.representation = Tpb; // } // else // { // if (k2 >= k3) // throw new ArgumentException("k2 must be smaller than k3"); // if (k2 <= 0) // throw new ArgumentException("k2 must be larger than 0"); // // this.representation = Ppb; // } // // if (x.SignValue < 0) // throw new ArgumentException("x value cannot be negative"); // // this.m = m; // this.k1 = k1; // this.k2 = k2; // this.k3 = k3; // } // // /** // * Constructor for Tpb. // * @param m The exponent <code>m</code> of // * <code>F<sub>2<sup>m</sup></sub></code>. // * @param k The integer <code>k</code> where <code>x<sup>m</sup> + // * x<sup>k</sup> + 1</code> represents the reduction // * polynomial <code>f(z)</code>. // * @param x The BigInteger representing the value of the field element. // */ // public F2mFieldElement( // int m, // int k, // BigInteger x) // : this(m, k, 0, 0, x) // { // // Set k1 to k, and set k2 and k3 to 0 // } // // public override string FieldName // { // get { return "F2m"; } // } // // /** // * Checks, if the ECFieldElements <code>a</code> and <code>b</code> // * are elements of the same field <code>F<sub>2<sup>m</sup></sub></code> // * (having the same representation). // * @param a field element. // * @param b field element to be compared. // * @throws ArgumentException if <code>a</code> and <code>b</code> // * are not elements of the same field // * <code>F<sub>2<sup>m</sup></sub></code> (having the same // * representation). // */ // public static void CheckFieldElements( // ECFieldElement a, // ECFieldElement b) // { // if (!(a is F2mFieldElement) || !(b is F2mFieldElement)) // { // throw new ArgumentException("Field elements are not " // + "both instances of F2mFieldElement"); // } // // if ((a.x.SignValue < 0) || (b.x.SignValue < 0)) // { // throw new ArgumentException( // "x value may not be negative"); // } // // F2mFieldElement aF2m = (F2mFieldElement)a; // F2mFieldElement bF2m = (F2mFieldElement)b; // // if ((aF2m.m != bF2m.m) || (aF2m.k1 != bF2m.k1) // || (aF2m.k2 != bF2m.k2) || (aF2m.k3 != bF2m.k3)) // { // throw new ArgumentException("Field elements are not " // + "elements of the same field F2m"); // } // // if (aF2m.representation != bF2m.representation) // { // // Should never occur // throw new ArgumentException( // "One of the field " // + "elements are not elements has incorrect representation"); // } // } // // /** // * Computes <code>z * a(z) mod f(z)</code>, where <code>f(z)</code> is // * the reduction polynomial of <code>this</code>. // * @param a The polynomial <code>a(z)</code> to be multiplied by // * <code>z mod f(z)</code>. // * @return <code>z * a(z) mod f(z)</code> // */ // private BigInteger multZModF( // BigInteger a) // { // // Left-shift of a(z) // BigInteger az = a.ShiftLeft(1); // if (az.TestBit(this.m)) // { // // If the coefficient of z^m in a(z) Equals 1, reduction // // modulo f(z) is performed: Add f(z) to to a(z): // // Step 1: Unset mth coeffient of a(z) // az = az.ClearBit(this.m); // // // Step 2: Add r(z) to a(z), where r(z) is defined as // // f(z) = z^m + r(z), and k1, k2, k3 are the positions of // // the non-zero coefficients in r(z) // az = az.FlipBit(0); // az = az.FlipBit(this.k1); // if (this.representation == Ppb) // { // az = az.FlipBit(this.k2); // az = az.FlipBit(this.k3); // } // } // return az; // } // // public override ECFieldElement Add( // ECFieldElement b) // { // // No check performed here for performance reasons. Instead the // // elements involved are checked in ECPoint.F2m // // checkFieldElements(this, b); // if (b.x.SignValue == 0) // return this; // // return new F2mFieldElement(this.m, this.k1, this.k2, this.k3, this.x.Xor(b.x)); // } // // public override ECFieldElement Subtract( // ECFieldElement b) // { // // Addition and subtraction are the same in F2m // return Add(b); // } // // public override ECFieldElement Multiply( // ECFieldElement b) // { // // Left-to-right shift-and-add field multiplication in F2m // // Input: Binary polynomials a(z) and b(z) of degree at most m-1 // // Output: c(z) = a(z) * b(z) mod f(z) // // // No check performed here for performance reasons. Instead the // // elements involved are checked in ECPoint.F2m // // checkFieldElements(this, b); // BigInteger az = this.x; // BigInteger bz = b.x; // BigInteger cz; // // // Compute c(z) = a(z) * b(z) mod f(z) // if (az.TestBit(0)) // { // cz = bz; // } // else // { // cz = BigInteger.Zero; // } // // for (int i = 1; i < this.m; i++) // { // // b(z) := z * b(z) mod f(z) // bz = multZModF(bz); // // if (az.TestBit(i)) // { // // If the coefficient of x^i in a(z) Equals 1, b(z) is added // // to c(z) // cz = cz.Xor(bz); // } // } // return new F2mFieldElement(m, this.k1, this.k2, this.k3, cz); // } // // // public override ECFieldElement Divide( // ECFieldElement b) // { // // There may be more efficient implementations // ECFieldElement bInv = b.Invert(); // return Multiply(bInv); // } // // public override ECFieldElement Negate() // { // // -x == x holds for all x in F2m // return this; // } // // public override ECFieldElement Square() // { // // Naive implementation, can probably be speeded up using modular // // reduction // return Multiply(this); // } // // public override ECFieldElement Invert() // { // // Inversion in F2m using the extended Euclidean algorithm // // Input: A nonzero polynomial a(z) of degree at most m-1 // // Output: a(z)^(-1) mod f(z) // // // u(z) := a(z) // BigInteger uz = this.x; // if (uz.SignValue <= 0) // { // throw new ArithmeticException("x is zero or negative, " + // "inversion is impossible"); // } // // // v(z) := f(z) // BigInteger vz = BigInteger.One.ShiftLeft(m); // vz = vz.SetBit(0); // vz = vz.SetBit(this.k1); // if (this.representation == Ppb) // { // vz = vz.SetBit(this.k2); // vz = vz.SetBit(this.k3); // } // // // g1(z) := 1, g2(z) := 0 // BigInteger g1z = BigInteger.One; // BigInteger g2z = BigInteger.Zero; // // // while u != 1 // while (uz.SignValue != 0) // { // // j := deg(u(z)) - deg(v(z)) // int j = uz.BitLength - vz.BitLength; // // // If j < 0 then: u(z) <-> v(z), g1(z) <-> g2(z), j := -j // if (j < 0) // { // BigInteger uzCopy = uz; // uz = vz; // vz = uzCopy; // // BigInteger g1zCopy = g1z; // g1z = g2z; // g2z = g1zCopy; // // j = -j; // } // // // u(z) := u(z) + z^j * v(z) // // Note, that no reduction modulo f(z) is required, because // // deg(u(z) + z^j * v(z)) <= max(deg(u(z)), j + deg(v(z))) // // = max(deg(u(z)), deg(u(z)) - deg(v(z)) + deg(v(z)) // // = deg(u(z)) // uz = uz.Xor(vz.ShiftLeft(j)); // // // g1(z) := g1(z) + z^j * g2(z) // g1z = g1z.Xor(g2z.ShiftLeft(j)); // // if (g1z.BitLength() > this.m) { // // throw new ArithmeticException( // // "deg(g1z) >= m, g1z = " + g1z.ToString(2)); // // } // } // return new F2mFieldElement(this.m, this.k1, this.k2, this.k3, g2z); // } // // public override ECFieldElement Sqrt() // { // throw new ArithmeticException("Not implemented"); // } // // /** // * @return the representation of the field // * <code>F<sub>2<sup>m</sup></sub></code>, either of // * {@link F2mFieldElement.Tpb} (trinomial // * basis representation) or // * {@link F2mFieldElement.Ppb} (pentanomial // * basis representation). // */ // public int Representation // { // get { return this.representation; } // } // // /** // * @return the degree <code>m</code> of the reduction polynomial // * <code>f(z)</code>. // */ // public int M // { // get { return this.m; } // } // // /** // * @return Tpb: The integer <code>k</code> where <code>x<sup>m</sup> + // * x<sup>k</sup> + 1</code> represents the reduction polynomial // * <code>f(z)</code>.<br/> // * Ppb: The integer <code>k1</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br/> // */ // public int K1 // { // get { return this.k1; } // } // // /** // * @return Tpb: Always returns <code>0</code><br/> // * Ppb: The integer <code>k2</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br/> // */ // public int K2 // { // get { return this.k2; } // } // // /** // * @return Tpb: Always set to <code>0</code><br/> // * Ppb: The integer <code>k3</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br/> // */ // public int K3 // { // get { return this.k3; } // } // // public override bool Equals( // object obj) // { // if (obj == this) // return true; // // F2mFieldElement other = obj as F2mFieldElement; // // if (other == null) // return false; // // return Equals(other); // } // // protected bool Equals( // F2mFieldElement other) // { // return m == other.m // && k1 == other.k1 // && k2 == other.k2 // && k3 == other.k3 // && representation == other.representation // && base.Equals(other); // } // // public override int GetHashCode() // { // return base.GetHashCode() ^ m ^ k1 ^ k2 ^ k3; // } // } /** * Class representing the Elements of the finite field * <code>F<sub>2<sup>m</sup></sub></code> in polynomial basis (PB) * representation. Both trinomial (Tpb) and pentanomial (Ppb) polynomial * basis representations are supported. Gaussian normal basis (GNB) * representation is not supported. */ public class F2mFieldElement : ECFieldElement { /** * Indicates gaussian normal basis representation (GNB). Number chosen * according to X9.62. GNB is not implemented at present. */ public const int Gnb = 1; /** * Indicates trinomial basis representation (Tpb). Number chosen * according to X9.62. */ public const int Tpb = 2; /** * Indicates pentanomial basis representation (Ppb). Number chosen * according to X9.62. */ public const int Ppb = 3; /** * Tpb or Ppb. */ private int representation; /** * The exponent <code>m</code> of <code>F<sub>2<sup>m</sup></sub></code>. */ private int m; /** * Tpb: The integer <code>k</code> where <code>x<sup>m</sup> + * x<sup>k</sup> + 1</code> represents the reduction polynomial * <code>f(z)</code>.<br/> * Ppb: The integer <code>k1</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br/> */ private int k1; /** * Tpb: Always set to <code>0</code><br/> * Ppb: The integer <code>k2</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br/> */ private int k2; /** * Tpb: Always set to <code>0</code><br/> * Ppb: The integer <code>k3</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br/> */ private int k3; /** * The <code>IntArray</code> holding the bits. */ private IntArray x; /** * The number of <code>int</code>s required to hold <code>m</code> bits. */ private readonly int t; /** * Constructor for Ppb. * @param m The exponent <code>m</code> of * <code>F<sub>2<sup>m</sup></sub></code>. * @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>. * @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>. * @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>. * @param x The BigInteger representing the value of the field element. */ public F2mFieldElement( int m, int k1, int k2, int k3, BigInteger x) { // t = m / 32 rounded up to the next integer this.t = (m + 31) >> 5; this.x = new IntArray(x, t); if ((k2 == 0) && (k3 == 0)) { this.representation = Tpb; } else { if (k2 >= k3) throw new ArgumentException("k2 must be smaller than k3"); if (k2 <= 0) throw new ArgumentException("k2 must be larger than 0"); this.representation = Ppb; } if (x.SignValue < 0) throw new ArgumentException("x value cannot be negative"); this.m = m; this.k1 = k1; this.k2 = k2; this.k3 = k3; } /** * Constructor for Tpb. * @param m The exponent <code>m</code> of * <code>F<sub>2<sup>m</sup></sub></code>. * @param k The integer <code>k</code> where <code>x<sup>m</sup> + * x<sup>k</sup> + 1</code> represents the reduction * polynomial <code>f(z)</code>. * @param x The BigInteger representing the value of the field element. */ public F2mFieldElement( int m, int k, BigInteger x) : this(m, k, 0, 0, x) { // Set k1 to k, and set k2 and k3 to 0 } private F2mFieldElement(int m, int k1, int k2, int k3, IntArray x) { t = (m + 31) >> 5; this.x = x; this.m = m; this.k1 = k1; this.k2 = k2; this.k3 = k3; if ((k2 == 0) && (k3 == 0)) { this.representation = Tpb; } else { this.representation = Ppb; } } public override BigInteger ToBigInteger() { return x.ToBigInteger(); } public override string FieldName { get { return "F2m"; } } public override int FieldSize { get { return m; } } /** * Checks, if the ECFieldElements <code>a</code> and <code>b</code> * are elements of the same field <code>F<sub>2<sup>m</sup></sub></code> * (having the same representation). * @param a field element. * @param b field element to be compared. * @throws ArgumentException if <code>a</code> and <code>b</code> * are not elements of the same field * <code>F<sub>2<sup>m</sup></sub></code> (having the same * representation). */ public static void CheckFieldElements( ECFieldElement a, ECFieldElement b) { if (!(a is F2mFieldElement) || !(b is F2mFieldElement)) { throw new ArgumentException("Field elements are not " + "both instances of F2mFieldElement"); } F2mFieldElement aF2m = (F2mFieldElement)a; F2mFieldElement bF2m = (F2mFieldElement)b; if ((aF2m.m != bF2m.m) || (aF2m.k1 != bF2m.k1) || (aF2m.k2 != bF2m.k2) || (aF2m.k3 != bF2m.k3)) { throw new ArgumentException("Field elements are not " + "elements of the same field F2m"); } if (aF2m.representation != bF2m.representation) { // Should never occur throw new ArgumentException( "One of the field " + "elements are not elements has incorrect representation"); } } public override ECFieldElement Add( ECFieldElement b) { // No check performed here for performance reasons. Instead the // elements involved are checked in ECPoint.F2m // checkFieldElements(this, b); IntArray iarrClone = (IntArray) this.x.Copy(); F2mFieldElement bF2m = (F2mFieldElement) b; iarrClone.AddShifted(bF2m.x, 0); return new F2mFieldElement(m, k1, k2, k3, iarrClone); } public override ECFieldElement Subtract( ECFieldElement b) { // Addition and subtraction are the same in F2m return Add(b); } public override ECFieldElement Multiply( ECFieldElement b) { // Right-to-left comb multiplication in the IntArray // Input: Binary polynomials a(z) and b(z) of degree at most m-1 // Output: c(z) = a(z) * b(z) mod f(z) // No check performed here for performance reasons. Instead the // elements involved are checked in ECPoint.F2m // checkFieldElements(this, b); F2mFieldElement bF2m = (F2mFieldElement) b; IntArray mult = x.Multiply(bF2m.x, m); mult.Reduce(m, new int[]{k1, k2, k3}); return new F2mFieldElement(m, k1, k2, k3, mult); } public override ECFieldElement Divide( ECFieldElement b) { // There may be more efficient implementations ECFieldElement bInv = b.Invert(); return Multiply(bInv); } public override ECFieldElement Negate() { // -x == x holds for all x in F2m return this; } public override ECFieldElement Square() { IntArray squared = x.Square(m); squared.Reduce(m, new int[]{k1, k2, k3}); return new F2mFieldElement(m, k1, k2, k3, squared); } public override ECFieldElement Invert() { // Inversion in F2m using the extended Euclidean algorithm // Input: A nonzero polynomial a(z) of degree at most m-1 // Output: a(z)^(-1) mod f(z) // u(z) := a(z) IntArray uz = (IntArray)this.x.Copy(); // v(z) := f(z) IntArray vz = new IntArray(t); vz.SetBit(m); vz.SetBit(0); vz.SetBit(this.k1); if (this.representation == Ppb) { vz.SetBit(this.k2); vz.SetBit(this.k3); } // g1(z) := 1, g2(z) := 0 IntArray g1z = new IntArray(t); g1z.SetBit(0); IntArray g2z = new IntArray(t); // while u != 0 while (uz.GetUsedLength() > 0) // while (uz.bitLength() > 1) { // j := deg(u(z)) - deg(v(z)) int j = uz.BitLength - vz.BitLength; // If j < 0 then: u(z) <-> v(z), g1(z) <-> g2(z), j := -j if (j < 0) { IntArray uzCopy = uz; uz = vz; vz = uzCopy; IntArray g1zCopy = g1z; g1z = g2z; g2z = g1zCopy; j = -j; } // u(z) := u(z) + z^j * v(z) // Note, that no reduction modulo f(z) is required, because // deg(u(z) + z^j * v(z)) <= max(deg(u(z)), j + deg(v(z))) // = max(deg(u(z)), deg(u(z)) - deg(v(z)) + deg(v(z)) // = deg(u(z)) // uz = uz.xor(vz.ShiftLeft(j)); // jInt = n / 32 int jInt = j >> 5; // jInt = n % 32 int jBit = j & 0x1F; IntArray vzShift = vz.ShiftLeft(jBit); uz.AddShifted(vzShift, jInt); // g1(z) := g1(z) + z^j * g2(z) // g1z = g1z.xor(g2z.ShiftLeft(j)); IntArray g2zShift = g2z.ShiftLeft(jBit); g1z.AddShifted(g2zShift, jInt); } return new F2mFieldElement(this.m, this.k1, this.k2, this.k3, g2z); } public override ECFieldElement Sqrt() { throw new ArithmeticException("Not implemented"); } /** * @return the representation of the field * <code>F<sub>2<sup>m</sup></sub></code>, either of * {@link F2mFieldElement.Tpb} (trinomial * basis representation) or * {@link F2mFieldElement.Ppb} (pentanomial * basis representation). */ public int Representation { get { return this.representation; } } /** * @return the degree <code>m</code> of the reduction polynomial * <code>f(z)</code>. */ public int M { get { return this.m; } } /** * @return Tpb: The integer <code>k</code> where <code>x<sup>m</sup> + * x<sup>k</sup> + 1</code> represents the reduction polynomial * <code>f(z)</code>.<br/> * Ppb: The integer <code>k1</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br/> */ public int K1 { get { return this.k1; } } /** * @return Tpb: Always returns <code>0</code><br/> * Ppb: The integer <code>k2</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br/> */ public int K2 { get { return this.k2; } } /** * @return Tpb: Always set to <code>0</code><br/> * Ppb: The integer <code>k3</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br/> */ public int K3 { get { return this.k3; } } public override bool Equals( object obj) { if (obj == this) return true; F2mFieldElement other = obj as F2mFieldElement; if (other == null) return false; return Equals(other); } protected bool Equals( F2mFieldElement other) { return m == other.m && k1 == other.k1 && k2 == other.k2 && k3 == other.k3 && representation == other.representation && base.Equals(other); } public override int GetHashCode() { return m.GetHashCode() ^ k1.GetHashCode() ^ k2.GetHashCode() ^ k3.GetHashCode() ^ representation.GetHashCode() ^ base.GetHashCode(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Portions derived from React Native: // Copyright (c) 2015-present, Facebook, Inc. // Licensed under the MIT License. using Facebook.Yoga; using Newtonsoft.Json.Linq; using ReactNative.Reflection; using ReactNative.UIManager; using ReactNative.UIManager.Annotations; using ReactNative.Views.Text; using System; #if WINDOWS_UWP using Windows.Foundation; using Windows.UI.Text; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; #else using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Media; #endif namespace ReactNative.Views.TextInput { /// <summary> /// This extension of <see cref="LayoutShadowNode"/> is responsible for /// measuring the layout for Native <see cref="TextBox"/>. /// </summary> public class ReactTextInputShadowNode : LayoutShadowNode { private const int Unset = -1; private const int DefaultBorderWidth = 2; private static readonly float[] s_defaultPaddings = { 10f, 3f, 6f, 5f, }; private bool _multiline; private bool _autoGrow; private int _letterSpacing; private int _numberOfLines; private double _fontSize = Unset; private double _lineHeight; private double? _maxHeight; private FontStyle? _fontStyle; private FontWeight? _fontWeight; #if WINDOWS_UWP private TextAlignment _textAlignment = TextAlignment.DetectFromContent; #else private TextAlignment _textAlignment = TextAlignment.Left; #endif private string _fontFamily; private string _text; private int _jsEventCount = Unset; /// <summary> /// Instantiates the <see cref="ReactTextInputShadowNode"/>. /// </summary> public ReactTextInputShadowNode() { SetDefaultPadding(EdgeSpacing.Left, s_defaultPaddings[0]); SetDefaultPadding(EdgeSpacing.Top, s_defaultPaddings[1]); SetDefaultPadding(EdgeSpacing.Right, s_defaultPaddings[2]); SetDefaultPadding(EdgeSpacing.Bottom, s_defaultPaddings[3]); SetBorder(EdgeSpacing.All, DefaultBorderWidth); MeasureFunction = (node, width, widthMode, height, heightMode) => MeasureTextInput(this, node, width, widthMode, height, heightMode); } /// <summary> /// Sets the text for the node. /// </summary> /// <param name="text">The text.</param> [ReactProp("text")] public void SetText(string text) { _text = text ?? ""; MarkUpdated(); } /// <summary> /// Sets the font size for the node. /// </summary> /// <param name="fontSize">The font size.</param> [ReactProp(ViewProps.FontSize, DefaultDouble = Unset)] public void SetFontSize(double fontSize) { if (_fontSize != fontSize) { _fontSize = fontSize; MarkUpdated(); } } /// <summary> /// Sets the font family for the node. /// </summary> /// <param name="fontFamily">The font family.</param> [ReactProp(ViewProps.FontFamily)] public void SetFontFamily(string fontFamily) { if (_fontFamily != fontFamily) { _fontFamily = fontFamily; MarkUpdated(); } } /// <summary> /// Sets the font weight for the node. /// </summary> /// <param name="fontWeightValue">The font weight string.</param> [ReactProp(ViewProps.FontWeight)] public void SetFontWeight(string fontWeightValue) { var fontWeight = FontStyleHelpers.ParseFontWeight(fontWeightValue); if (_fontWeight.HasValue != fontWeight.HasValue || (_fontWeight.HasValue && fontWeight.HasValue && #if WINDOWS_UWP _fontWeight.Value.Weight != fontWeight.Value.Weight)) #else _fontWeight.Value.ToOpenTypeWeight() != fontWeight.Value.ToOpenTypeWeight())) #endif { _fontWeight = fontWeight; MarkUpdated(); } } /// <summary> /// Sets the font style for the node. /// </summary> /// <param name="fontStyleValue">The font style string.</param> [ReactProp(ViewProps.FontStyle)] public void SetFontStyle(string fontStyleValue) { var fontStyle = EnumHelpers.ParseNullable<FontStyle>(fontStyleValue); if (_fontStyle != fontStyle) { _fontStyle = fontStyle; MarkUpdated(); } } /// <summary> /// Sets the letter spacing for the node. /// </summary> /// <param name="letterSpacing">The letter spacing.</param> [ReactProp(ViewProps.LetterSpacing)] public void SetLetterSpacing(int letterSpacing) { var spacing = 50*letterSpacing; // TODO: Find exact multiplier (50) to match iOS if (_letterSpacing != spacing) { _letterSpacing = spacing; MarkUpdated(); } } /// <summary> /// Sets the line height. /// </summary> /// <param name="lineHeight">The line height.</param> [ReactProp(ViewProps.LineHeight)] public void SetLineHeight(double lineHeight) { if (_lineHeight != lineHeight) { _lineHeight = lineHeight; MarkUpdated(); } } /// <summary> /// Sets the max height. /// </summary> /// <param name="maxHeight">The max height.</param> [ReactProp(ViewProps.MaxHeight)] public override void SetMaxHeight(JValue maxHeight) { var maxHeightValue = maxHeight.Value<double?>(); if (_maxHeight != maxHeightValue) { _maxHeight = maxHeightValue; MarkUpdated(); } } /// <summary> /// Sets the maximum number of lines. /// </summary> /// <param name="numberOfLines">Max number of lines.</param> [ReactProp(ViewProps.NumberOfLines)] public void SetNumberOfLines(int numberOfLines) { if (_numberOfLines != numberOfLines) { _numberOfLines = numberOfLines; MarkUpdated(); } } /// <summary> /// Sets whether to enable multiline input on the text input. /// </summary> /// <param name="multiline">The multiline flag.</param> [ReactProp("multiline")] public void SetMultiline(bool multiline) { if (_multiline != multiline) { _multiline = multiline; MarkUpdated(); } } /// <summary> /// Sets whether to enable auto-grow on the text input. /// </summary> /// <param name="autoGrow">The auto-grow flag.</param> [ReactProp("autoGrow")] public void SetAutoGrow(bool autoGrow) { if (_autoGrow != autoGrow) { _autoGrow = autoGrow; if (!_autoGrow) { MarkUpdated(); } } } /// <summary> /// Sets the text alignment. /// </summary> /// <param name="textAlign">The text alignment string.</param> [ReactProp(ViewProps.TextAlign)] public void SetTextAlign(string textAlign) { var textAlignment = textAlign == "auto" || textAlign == null ? #if WINDOWS_UWP TextAlignment.DetectFromContent : #else TextAlignment.Left : #endif EnumHelpers.Parse<TextAlignment>(textAlign); if (_textAlignment != textAlignment) { _textAlignment = textAlignment; MarkUpdated(); } } /// <summary> /// Set the most recent event count in JavaScript. /// </summary> /// <param name="mostRecentEventCount">The event count.</param> [ReactProp("mostRecentEventCount")] public void SetMostRecentEventCount(int mostRecentEventCount) { _jsEventCount = mostRecentEventCount; } /// <summary> /// Called to aggregate the current text and event counter. /// </summary> /// <param name="uiViewOperationQueue">The UI operation queue.</param> public override void OnCollectExtraUpdates(UIViewOperationQueue uiViewOperationQueue) { base.OnCollectExtraUpdates(uiViewOperationQueue); var computedPadding = GetComputedPadding(); if (computedPadding != null) { uiViewOperationQueue.EnqueueUpdateExtraData(ReactTag, computedPadding); } if (_jsEventCount != Unset) { uiViewOperationQueue.EnqueueUpdateExtraData(ReactTag, Tuple.Create(_jsEventCount, _text)); } } /// <summary> /// Sets the paddings of the shadow node. /// </summary> /// <param name="index">The spacing type index.</param> /// <param name="padding">The padding value.</param> public override void SetPaddings(int index, JValue padding) { MarkUpdated(); base.SetPaddings(index, padding); } /// <summary> /// Marks a node as updated. /// </summary> protected override void MarkUpdated() { base.MarkUpdated(); dirty(); } private float[] GetComputedPadding() { return new[] { GetPadding(YogaEdge.Left), GetPadding(YogaEdge.Top), GetPadding(YogaEdge.Right), GetPadding(YogaEdge.Bottom), }; } private static YogaSize MeasureTextInput(ReactTextInputShadowNode textInputNode, YogaNode node, float width, YogaMeasureMode widthMode, float height, YogaMeasureMode heightMode) { var normalizedWidth = Math.Max(0, (YogaConstants.IsUndefined(width) ? double.PositiveInfinity : width)); var normalizedHeight = Math.Max(0, (YogaConstants.IsUndefined(height) ? double.PositiveInfinity : height)); var normalizedText = string.IsNullOrEmpty(textInputNode._text) ? " " : textInputNode._text; var textBlock = new TextBlock { Text = normalizedText, TextWrapping = textInputNode._multiline ? TextWrapping.Wrap : TextWrapping.NoWrap, }; ApplyStyles(textInputNode, textBlock); textBlock.Measure(new Size(normalizedWidth, normalizedHeight)); return MeasureOutput.Make( (float)Math.Ceiling(width), (float)Math.Ceiling(textBlock.ActualHeight)); } private static void ApplyStyles(ReactTextInputShadowNode textNode, TextBlock textBlock) { if (textNode._fontSize != Unset) { var fontSize = textNode._fontSize; textBlock.FontSize = fontSize; } if (textNode._fontStyle.HasValue) { var fontStyle = textNode._fontStyle.Value; textBlock.FontStyle = fontStyle; } if (textNode._fontWeight.HasValue) { var fontWeight = textNode._fontWeight.Value; textBlock.FontWeight = fontWeight; } if (textNode._fontFamily != null) { var fontFamily = new FontFamily(textNode._fontFamily); textBlock.FontFamily = fontFamily; } if (textNode._maxHeight.HasValue) { textBlock.MaxHeight = textNode._maxHeight.Value; } } } }
// Copyright 2009-2013 Matvei Stefarov <me@matvei.org> using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Cache; using System.Text; using System.Net.Sockets; using System.Linq; using fCraft.Events; using JetBrains.Annotations; namespace fCraft { /// <summary> Static class responsible for sending heartbeats. </summary> public static class Heartbeat { static readonly Uri ClassiCubeNetUri; /// <summary> Delay between sending heartbeats. Default: 25s </summary> public static TimeSpan Delay { get; set; } /// <summary> Request timeout for heartbeats. Default: 10s </summary> public static TimeSpan Timeout { get; set; } /// <summary> Secret string used to verify players' names. /// Randomly generated at startup. /// Known only to this server, heartbeat servers, and webpanel. </summary> public static string Salt { get; internal set; } /// <summary> Second salt. /// Used if server is running a dual heartbeat</summary> public static string Salt2 { get; internal set; } static Heartbeat() { ClassiCubeNetUri = new Uri("http://www.classicube.net/heartbeat.jsp"); Delay = TimeSpan.FromSeconds(45); Timeout = TimeSpan.FromSeconds(10); Salt = Server.GetRandomString(32); Salt2 = Server.GetRandomString(32); Server.ShutdownBegan += OnServerShutdown; } static void OnServerShutdown(object sender, ShutdownEventArgs e) { if (minecraftNetRequest != null) { minecraftNetRequest.Abort(); } } internal static void Start() { Scheduler.NewBackgroundTask(Beat).RunForever(Delay); } static void Beat(SchedulerTask scheduledTask) { if (Server.IsShuttingDown) return; if (ConfigKey.HeartbeatEnabled.Enabled()) { SendClassiCubeBeat(); HbSave(); } else { // If heartbeats are disabled, the server data is written // to a text file instead (heartbeatdata.txt) string[] data = new[]{ Salt, Server.InternalIP.ToString(), Server.Port.ToString(), Server.CountPlayers( false ).ToString(), ConfigKey.MaxPlayers.GetString(), ConfigKey.ServerName.GetString(), ConfigKey.IsPublic.GetString(), }; const string tempFile = Paths.HeartbeatDataFileName + ".tmp"; File.WriteAllLines(tempFile, data, Encoding.ASCII); Paths.MoveOrReplace(tempFile, Paths.HeartbeatDataFileName); } } static HttpWebRequest minecraftNetRequest; static void SendClassiCubeBeat() { HeartbeatData data = new HeartbeatData(ClassiCubeNetUri); if (!RaiseHeartbeatSendingEvent(data, ClassiCubeNetUri, true)) { return; } minecraftNetRequest = CreateRequest(data.CreateUri(Salt2)); var state = new HeartbeatRequestState(minecraftNetRequest, data, true); minecraftNetRequest.BeginGetResponse(ResponseCallback, state); } // Creates an asynchrnous HTTP request to the given URL static HttpWebRequest CreateRequest(Uri uri) { HttpWebRequest request = HttpUtil.CreateRequest(uri, Timeout); request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.BypassCache); return request; } public static string HbData; public static void HbSave() { try { const string SaverFile = "heartbeatdata.txt"; if (File.Exists(SaverFile)) { File.Delete(SaverFile); } if (Salt == null) return; if (Server.CountPlayers(false).ToString() == null) return; string[] data = new[] { Salt, Server.InternalIP.ToString(), Server.Port.ToString(), Server.CountPlayers( false ).ToString(), ConfigKey.MaxPlayers.GetString(), ConfigKey.ServerName.GetString(), ConfigKey.IsPublic.GetString(), Salt2 }; //"port=" + Server.Port.ToString() + "&max=" + ConfigKey.MaxPlayers.GetString() + "&name=" + //Uri.EscapeDataString(ConfigKey.ServerName.GetString()) + //"&public=True" + "&salt=" + Salt + "&users=" + Server.CountPlayers(false).ToString(); const string tempFile = Paths.HeartbeatDataFileName + ".tmp"; File.WriteAllLines(tempFile, data, Encoding.ASCII); Paths.MoveOrReplace(tempFile, Paths.HeartbeatDataFileName); } catch (Exception ex) { Logger.Log(LogType.Error, "" + ex); } } // Called when the heartbeat server responds. static void ResponseCallback(IAsyncResult result) { if (Server.IsShuttingDown) return; HeartbeatRequestState state = (HeartbeatRequestState)result.AsyncState; try { string responseText; using (HttpWebResponse response = (HttpWebResponse)state.Request.EndGetResponse(result)) { // ReSharper disable AssignNullToNotNullAttribute using (StreamReader responseReader = new StreamReader(response.GetResponseStream())) { // ReSharper restore AssignNullToNotNullAttribute responseText = responseReader.ReadToEnd(); } RaiseHeartbeatSentEvent(state.Data, response, responseText); } // try parse response as server Uri, if needed if (state.GetServerUri) { string replyString = responseText.Trim(); if (replyString.StartsWith("bad heartbeat", StringComparison.OrdinalIgnoreCase)) { Logger.Log(LogType.Error, "Heartbeat: {0}", replyString); } else { try { Uri newUri = new Uri(replyString); Uri oldUri = Server.Uri; if (newUri != oldUri) { Server.Uri = newUri; RaiseUriChangedEvent(oldUri, newUri); } } catch (UriFormatException) { Logger.Log(LogType.Error, "Heartbeat: Server replied with: {0}", replyString); } } } } catch (Exception ex) { if (ex is WebException || ex is IOException) { Logger.Log(LogType.Warning, "Heartbeat: {0} is probably down ({1})", state.Request.RequestUri.Host, ex.Message); } else { Logger.Log(LogType.Error, "Heartbeat: {0}", ex); } } } #region Events /// <summary> Occurs when a heartbeat is about to be sent (cancellable). </summary> public static event EventHandler<HeartbeatSendingEventArgs> Sending; /// <summary> Occurs when a heartbeat has been sent. </summary> public static event EventHandler<HeartbeatSentEventArgs> Sent; /// <summary> Occurs when the server Uri has been set or changed. </summary> public static event EventHandler<UriChangedEventArgs> UriChanged; static bool RaiseHeartbeatSendingEvent(HeartbeatData data, Uri uri, bool getServerUri) { var h = Sending; if (h == null) return true; var e = new HeartbeatSendingEventArgs(data, uri, getServerUri); h(null, e); return !e.Cancel; } static void RaiseHeartbeatSentEvent(HeartbeatData heartbeatData, HttpWebResponse response, string text) { var h = Sent; if (h != null) { h(null, new HeartbeatSentEventArgs(heartbeatData, response.Headers, response.StatusCode, text)); } } static void RaiseUriChangedEvent(Uri oldUri, Uri newUri) { var h = UriChanged; if (h != null) h(null, new UriChangedEventArgs(oldUri, newUri)); } #endregion sealed class HeartbeatRequestState { public HeartbeatRequestState(HttpWebRequest request, HeartbeatData data, bool getServerUri) { Request = request; Data = data; GetServerUri = getServerUri; } public readonly HttpWebRequest Request; public readonly HeartbeatData Data; public readonly bool GetServerUri; } } public sealed class HeartbeatData { internal HeartbeatData([NotNull] Uri heartbeatUri) { if (heartbeatUri == null) throw new ArgumentNullException("heartbeatUri"); IsPublic = ConfigKey.IsPublic.Enabled(); MaxPlayers = ConfigKey.MaxPlayers.GetInt(); PlayerCount = Server.CountPlayers(false); ServerIP = Server.InternalIP; Port = Server.Port; ProtocolVersion = Config.ProtocolVersion; Salt = Heartbeat.Salt; Salt2 = Heartbeat.Salt2; ServerName = ConfigKey.ServerName.GetString(); CustomData = new Dictionary<string, string>(); HeartbeatUri = heartbeatUri; } [NotNull] public Uri HeartbeatUri { get; private set; } public string Salt { get; set; } public string Salt2 { get; set; } public IPAddress ServerIP { get; set; } public int Port { get; set; } public int PlayerCount { get; set; } public int MaxPlayers { get; set; } public string ServerName { get; set; } public bool IsPublic { get; set; } public int ProtocolVersion { get; set; } public Dictionary<string, string> CustomData { get; private set; } public Uri CreateUri(string salt_) { UriBuilder ub = new UriBuilder(HeartbeatUri); StringBuilder sb = new StringBuilder(); //if we are sending to CC if (salt_ == Salt2) { sb.AppendFormat("public={0}&max={1}&users={2}&port={3}&software={7}&version={4}&salt={5}&name={6}", IsPublic, MaxPlayers, PlayerCount, Port, ProtocolVersion, Uri.EscapeDataString(salt_), Uri.EscapeDataString(ServerName), "LegendCraft v" + Updater.LatestStable); foreach (var pair in CustomData) { sb.AppendFormat("&{0}={1}", Uri.EscapeDataString(pair.Key), Uri.EscapeDataString(pair.Value)); } ub.Query = sb.ToString(); } else { sb.AppendFormat("public={0}&max={1}&users={2}&port={3}&version={4}&salt={5}&name={6}", IsPublic, MaxPlayers, PlayerCount, Port, ProtocolVersion, Uri.EscapeDataString(salt_), Uri.EscapeDataString(ServerName)); foreach (var pair in CustomData) { sb.AppendFormat("&{0}={1}", Uri.EscapeDataString(pair.Key), Uri.EscapeDataString(pair.Value)); } ub.Query = sb.ToString(); } return ub.Uri; } } } namespace fCraft.Events { public sealed class HeartbeatSentEventArgs : EventArgs { internal HeartbeatSentEventArgs(HeartbeatData heartbeatData, WebHeaderCollection headers, HttpStatusCode status, string text) { HeartbeatData = heartbeatData; ResponseHeaders = headers; ResponseStatusCode = status; ResponseText = text; } public HeartbeatData HeartbeatData { get; private set; } public WebHeaderCollection ResponseHeaders { get; private set; } public HttpStatusCode ResponseStatusCode { get; private set; } public string ResponseText { get; private set; } } public sealed class HeartbeatSendingEventArgs : EventArgs, ICancellableEvent { internal HeartbeatSendingEventArgs(HeartbeatData data, Uri uri, bool getServerUri) { HeartbeatData = data; Uri = uri; GetServerUri = getServerUri; } public HeartbeatData HeartbeatData { get; private set; } public Uri Uri { get; set; } public bool GetServerUri { get; set; } public bool Cancel { get; set; } } public sealed class UriChangedEventArgs : EventArgs { internal UriChangedEventArgs(Uri oldUri, Uri newUri) { OldUri = oldUri; NewUri = newUri; } public Uri OldUri { get; private set; } public Uri NewUri { get; private set; } } }
using System; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using FluentAssertions; using Newtonsoft.Json.Linq; using NuGet.Test.Helpers; using Sleet; using Xunit; namespace SleetLib.Tests { public class ExternalSearchTests { [Fact] public async Task VerifySetUpdatesIndexJson() { using (var packagesFolder = new TestFolder()) using (var target = new TestFolder()) using (var cache = new LocalCache()) using (var outputFolder = new TestFolder()) { var log = new TestLogger(); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root)); var settings = new LocalSettings(); var context = new SleetContext() { Token = CancellationToken.None, LocalSettings = settings, Log = log, Source = fileSystem, SourceSettings = new FeedSettings() }; var success = await InitCommand.RunAsync(settings, fileSystem, log); success &= await FeedSettingsCommand.RunAsync( settings, fileSystem, unsetAll: false, getAll: false, getSettings: Array.Empty<string>(), unsetSettings: Array.Empty<string>(), setSettings: new string[] { "externalsearch:https://example.org/search/query" }, log: log, token: context.Token); success.Should().BeTrue(); var indexJsonPath = Path.Combine(target.RootDirectory.FullName, "index.json"); var entry = GetSearchEntry(indexJsonPath); var value = entry["@id"].ToObject<string>(); value.Should().Be("https://example.org/search/query"); } } [Fact] public async Task VerifyUnSetUpdatesIndexJson() { using (var packagesFolder = new TestFolder()) using (var target = new TestFolder()) using (var cache = new LocalCache()) using (var outputFolder = new TestFolder()) { var log = new TestLogger(); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root)); var settings = new LocalSettings(); var context = new SleetContext() { Token = CancellationToken.None, LocalSettings = settings, Log = log, Source = fileSystem, SourceSettings = new FeedSettings() }; var success = await InitCommand.RunAsync(settings, fileSystem, log); success &= await FeedSettingsCommand.RunAsync( settings, fileSystem, unsetAll: false, getAll: false, getSettings: Array.Empty<string>(), unsetSettings: Array.Empty<string>(), setSettings: new string[] { "externalsearch:https://example.org/search/query" }, log: log, token: context.Token); success &= await FeedSettingsCommand.RunAsync( settings, fileSystem, unsetAll: false, getAll: false, getSettings: Array.Empty<string>(), unsetSettings: new string[] { "externalsearch" }, setSettings: Array.Empty<string>(), log: log, token: context.Token); success.Should().BeTrue(); var indexJsonPath = Path.Combine(target.RootDirectory.FullName, "index.json"); var entry = GetSearchEntry(indexJsonPath); var value = entry["@id"].ToObject<string>(); value.Should().NotBe("https://example.org/search/query"); } } [Fact] public async Task VerifyUnSetAllUpdatesIndexJson() { using (var packagesFolder = new TestFolder()) using (var target = new TestFolder()) using (var cache = new LocalCache()) using (var outputFolder = new TestFolder()) { var log = new TestLogger(); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root)); var settings = new LocalSettings(); var context = new SleetContext() { Token = CancellationToken.None, LocalSettings = settings, Log = log, Source = fileSystem, SourceSettings = new FeedSettings() }; var success = await InitCommand.RunAsync(settings, fileSystem, log); success &= await FeedSettingsCommand.RunAsync( settings, fileSystem, unsetAll: false, getAll: false, getSettings: Array.Empty<string>(), unsetSettings: Array.Empty<string>(), setSettings: new string[] { "externalsearch:https://example.org/search/query" }, log: log, token: context.Token); success &= await FeedSettingsCommand.RunAsync( settings, fileSystem, unsetAll: true, getAll: false, getSettings: Array.Empty<string>(), unsetSettings: Array.Empty<string>(), setSettings: Array.Empty<string>(), log: log, token: context.Token); success.Should().BeTrue(); var indexJsonPath = Path.Combine(target.RootDirectory.FullName, "index.json"); var entry = GetSearchEntry(indexJsonPath); var value = entry["@id"].ToObject<string>(); value.Should().NotBe("https://example.org/search/query"); } } [Fact] public async Task VerifyRecreateKeepsExternalSearch() { using (var tmpFolder = new TestFolder()) using (var packagesFolder = new TestFolder()) using (var target = new TestFolder()) using (var cache = new LocalCache()) using (var outputFolder = new TestFolder()) { var log = new TestLogger(); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root)); var settings = new LocalSettings(); var context = new SleetContext() { Token = CancellationToken.None, LocalSettings = settings, Log = log, Source = fileSystem, SourceSettings = new FeedSettings() }; var success = await InitCommand.RunAsync(settings, fileSystem, log); success &= await FeedSettingsCommand.RunAsync( settings, fileSystem, unsetAll: false, getAll: false, getSettings: Array.Empty<string>(), unsetSettings: Array.Empty<string>(), setSettings: new string[] { "externalsearch:https://example.org/search/query" }, log: log, token: context.Token); success &= await RecreateCommand.RunAsync( settings, fileSystem, tmpFolder.RootDirectory.FullName, false, context.Log); success.Should().BeTrue(); var indexJsonPath = Path.Combine(target.RootDirectory.FullName, "index.json"); var entry = GetSearchEntry(indexJsonPath); var value = entry["@id"].ToObject<string>(); value.Should().Be("https://example.org/search/query"); } } private JObject GetSearchEntry(string indexJsonPath) { var json = JObject.Parse(File.ReadAllText(indexJsonPath)); return GetSearchEntry(json); } private JObject GetSearchEntry(JObject serviceIndex) { var resources = (JArray)serviceIndex["resources"]; return (JObject)resources.First(e => e["@type"].ToObject<string>().StartsWith("SearchQueryService/")); } } }
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: api@infopluscommerce.com * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using RestSharp; using Infoplus.Client; using Infoplus.Model; namespace Infoplus.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IBusinessTransactionApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Search businessTransactions by filter /// </summary> /// <remarks> /// Returns the list of businessTransactions that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>List&lt;BusinessTransaction&gt;</returns> List<BusinessTransaction> GetBusinessTransactionByFilter (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Search businessTransactions by filter /// </summary> /// <remarks> /// Returns the list of businessTransactions that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>ApiResponse of List&lt;BusinessTransaction&gt;</returns> ApiResponse<List<BusinessTransaction>> GetBusinessTransactionByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Get a businessTransaction by id /// </summary> /// <remarks> /// Returns the businessTransaction identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="businessTransactionId">Id of the businessTransaction to be returned.</param> /// <returns>BusinessTransaction</returns> BusinessTransaction GetBusinessTransactionById (int? businessTransactionId); /// <summary> /// Get a businessTransaction by id /// </summary> /// <remarks> /// Returns the businessTransaction identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="businessTransactionId">Id of the businessTransaction to be returned.</param> /// <returns>ApiResponse of BusinessTransaction</returns> ApiResponse<BusinessTransaction> GetBusinessTransactionByIdWithHttpInfo (int? businessTransactionId); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Search businessTransactions by filter /// </summary> /// <remarks> /// Returns the list of businessTransactions that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of List&lt;BusinessTransaction&gt;</returns> System.Threading.Tasks.Task<List<BusinessTransaction>> GetBusinessTransactionByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Search businessTransactions by filter /// </summary> /// <remarks> /// Returns the list of businessTransactions that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of ApiResponse (List&lt;BusinessTransaction&gt;)</returns> System.Threading.Tasks.Task<ApiResponse<List<BusinessTransaction>>> GetBusinessTransactionByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Get a businessTransaction by id /// </summary> /// <remarks> /// Returns the businessTransaction identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="businessTransactionId">Id of the businessTransaction to be returned.</param> /// <returns>Task of BusinessTransaction</returns> System.Threading.Tasks.Task<BusinessTransaction> GetBusinessTransactionByIdAsync (int? businessTransactionId); /// <summary> /// Get a businessTransaction by id /// </summary> /// <remarks> /// Returns the businessTransaction identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="businessTransactionId">Id of the businessTransaction to be returned.</param> /// <returns>Task of ApiResponse (BusinessTransaction)</returns> System.Threading.Tasks.Task<ApiResponse<BusinessTransaction>> GetBusinessTransactionByIdAsyncWithHttpInfo (int? businessTransactionId); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class BusinessTransactionApi : IBusinessTransactionApi { private Infoplus.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="BusinessTransactionApi"/> class. /// </summary> /// <returns></returns> public BusinessTransactionApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="BusinessTransactionApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public BusinessTransactionApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public Infoplus.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Search businessTransactions by filter Returns the list of businessTransactions that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>List&lt;BusinessTransaction&gt;</returns> public List<BusinessTransaction> GetBusinessTransactionByFilter (string filter = null, int? page = null, int? limit = null, string sort = null) { ApiResponse<List<BusinessTransaction>> localVarResponse = GetBusinessTransactionByFilterWithHttpInfo(filter, page, limit, sort); return localVarResponse.Data; } /// <summary> /// Search businessTransactions by filter Returns the list of businessTransactions that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>ApiResponse of List&lt;BusinessTransaction&gt;</returns> public ApiResponse< List<BusinessTransaction> > GetBusinessTransactionByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null) { var localVarPath = "/v1.0/businessTransaction/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetBusinessTransactionByFilter", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<BusinessTransaction>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<BusinessTransaction>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<BusinessTransaction>))); } /// <summary> /// Search businessTransactions by filter Returns the list of businessTransactions that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of List&lt;BusinessTransaction&gt;</returns> public async System.Threading.Tasks.Task<List<BusinessTransaction>> GetBusinessTransactionByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null) { ApiResponse<List<BusinessTransaction>> localVarResponse = await GetBusinessTransactionByFilterAsyncWithHttpInfo(filter, page, limit, sort); return localVarResponse.Data; } /// <summary> /// Search businessTransactions by filter Returns the list of businessTransactions that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of ApiResponse (List&lt;BusinessTransaction&gt;)</returns> public async System.Threading.Tasks.Task<ApiResponse<List<BusinessTransaction>>> GetBusinessTransactionByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null) { var localVarPath = "/v1.0/businessTransaction/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetBusinessTransactionByFilter", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<BusinessTransaction>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<BusinessTransaction>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<BusinessTransaction>))); } /// <summary> /// Get a businessTransaction by id Returns the businessTransaction identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="businessTransactionId">Id of the businessTransaction to be returned.</param> /// <returns>BusinessTransaction</returns> public BusinessTransaction GetBusinessTransactionById (int? businessTransactionId) { ApiResponse<BusinessTransaction> localVarResponse = GetBusinessTransactionByIdWithHttpInfo(businessTransactionId); return localVarResponse.Data; } /// <summary> /// Get a businessTransaction by id Returns the businessTransaction identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="businessTransactionId">Id of the businessTransaction to be returned.</param> /// <returns>ApiResponse of BusinessTransaction</returns> public ApiResponse< BusinessTransaction > GetBusinessTransactionByIdWithHttpInfo (int? businessTransactionId) { // verify the required parameter 'businessTransactionId' is set if (businessTransactionId == null) throw new ApiException(400, "Missing required parameter 'businessTransactionId' when calling BusinessTransactionApi->GetBusinessTransactionById"); var localVarPath = "/v1.0/businessTransaction/{businessTransactionId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (businessTransactionId != null) localVarPathParams.Add("businessTransactionId", Configuration.ApiClient.ParameterToString(businessTransactionId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetBusinessTransactionById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<BusinessTransaction>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (BusinessTransaction) Configuration.ApiClient.Deserialize(localVarResponse, typeof(BusinessTransaction))); } /// <summary> /// Get a businessTransaction by id Returns the businessTransaction identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="businessTransactionId">Id of the businessTransaction to be returned.</param> /// <returns>Task of BusinessTransaction</returns> public async System.Threading.Tasks.Task<BusinessTransaction> GetBusinessTransactionByIdAsync (int? businessTransactionId) { ApiResponse<BusinessTransaction> localVarResponse = await GetBusinessTransactionByIdAsyncWithHttpInfo(businessTransactionId); return localVarResponse.Data; } /// <summary> /// Get a businessTransaction by id Returns the businessTransaction identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="businessTransactionId">Id of the businessTransaction to be returned.</param> /// <returns>Task of ApiResponse (BusinessTransaction)</returns> public async System.Threading.Tasks.Task<ApiResponse<BusinessTransaction>> GetBusinessTransactionByIdAsyncWithHttpInfo (int? businessTransactionId) { // verify the required parameter 'businessTransactionId' is set if (businessTransactionId == null) throw new ApiException(400, "Missing required parameter 'businessTransactionId' when calling BusinessTransactionApi->GetBusinessTransactionById"); var localVarPath = "/v1.0/businessTransaction/{businessTransactionId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (businessTransactionId != null) localVarPathParams.Add("businessTransactionId", Configuration.ApiClient.ParameterToString(businessTransactionId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetBusinessTransactionById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<BusinessTransaction>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (BusinessTransaction) Configuration.ApiClient.Deserialize(localVarResponse, typeof(BusinessTransaction))); } } }
/*************************************************************************************************************** * Author: Tanay Parikh Project Name: Moneta Description: Main view controller. Manages form actions and calls the appropriate command in the appropriate module. Includes refrences to the Business Stats, Invoice, Settings, Client and Expense modules. * ***************************************************************************************************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MySql.Data.MySqlClient; using System.Diagnostics; using System.IO; namespace Moneta { public partial class FrmMain : Form { //Stores the main project wide shared data variable private SharedData data; //Variables storing whether the window is currently being dragged and the last point on the screen of the window. private bool dragging = false; private Point startPoint = new Point(0, 0); //Variables storing the individual modules private InvoiceModule invoices; private SettingsModule settings; private BusinessStatsModule businessStats; private ClientModule clients; private ExpenseModule expenses; //Loads the item dataset public DataSet itemsDataS = new DataSet("items"); //Main form class constructor public FrmMain() { //Instanstiates the program's shared data data = new SharedData(); //Instanstiates the program's modules, with the form, and the shared data variable as it's parameters. invoices = new InvoiceModule(this, data); settings = new SettingsModule(this, data); businessStats = new BusinessStatsModule(this, data); clients = new ClientModule(this, data); expenses = new ExpenseModule(this, data); //Initializes the form InitializeComponent(); //Initializes the modules invoices.initialize(); expenses.initialize(); businessStats.initialize(); settings.initialize(); } //Loads form elements private void frmMain_Load(object sender, EventArgs e) { data.setupNewProgram(); //Attempts to load the databases try { //Loads the expenses dataset this.expensesTableAdapter.Fill(this.expensesDataSet.expenses); //Loads the invoices dataset this.invoicesTableAdapter.Fill(this.invoicesDataSet.invoices); //Loads the client dataset this.clientsTableAdapter.Fill(this.mydbDataSet.clients); //Performs the final instialization of the individual modules. //Fills in checkboxes and other special columns in datagridview expenses.updateImagesColumn(); invoices.updateInvoiceCheckboxes(); //Fills value for autofill of client information setUpClientAutofill(); //Accounts for first initialization if (dgvInvoices.Rows.Count > 0) { //Ensures no invoice is initially selected dgvInvoices.Rows[0].Cells[0].Selected = false; } } //Catches any exceptions resulting from the inability to access the database catch (MySqlException sqle) { //Informs the user of the error and troubleshooting MessageBox.Show("Please restart the program." + sqle.Message); } } /**************************************************************************************************************************** * * General Form Event Handlers * ****************************************************************************************************************************/ private void btnClose_Click(object sender, EventArgs e) { //Stops the mysql server string driveName = Application.StartupPath.Substring(0, Application.StartupPath.IndexOf('\\')) + "\\"; data.startProcess(driveName + "\\MonetaDatabase\\xampplite\\mysql_stop.bat"); //Closes the application upon selection of the 'x' button Application.Exit(); } private void btnMinimize_Click(object sender, EventArgs e) { //Minimizes the application upon selection of the '-' button this.WindowState = FormWindowState.Minimized; } private void frmMain_MouseDown(object sender, MouseEventArgs e) { //Indicates the mouse is currently down on the form, dragging begins/continues //The current update's window coordinate is stored. dragging = true; startPoint = new Point(e.X, e.Y); } private void frmMain_MouseUp(object sender, MouseEventArgs e) { //Indicates that the dragging has stopped dragging = false; } private void frmMain_MouseMove(object sender, MouseEventArgs e) { //Checks if the window is currently being dragged if (dragging) { //Gets the current cursor position Point cursorLocation = PointToScreen(e.Location); //Updates the location of the window to the amount moved by the cursor in the x and y directions Location = new Point(cursorLocation.X - this.startPoint.X, cursorLocation.Y - this.startPoint.Y); } } private void lblClients_Click(object sender, EventArgs e) { //Indicates the selection of the clients module. //Resets visibilities of other modules, and makes the module nav text green. resetVisibilities(); lblNavClients.ForeColor = data.greenText; pnlClients.Visible = true; } private void lblNavInvoices_Click(object sender, EventArgs e) { //Indicates the selection of the invoices module. //Resets visibilities of other modules, and makes the module nav text green. resetVisibilities(); lblNavInvoices.ForeColor = data.greenText; pnlInvoices.Visible = true; } private void lblNavExpenses_Click(object sender, EventArgs e) { //Indicates the selection of the expenses module. //Resets visibilities of other modules, and makes the module nav text green. resetVisibilities(); lblNavExpenses.ForeColor = data.greenText; pnlExpenses.Visible = true; } private void lblNavBusinessStats_Click(object sender, EventArgs e) { //Indicates the selection of the business stats module. //Resets visibilities of other modules, and makes the module nav text green. resetVisibilities(); lblNavBusinessStats.ForeColor = data.greenText; pnlBusinessStats.Visible = true; //Sets the default starting and ending dates, and calls for the calculation of the stats dtpStatsStart.Value = DateTime.Today.AddDays(-120).Date; dtpStatsEnd.Value = DateTime.Today; businessStats.calculateStats(); } private void lblNavSettings_Click(object sender, EventArgs e) { //Indicates the selection of the settings module. //Resets visibilities of other modules, and makes the module nav text green. resetVisibilities(); lblNavSettings.ForeColor = data.greenText; pnlSettings.Visible = true; } private void lblNavHome_Click(object sender, EventArgs e) { //Indicates the selection of the home page. //Resets visibilities of other modules, and makes the page nav text green. resetVisibilities(); lblNavHome.ForeColor = data.greenText; pnlHome.Visible = true; } //Pre: None //Post: Resets the visibilities and text colours of the nav text. //Description: Makes all panels invisible and sets text colors to white for the navigation. private void resetVisibilities() { //Makes all panels, aside from navigation, invisible pnlClients.Visible = false; pnlInvoices.Visible = false; pnlExpenses.Visible = false; pnlBusinessStats.Visible = false; pnlSettings.Visible = false; pnlHome.Visible = false; //Resets all nav link fore colours to white lblNavBusinessStats.ForeColor = data.textColorWhite; lblNavClients.ForeColor = data.textColorWhite; lblNavExpenses.ForeColor = data.textColorWhite; lblNavHome.ForeColor = data.textColorWhite; lblNavInvoices.ForeColor = data.textColorWhite; lblNavSettings.ForeColor = data.textColorWhite; } /**************************************************************************************************************************** * * Clients Event Handlers * ****************************************************************************************************************************/ public void btnCreateClient_Click(object sender, EventArgs e) { //Calls for the creation of the client clients.createClient(); } public void dgvClients_SelectionChanged(object sender, EventArgs e) { //Indicates selection has changed in client dgv clients.dgvSelectionChanged(); } public void dgvClients_DataError(object sender, DataGridViewDataErrorEventArgs error) { //Indicates error in client dgv clients.dgvDataError(sender, error); } /**************************************************************************************************************************** * * Expenses Event Handlers * ****************************************************************************************************************************/ public void tmrWorkTime_Tick(object sender, EventArgs e) { //Instantiates the timer expenses.timerTick(); } public void btnTimerReset_Click(object sender, EventArgs e) { //Resets the timer and values expenses.timerReset(); } public void btnTimerStartStop_Click(object sender, EventArgs e) { //Starts/stops the timer expenses.timerStartStop(); } public void btnSubmitDistance_Click(object sender, EventArgs e) { //Submits the distance into the dgv, and updates dgv entries expenses.submitDistance(); dgvExpenses_SelectionChanged(sender, e); } private void btnTimeAddExpense_Click(object sender, EventArgs e) { //Submits the time into the dgv, and updates dgv entries expenses.submitTime(); dgvExpenses_SelectionChanged(sender, e); } public void dgvExpenses_CellClick(object sender, DataGridViewCellEventArgs e) { //Indicates cell click in expenses dgv expenses.dgvCellClick(e); } public void dgvExpenses_SelectionChanged(object sender, EventArgs e) { //Indicates selection changed in expenses dgv expenses.dgvSelectionChanged(); } public void dgvExpenses_CellEnter(object sender, DataGridViewCellEventArgs e) { //Indicates cell has been entered in expenses dgv expenses.dgvCellEnter(e); } public void dgvExpenses_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { //Calls for the instantiation of the autocomplete fields for the expense categories expenses.displayExpenseCategorizationInfo(e); } public void dgvExpenses_DataError(object sender, DataGridViewDataErrorEventArgs error) { //Indicates an error has been encountered with dgv expenses expenses.dgvDataError(sender, error); } private void dgvExpenses_Sorted(object sender, EventArgs e) { //Redisplays the image column based on the newly sorted dgv expenses.updateImagesColumn(); } private void btnAddExpense_Click(object sender, EventArgs e) { //Indicates the add expense button has been pressed expenses.addExpense(); } private void btnAddImage_Click(object sender, EventArgs e) { //Indicates the add image button has been pressed. Calls for the fetching of the image, if it fails, returns back the existing label. btnExpenseAddImage.Text = expenses.fetchImage("Add Image"); } /**************************************************************************************************************************** * * Invoices Event Handlers * ****************************************************************************************************************************/ public void dgvInvoices_Sorted(object sender, EventArgs e) { //Calls for the updating of dgv invoice checkboxes based on newly sorted arrangement invoices.updateInvoiceCheckboxes(); } public void dgvInvoices_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { //Calls for the sorting of the invoices invoices.sortInvoices(e); } public void btnPrintInvoice_Click(object sender, EventArgs e) { //Calls for the printing of the invoice invoices.printInvoice(); } public void btnEmailInvoice_Click(object sender, EventArgs e) { //Calls for the emailing of the invoice invoices.sendInvoice(); } public void dgvItems_DataError(object sender, DataGridViewDataErrorEventArgs error) { //Indicates error in items dgv data.displayDGVError(sender, error); } private void dgvItems_CellValueChanged(object sender, DataGridViewCellEventArgs e) { //Indicates selection change in items dgv invoices.dgvItemsSelectionChanged(); } public void dgvInvoices_DataError(object sender, DataGridViewDataErrorEventArgs error) { //Indicates error in invoices dgv data.displayDGVError(sender, error); } public void dgvInvoices_SelectionChanged(object sender, EventArgs e) { //Indicates selection change in invoices dgv invoices.dgvInvoicesSelectionChanged(); } private void txtInvoiceClientName_TextChanged(object sender, EventArgs e) { invoices.scanForClientID(); } public void setUpClientAutofill() { invoices.setUpAutofillClientName(); } public void dgvInvoices_CellClick_1(object sender, DataGridViewCellEventArgs e) { //Indicates cell in dgv invoices has been clicked invoices.dgvCellClick(); } private void btnCreateInvoice_Click(object sender, EventArgs e) { //Calls for the creation of the invoice and the updating of the dgv invoices invoices.setupNewInvoice(); dgvInvoices_SelectionChanged(sender, e); } private void btnCreateEditDone_Click(object sender, EventArgs e) { //Calls to save modified invoice data if any. invoices.btnCreateDone(sender, e); } private void btnCreateEditAddItems_Click(object sender, EventArgs e) { //Confirms creation of invoice with data provided. invoices.createInvoice(); } /**************************************************************************************************************************** * * Business Stats Event Handlers * ****************************************************************************************************************************/ private void btnUpdateStats_Click(object sender, EventArgs e) { //Calls for the recalculation of the stats based on time range selected businessStats.calculateStats(); } private void btnGenerateProfitLossStatement_Click(object sender, EventArgs e) { //Calls for the generation of the profit loss statement businessStats.generateProfitLoss(); } /**************************************************************************************************************************** * * Settings Event Handlers * ****************************************************************************************************************************/ private void btnSaveSettings_Click(object sender, EventArgs e) { //Saves the settings entered settings.saveSettings(); } private void dgvSettings_DataError(object sender, DataGridViewDataErrorEventArgs e) { //Displays the settings dgv error data.displayDGVError(sender, e); } private void dgvSettings_SelectionChanged(object sender, EventArgs e) { //Indicates selection changed in settings dgv settings.dgvSelectionChanged(); } } }
// Prexonite // // Copyright (c) 2014, Christian Klauser // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // The names of the contributors may be used to endorse or // promote products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using JetBrains.Annotations; namespace Prexonite.Compiler.Ast { /// <summary> /// An AST expression node for optimized string concatenation. /// </summary> /// <remarks> /// <para> /// This node get's created as a replacement for nodes created by <see cref = "IAstFactory.BinaryOperation" /> with string operands. /// </para> /// </remarks> public class AstStringConcatenation : AstExpr, IAstHasExpressions { [NotNull] private readonly AstGetSet _simpleConcatPrototype; [NotNull] private readonly AstGetSet _multiConcatPrototype; /// <summary> /// The list of arguments for the string concatenation. /// </summary> [NotNull] private readonly List<AstExpr> _arguments = new List<AstExpr>(); /// <summary> /// Creates a new AstStringConcatenation AST node. /// </summary> /// <param name="position">The portion of source code that spawned this AST node.</param> /// <param name="simpleConcatPrototype">A prototype of the call that implements the simple string concatenation (two operands).</param> /// <param name="multiConcatPrototype">A prototype of the call that implements the multi-string concatenation (more than two operands).</param> /// <param name = "arguments">A list of expressions to be added to the <see cref = "_arguments" /> list.</param> [DebuggerNonUserCode] public AstStringConcatenation(ISourcePosition position, AstGetSet simpleConcatPrototype, AstGetSet multiConcatPrototype, params AstExpr[] arguments) : base(position) { if (simpleConcatPrototype == null) throw new ArgumentNullException("simpleConcatPrototype"); if (multiConcatPrototype == null) throw new ArgumentNullException("multiConcatPrototype"); if (arguments == null) arguments = new AstExpr[] {}; _arguments.AddRange(arguments); _simpleConcatPrototype = simpleConcatPrototype; _multiConcatPrototype = multiConcatPrototype; } #region IAstHasExpressions Members public AstExpr[] Expressions { get { return _arguments.ToArray(); } } /// <summary> /// The list of arguments for the string concatenation. /// </summary> public List<AstExpr> Arguments { get { return _arguments; } } #endregion /// <summary> /// Emits code for the AstStringConcatenation node. /// </summary> /// <param name = "target">The target to which to write the code to.</param> /// <param name="stackSemantics">The stack semantics with which to emit code. </param> /// <remarks> /// <para> /// AstStringConcatenation tries to find the most efficient way to concatenate strings. StringBuilders are actually slower when concatenating only two arguments. /// </para> /// <para> /// <list type = "table"> /// <listheader> /// <term>Arguments</term> /// <description>Emitted code</description> /// </listheader> /// <item> /// <term>0</term> /// <description><c><see cref = "OpCode.ldc_string">ldc.string</see> ""</c> (Empty string)</description> /// </item> /// <item> /// <term>1</term> /// <description>Just that argument and, unless it is a <see cref = "AstConstant">string constant</see>, a call to <c>ToString</c>.</description> /// </item> /// <item> /// <term>2</term> /// <description>Concatenation using the Addition (<c><see cref = "OpCode.add">add</see></c>) operator.</description> /// </item> /// <item> /// <term>n</term> /// <description>A call to the <c><see cref = "Prexonite.Engine.ConcatenateAlias">concat</see></c> command.</description> /// </item> /// </list> /// </para> /// </remarks> protected override void DoEmitCode(CompilerTarget target, StackSemantics stackSemantics) { if (_arguments.Count > 2) { var call = _multiConcatPrototype.GetCopy(); call.Arguments.AddRange(Arguments); call.EmitCode(target, stackSemantics); } else if (_arguments.Count >= 2) { var call = _simpleConcatPrototype.GetCopy(); call.Arguments.AddRange(Arguments); call.EmitCode(target, stackSemantics); } else if (_arguments.Count == 1) { if (stackSemantics == StackSemantics.Value) { _arguments[0].EmitValueCode(target); AstConstant constant; if ((constant = _arguments[0] as AstConstant) != null && !(constant.Constant is string)) target.EmitGetCall(Position, 1, "ToString"); } else { _arguments[0].EmitEffectCode(target); } } else if (_arguments.Count == 0) { if(stackSemantics == StackSemantics.Value) target.EmitConstant(Position, ""); } } #region AstExpr Members /// <summary> /// Tries to optimize the AstStringConcatenation node. /// </summary> /// <param name = "target">The context in which to perform the optimization.</param> /// <param name = "expr">A possible replacement for the called node.</param> /// <returns>True, if <paramref name = "expr" /> contains a replacement for the called node. /// False otherwise.</returns> /// <remarks> /// <para> /// Note that <c>false</c> as the return value doesn't mean that the node cannot be /// optimized. It just cannot be replaced by <paramref name = "expr" />. /// </para> /// <para> /// Also, <paramref name = "expr" /> is only defined if the method call returns <c>true</c>. Don't use it otherwise. /// </para> /// </remarks> public override bool TryOptimize(CompilerTarget target, out AstExpr expr) { _OptimizeInternal(target); AstConstant collapsed; if (Arguments.Count == 1 && (collapsed = Arguments[0] as AstConstant) != null) { expr = collapsed.Constant is string ? (AstExpr) collapsed : new AstGetSetMemberAccess(File, Line, Column, collapsed, "ToString"); } else { expr = null; } return expr != null; } internal void _OptimizeInternal(CompilerTarget target) { //Optimize arguments foreach (var arg in _arguments.ToArray()) { if (arg == null) throw new PrexoniteException( "Invalid (null) argument in StringConcat node (" + ToString() + // ReSharper disable ConditionIsAlwaysTrueOrFalse ") detected."); // ReSharper restore ConditionIsAlwaysTrueOrFalse var oArg = _GetOptimizedNode(target, arg); if (!ReferenceEquals(oArg, arg)) { var idx = _arguments.IndexOf(arg); _arguments.Insert(idx, oArg); _arguments.RemoveAt(idx + 1); } } //Expand embedded concats argument list var argumentArray = _arguments.ToArray(); for (var i = 0; i < argumentArray.Length; i++) { var argument = argumentArray[i]; var concat = argument as AstStringConcatenation; if (concat != null) { _arguments.RemoveAt(i); //Remove embedded concat _arguments.InsertRange(i, concat._arguments); //insert it's arguments instead } } //Try to shorten argument list var nlst = new List<AstExpr>(); string last = null; var buffer = new StringBuilder(); foreach (var e in _arguments) { string current; var currConst = e as AstConstant; if (currConst != null) current = currConst.ToPValue(target).CallToString(target.Loader); else current = null; if (current != null) { //Drop empty strings if (current.Length == 0) continue; buffer.Append(current); } else //current == null { if (last != null) { nlst.Add(new AstConstant(File, Line, Column, buffer.ToString())); buffer.Length = 0; } nlst.Add(e); } last = current; } if (last != null) { nlst.Add(new AstConstant(File, Line, Column, buffer.ToString())); buffer.Length = 0; } _arguments.Clear(); _arguments.AddRange(nlst); } #endregion } }
using UnityEngine; namespace Cinemachine.Utility { /// <summary>Extensions to the Vector3 class, used by Cinemachine</summary> public static class UnityVectorExtensions { /// <summary>A useful Epsilon</summary> public const float Epsilon = 0.0001f; /// <summary> /// Get the closest point on a line segment. /// </summary> /// <param name="p">A point in space</param> /// <param name="s0">Start of line segment</param> /// <param name="s1">End of line segment</param> /// <returns>The interpolation parameter representing the point on the segment, with 0==s0, and 1==s1</returns> public static float ClosestPointOnSegment(this Vector3 p, Vector3 s0, Vector3 s1) { Vector3 s = s1 - s0; float len2 = Vector3.SqrMagnitude(s); if (len2 < Epsilon) return 0; // degenrate segment return Mathf.Clamp01(Vector3.Dot(p - s0, s) / len2); } /// <summary> /// Returns a non-normalized projection of the supplied vector onto a plane /// as described by its normal /// </summary> /// <param name="vector"></param> /// <param name="planeNormal">The normal that defines the plane. Cannot be zero-length.</param> /// <returns>The component of the vector that lies in the plane</returns> public static Vector3 ProjectOntoPlane(this Vector3 vector, Vector3 planeNormal) { return (vector - Vector3.Dot(vector, planeNormal) * planeNormal); } /// <summary>Is the vector within Epsilon of zero length?</summary> /// <param name="v"></param> /// <returns>True if the square magnitude of the vector is within Epsilon of zero</returns> public static bool AlmostZero(this Vector3 v) { return v.sqrMagnitude < Epsilon; } /// <summary>Get a signed angle between two vectors</summary> /// <param name="from">Start direction</param> /// <param name="to">End direction</param> /// <param name="refNormal">This is needed in order to determine the sign. /// For example, if from an to lie on the XZ plane, then this would be the /// Y unit vector, or indeed any vector which, when dotted with Y unit vector, /// would give a positive result.</param> /// <returns>The signed angle between the vectors</returns> public static float SignedAngle(Vector3 from, Vector3 to, Vector3 refNormal) { float angle = Vector3.Angle(from, to); if (Vector3.Dot(Vector3.Cross(from, to), refNormal) < 0) return -angle; return angle; } /// <summary>This is a slerp that mimics a camera operator's movement in that /// it chooses a path that avoids the lower hemisphere, as defined by /// the up param</summary> /// <param name="vA">First direction</param> /// <param name="vB">Second direction</param> /// <param name="t">Interpolation amoun t</param> /// <param name="up">Defines the up direction</param> public static Vector3 SlerpWithReferenceUp( Vector3 vA, Vector3 vB, float t, Vector3 up) { float dA = vA.magnitude; float dB = vB.magnitude; if (dA < Epsilon || dB < Epsilon) return Vector3.Lerp(vA, vB, t); Vector3 dirA = vA / dA; Vector3 dirB = vB / dB; Quaternion qA = Quaternion.LookRotation(dirA, up); Quaternion qB = Quaternion.LookRotation(dirB, up); Quaternion q = UnityQuaternionExtensions.SlerpWithReferenceUp(qA, qB, t, up); Vector3 dir = q * Vector3.forward; return dir * Mathf.Lerp(dA, dB, t); } } /// <summary>Extentions to the Quaternion class, usen in various places by Cinemachine</summary> public static class UnityQuaternionExtensions { /// <summary>This is a slerp that mimics a camera operator's movement in that /// it chooses a path that avoids the lower hemisphere, as defined by /// the up param</summary> /// <param name="qA">First direction</param> /// <param name="qB">Second direction</param> /// <param name="t">Interpolation amoun t</param> /// <param name="up">Defines the up direction</param> public static Quaternion SlerpWithReferenceUp( Quaternion qA, Quaternion qB, float t, Vector3 up) { Vector3 dirA = (qA * Vector3.forward).ProjectOntoPlane(up); Vector3 dirB = (qB * Vector3.forward).ProjectOntoPlane(up); if (dirA.AlmostZero() || dirB.AlmostZero()) return Quaternion.Slerp(qA, qB, t); // Work on the plane, in eulers Quaternion qBase = Quaternion.LookRotation(dirA, up); Quaternion qA1 = Quaternion.Inverse(qBase) * qA; Quaternion qB1 = Quaternion.Inverse(qBase) * qB; Vector3 eA = qA1.eulerAngles; Vector3 eB = qB1.eulerAngles; return qBase * Quaternion.Euler( Mathf.LerpAngle(eA.x, eB.x, t), Mathf.LerpAngle(eA.y, eB.y, t), Mathf.LerpAngle(eA.z, eB.z, t)); } /// <summary>Normalize a quaternion</summary> /// <param name="q"></param> /// <returns>The normalized quaternion. Unit length is 1.</returns> public static Quaternion Normalized(this Quaternion q) { Vector4 v = new Vector4(q.x, q.y, q.z, q.w).normalized; return new Quaternion(v.x, v.y, v.z, v.w); } /// <summary> /// Get the rotations, first about world up, then about (travelling) local right, /// necessary to align the quaternion's forward with the target direction. /// This represents the tripod head movement needed to look at the target. /// This formulation makes it easy to interpolate without introducing spurious roll. /// </summary> /// <param name="orient"></param> /// <param name="lookAt">The target we want to look at</param> /// <param name="worldUp">Which way is up</param> /// <returns>Vector2.y is rotation about worldUp, and Vector2.x is second rotation, /// about local right.</returns> public static Vector2 GetCameraRotationToTarget( this Quaternion orient, Vector3 lookAt, Vector3 worldUp) { if (lookAt.AlmostZero()) return Vector2.zero; // degenerate // Work in local space Quaternion toLocal = Quaternion.Inverse(orient); Vector3 up = toLocal * worldUp; lookAt = toLocal * lookAt; // Align yaw based on world up float angleH = 0; { Vector3 targetDirH = lookAt.ProjectOntoPlane(up); if (!targetDirH.AlmostZero()) { Vector3 currentDirH = Vector3.forward.ProjectOntoPlane(up); if (currentDirH.AlmostZero()) { // We're looking at the north or south pole if (Vector3.Dot(currentDirH, up) > 0) currentDirH = Vector3.down.ProjectOntoPlane(up); else currentDirH = Vector3.up.ProjectOntoPlane(up); } angleH = UnityVectorExtensions.SignedAngle(currentDirH, targetDirH, up); } } Quaternion q = Quaternion.AngleAxis(angleH, up); // Get local vertical angle float angleV = UnityVectorExtensions.SignedAngle( q * Vector3.forward, lookAt, q * Vector3.right); return new Vector2(angleV, angleH); } /// <summary> /// Apply rotations, first about world up, then about (travelling) local right. /// rot.y is rotation about worldUp, and rot.x is second rotation, about local right. /// </summary> /// <param name="orient"></param> /// <param name="rot">Vector2.y is rotation about worldUp, and Vector2.x is second rotation, /// about local right.</param> /// <param name="worldUp">Which way is up</param> public static Quaternion ApplyCameraRotation( this Quaternion orient, Vector2 rot, Vector3 worldUp) { Quaternion q = Quaternion.AngleAxis(rot.x, Vector3.right); return (Quaternion.AngleAxis(rot.y, worldUp) * orient) * q; } } /// <summary>Ad-hoc xxtentions to the Rect structure, used by Cinemachine</summary> public static class UnityRectExtensions { /// <summary>Inflate a rect</summary> /// <param name="r"></param> /// <param name="delta">x and y are added/subtracted fto/from the edges of /// the rect, inflating it in all directions</param> /// <returns>The inflated rect</returns> public static Rect Inflated(this Rect r, Vector2 delta) { return new Rect( r.xMin - delta.x, r.yMin - delta.y, r.width + delta.x * 2, r.height + delta.y * 2); } } }
using System; using System.Collections.Generic; using System.IO; namespace BizHawk.Emulation.DiscSystem { static class SynthUtils { /// <summary> /// Calculates the checksum of the provided Q subchannel buffer and emplaces it /// </summary> /// <param name="buffer">12 byte Q subchannel buffer: input and output buffer for operation</param> /// <param name="offset">location within buffer of Q subchannel</param> public static ushort SubQ_SynthChecksum(byte[] buf12, int offset) { ushort crc16 = CRC16_CCITT.Calculate(buf12, offset, 10); //CRC is stored inverted and big endian buf12[offset + 10] = (byte)(~(crc16 >> 8)); buf12[offset + 11] = (byte)(~(crc16)); return crc16; } /// <summary> /// Caclulates the checksum of the provided Q subchannel buffer /// </summary> public static ushort SubQ_CalcChecksum(byte[] buf12, int offset) { return CRC16_CCITT.Calculate(buf12, offset, 10); } /// <summary> /// Serializes the provided SubchannelQ structure into a buffer /// Returns the crc, calculated or otherwise. /// </summary> public static ushort SubQ_Serialize(byte[] buf12, int offset, ref SubchannelQ sq) { buf12[offset + 0] = sq.q_status; buf12[offset + 1] = sq.q_tno.BCDValue; buf12[offset + 2] = sq.q_index.BCDValue; buf12[offset + 3] = sq.min.BCDValue; buf12[offset + 4] = sq.sec.BCDValue; buf12[offset + 5] = sq.frame.BCDValue; buf12[offset + 6] = sq.zero; buf12[offset + 7] = sq.ap_min.BCDValue; buf12[offset + 8] = sq.ap_sec.BCDValue; buf12[offset + 9] = sq.ap_frame.BCDValue; return SubQ_SynthChecksum(buf12, offset); } /// <summary> /// Synthesizes the typical subP data into the provided buffer depending on the indicated pause flag /// </summary> public static void SubP(byte[] buffer12, int offset, bool pause) { byte val = (byte)(pause ? 0xFF : 0x00); for (int i = 0; i < 12; i++) buffer12[offset + i] = val; } /// <summary> /// Synthesizes a data sector header /// </summary> public static void SectorHeader(byte[] buffer16, int offset, int LBA, byte mode) { buffer16[offset + 0] = 0x00; for (int i = 1; i < 11; i++) buffer16[offset + i] = 0xFF; buffer16[offset + 11] = 0x00; Timestamp ts = new Timestamp(LBA + 150); buffer16[offset + 12] = BCD2.IntToBCD(ts.MIN); buffer16[offset + 13] = BCD2.IntToBCD(ts.SEC); buffer16[offset + 14] = BCD2.IntToBCD(ts.FRAC); buffer16[offset + 15] = mode; } /// <summary> /// Synthesizes the EDC checksum for a Mode 2 Form 1 data sector (and puts it in place) /// </summary> public static void EDC_Mode2_Form1(byte[] buf2352, int offset) { uint edc = ECM.EDC_Calc(buf2352, offset + 16, 2048 + 8); ECM.PokeUint(buf2352, offset + 2072, edc); } /// <summary> /// Synthesizes the EDC checksum for a Mode 2 Form 2 data sector (and puts it in place) /// </summary> public static void EDC_Mode2_Form2(byte[] buf2352, int offset) { uint edc = ECM.EDC_Calc(buf2352, offset + 16, 2324 + 8); ECM.PokeUint(buf2352, offset + 2348, edc); } /// <summary> /// Synthesizes the complete ECM data (EDC + ECC) for a Mode 1 data sector (and puts it in place) /// Make sure everything else in the sector userdata is done before calling this /// </summary> public static void ECM_Mode1(byte[] buf2352, int offset, int LBA) { //EDC uint edc = ECM.EDC_Calc(buf2352, offset, 2064); ECM.PokeUint(buf2352, offset + 2064, edc); //reserved, zero for (int i = 0; i < 8; i++) buf2352[offset + 2068 + i] = 0; //ECC ECM.ECC_Populate(buf2352, offset, buf2352, offset, false); } /// <summary> /// Converts the useful (but unrealistic) deinterleaved subchannel data into the useless (but realistic) interleaved format. /// in_buf and out_buf should not overlap /// </summary> public static void InterleaveSubcode(byte[] in_buf, int in_buf_index, byte[] out_buf, int out_buf_index) { for (int d = 0; d < 12; d++) { for (int bitpoodle = 0; bitpoodle < 8; bitpoodle++) { int rawb = 0; for (int ch = 0; ch < 8; ch++) { rawb |= ((in_buf[ch * 12 + d + in_buf_index] >> (7 - bitpoodle)) & 1) << (7 - ch); } out_buf[(d << 3) + bitpoodle + out_buf_index] = (byte)rawb; } } } /// <summary> /// Converts the useless (but realistic) interleaved subchannel data into a useful (but unrealistic) deinterleaved format. /// in_buf and out_buf should not overlap /// </summary> public static void DeinterleaveSubcode(byte[] in_buf, int in_buf_index, byte[] out_buf, int out_buf_index) { for (int i = 0; i < 96; i++) out_buf[i] = 0; for (int ch = 0; ch < 8; ch++) { for (int i = 0; i < 96; i++) { out_buf[(ch * 12) + (i >> 3) + out_buf_index] |= (byte)(((in_buf[i + in_buf_index] >> (7 - ch)) & 0x1) << (7 - (i & 0x7))); } } } /// <summary> /// Converts the useful (but unrealistic) deinterleaved data into the useless (but realistic) interleaved subchannel format. /// </summary> public unsafe static void InterleaveSubcodeInplace(byte[] buf, int buf_index) { byte* out_buf = stackalloc byte[96]; for (int i = 0; i < 96; i++) out_buf[i] = 0; for (int d = 0; d < 12; d++) { for (int bitpoodle = 0; bitpoodle < 8; bitpoodle++) { int rawb = 0; for (int ch = 0; ch < 8; ch++) { rawb |= ((buf[ch * 12 + d + buf_index] >> (7 - bitpoodle)) & 1) << (7 - ch); } out_buf[(d << 3) + bitpoodle] = (byte)rawb; } } for (int i = 0; i < 96; i++) buf[i + buf_index] = out_buf[i]; } /// <summary> /// Converts the useless (but realistic) interleaved subchannel data into a useful (but unrealistic) deinterleaved format. /// </summary> public unsafe static void DeinterleaveSubcodeInplace(byte[] buf, int buf_index) { byte* out_buf = stackalloc byte[96]; for (int i = 0; i < 96; i++) out_buf[i] = 0; for (int ch = 0; ch < 8; ch++) { for (int i = 0; i < 96; i++) { out_buf[(ch * 12) + (i >> 3)] |= (byte)(((buf[i + buf_index] >> (7 - ch)) & 0x1) << (7 - (i & 0x7))); } } for (int i = 0; i < 96; i++) buf[i + buf_index] = out_buf[i]; } } }
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { using System; using System.Collections.Generic; using System.Globalization; using System.Text; using NLog.Config; using NLog.Internal; using NLog.Layouts; /// <summary> /// Represents target that supports context capture using MDLC, MDC, NDLC and NDC /// </summary> public abstract class TargetWithContext : TargetWithLayout, IIncludeContext { /// <inheritdoc/> /// <docgen category='Layout Options' order='1' /> public sealed override Layout Layout { get => _contextLayout; set { if (_contextLayout != null) _contextLayout.TargetLayout = value; else _contextLayout = new TargetWithContextLayout(this, value); } } private TargetWithContextLayout _contextLayout; /// <inheritdoc/> bool IIncludeContext.IncludeAllProperties { get => IncludeEventProperties; set => IncludeEventProperties = value; } /// <docgen category='Layout Options' order='10' /> public bool IncludeEventProperties { get => _contextLayout.IncludeAllProperties; set => _contextLayout.IncludeAllProperties = value; } /// <inheritdoc/> /// <docgen category='Layout Options' order='10' /> public bool IncludeMdc { get => _contextLayout.IncludeMdc; set => _contextLayout.IncludeMdc = value; } /// <inheritdoc/> /// <docgen category='Layout Options' order='10' /> public bool IncludeNdc { get => _contextLayout.IncludeNdc; set => _contextLayout.IncludeNdc = value; } #if !SILVERLIGHT /// <inheritdoc/> /// <docgen category='Layout Options' order='10' /> public bool IncludeMdlc { get => _contextLayout.IncludeMdlc; set => _contextLayout.IncludeMdlc = value; } /// <inheritdoc/> /// <docgen category='Layout Options' order='10' /> public bool IncludeNdlc { get => _contextLayout.IncludeNdlc; set => _contextLayout.IncludeNdlc = value; } #endif /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="GlobalDiagnosticsContext"/> dictionary /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeGdc { get; set; } /// <summary> /// Gets or sets a value indicating whether to include call site (class and method name) in the <see cref="LogEventInfo" /> /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeCallSite { get => _contextLayout.IncludeCallSite; set => _contextLayout.IncludeCallSite = value; } /// <summary> /// Gets or sets a value indicating whether to include source info (file name and line number) in the <see cref="LogEventInfo" /> /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeCallSiteStackTrace { get => _contextLayout.IncludeCallSiteStackTrace; set => _contextLayout.IncludeCallSiteStackTrace = value; } /// <summary> /// Gets the array of custom attributes to be passed into the logevent context /// </summary> /// <docgen category='Layout Options' order='10' /> [ArrayParameter(typeof(TargetPropertyWithContext), "contextproperty")] public virtual IList<TargetPropertyWithContext> ContextProperties { get; } = new List<TargetPropertyWithContext>(); private IPropertyTypeConverter PropertyTypeConverter { get => _propertyTypeConverter ?? (_propertyTypeConverter = ConfigurationItemFactory.Default.PropertyTypeConverter); set => _propertyTypeConverter = value; } private IPropertyTypeConverter _propertyTypeConverter; /// <summary> /// Constructor /// </summary> protected TargetWithContext() { _contextLayout = _contextLayout ?? new TargetWithContextLayout(this, base.Layout); OptimizeBufferReuse = true; } /// <inheritdoc/> protected override void CloseTarget() { PropertyTypeConverter = null; base.CloseTarget(); } /// <summary> /// Check if logevent has properties (or context properties) /// </summary> /// <param name="logEvent"></param> /// <returns>True if properties should be included</returns> protected bool ShouldIncludeProperties(LogEventInfo logEvent) { return IncludeGdc || IncludeMdc #if !SILVERLIGHT || IncludeMdlc #endif || (IncludeEventProperties && (logEvent?.HasProperties ?? false)); } /// <summary> /// Checks if any context properties, and if any returns them as a single dictionary /// </summary> /// <param name="logEvent"></param> /// <returns>Dictionary with any context properties for the logEvent (Null if none found)</returns> protected IDictionary<string, object> GetContextProperties(LogEventInfo logEvent) { return GetContextProperties(logEvent, null); } /// <summary> /// Checks if any context properties, and if any returns them as a single dictionary /// </summary> /// <param name="logEvent"></param> /// <param name="combinedProperties">Optional prefilled dictionary</param> /// <returns>Dictionary with any context properties for the logEvent (Null if none found)</returns> protected IDictionary<string, object> GetContextProperties(LogEventInfo logEvent, IDictionary<string, object> combinedProperties) { if (ContextProperties?.Count > 0) { combinedProperties = CaptureContextProperties(logEvent, combinedProperties); } #if !SILVERLIGHT if (IncludeMdlc && !CombineProperties(logEvent, _contextLayout.MdlcLayout, ref combinedProperties)) { combinedProperties = CaptureContextMdlc(logEvent, combinedProperties); } #endif if (IncludeMdc && !CombineProperties(logEvent, _contextLayout.MdcLayout, ref combinedProperties)) { combinedProperties = CaptureContextMdc(logEvent, combinedProperties); } if (IncludeGdc) { combinedProperties = CaptureContextGdc(logEvent, combinedProperties); } return combinedProperties; } /// <summary> /// Creates combined dictionary of all configured properties for logEvent /// </summary> /// <param name="logEvent"></param> /// <returns>Dictionary with all collected properties for logEvent</returns> protected IDictionary<string, object> GetAllProperties(LogEventInfo logEvent) { return GetAllProperties(logEvent, null); } /// <summary> /// Creates combined dictionary of all configured properties for logEvent /// </summary> /// <param name="logEvent"></param> /// <param name="combinedProperties">Optional prefilled dictionary</param> /// <returns>Dictionary with all collected properties for logEvent</returns> protected IDictionary<string, object> GetAllProperties(LogEventInfo logEvent, IDictionary<string, object> combinedProperties) { if (IncludeEventProperties && logEvent.HasProperties) { // TODO Make Dictionary-Lazy-adapter for PropertiesDictionary to skip extra Dictionary-allocation combinedProperties = combinedProperties ?? CreateNewDictionary(logEvent.Properties.Count + (ContextProperties?.Count ?? 0)); bool checkForDuplicates = combinedProperties.Count > 0; foreach (var property in logEvent.Properties) { string propertyKey = property.Key.ToString(); if (string.IsNullOrEmpty(propertyKey)) continue; AddContextProperty(logEvent, propertyKey, property.Value, checkForDuplicates, combinedProperties); } } combinedProperties = GetContextProperties(logEvent, combinedProperties); return combinedProperties ?? new Dictionary<string, object>(); } private static IDictionary<string, object> CreateNewDictionary(int initialCapacity) { return new Dictionary<string, object>(Math.Max(initialCapacity, 3)); } /// <summary> /// Generates a new unique name, when duplicate names are detected /// </summary> /// <param name="logEvent">LogEvent that triggered the duplicate name</param> /// <param name="itemName">Duplicate item name</param> /// <param name="itemValue">Item Value</param> /// <param name="combinedProperties">Dictionary of context values</param> /// <returns>New (unique) value (or null to skip value). If the same value is used then the item will be overwritten</returns> protected virtual string GenerateUniqueItemName(LogEventInfo logEvent, string itemName, object itemValue, IDictionary<string, object> combinedProperties) { itemName = itemName ?? string.Empty; int newNameIndex = 1; var newItemName = string.Concat(itemName, "_1"); while (combinedProperties.ContainsKey(newItemName)) { newItemName = string.Concat(itemName, "_", (++newNameIndex).ToString()); } return newItemName; } private bool CombineProperties(LogEventInfo logEvent, Layout contextLayout, ref IDictionary<string, object> combinedProperties) { if (!logEvent.TryGetCachedLayoutValue(contextLayout, out object value)) { return false; } if (value is IDictionary<string, object> contextProperties) { if (combinedProperties != null) { bool checkForDuplicates = combinedProperties.Count > 0; foreach (var property in contextProperties) { AddContextProperty(logEvent, property.Key, property.Value, checkForDuplicates, combinedProperties); } } else { combinedProperties = contextProperties; } } return true; } private void AddContextProperty(LogEventInfo logEvent, string itemName, object itemValue, bool checkForDuplicates, IDictionary<string, object> combinedProperties) { if (checkForDuplicates && combinedProperties.ContainsKey(itemName)) { itemName = GenerateUniqueItemName(logEvent, itemName, itemValue, combinedProperties); if (itemName == null) return; } combinedProperties[itemName] = itemValue; } /// <summary> /// Returns the captured snapshot of <see cref="MappedDiagnosticsContext"/> for the <see cref="LogEventInfo"/> /// </summary> /// <param name="logEvent"></param> /// <returns>Dictionary with MDC context if any, else null</returns> protected IDictionary<string, object> GetContextMdc(LogEventInfo logEvent) { if (logEvent.TryGetCachedLayoutValue(_contextLayout.MdcLayout, out object value)) { return value as IDictionary<string, object>; } return CaptureContextMdc(logEvent, null); } #if !SILVERLIGHT /// <summary> /// Returns the captured snapshot of <see cref="MappedDiagnosticsLogicalContext"/> for the <see cref="LogEventInfo"/> /// </summary> /// <param name="logEvent"></param> /// <returns>Dictionary with MDLC context if any, else null</returns> protected IDictionary<string, object> GetContextMdlc(LogEventInfo logEvent) { if (logEvent.TryGetCachedLayoutValue(_contextLayout.MdlcLayout, out object value)) { return value as IDictionary<string, object>; } return CaptureContextMdlc(logEvent, null); } #endif /// <summary> /// Returns the captured snapshot of <see cref="NestedDiagnosticsContext"/> for the <see cref="LogEventInfo"/> /// </summary> /// <param name="logEvent"></param> /// <returns>Dictionary with NDC context if any, else null</returns> protected IList<object> GetContextNdc(LogEventInfo logEvent) { if (logEvent.TryGetCachedLayoutValue(_contextLayout.NdcLayout, out object value)) { return value as IList<object>; } return CaptureContextNdc(logEvent); } #if !SILVERLIGHT /// <summary> /// Returns the captured snapshot of <see cref="NestedDiagnosticsLogicalContext"/> for the <see cref="LogEventInfo"/> /// </summary> /// <param name="logEvent"></param> /// <returns>Dictionary with NDLC context if any, else null</returns> protected IList<object> GetContextNdlc(LogEventInfo logEvent) { if (logEvent.TryGetCachedLayoutValue(_contextLayout.NdlcLayout, out object value)) { return value as IList<object>; } return CaptureContextNdlc(logEvent); } #endif private IDictionary<string, object> CaptureContextProperties(LogEventInfo logEvent, IDictionary<string, object> combinedProperties) { combinedProperties = combinedProperties ?? CreateNewDictionary(ContextProperties.Count); for (int i = 0; i < ContextProperties.Count; ++i) { var contextProperty = ContextProperties[i]; if (string.IsNullOrEmpty(contextProperty?.Name) || contextProperty.Layout == null) continue; try { if (TryGetContextPropertyValue(logEvent, contextProperty, out var propertyValue)) { combinedProperties[contextProperty.Name] = propertyValue; } } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; Common.InternalLogger.Warn(ex, "{0}(Name={1}): Failed to add context property {2}", GetType(), Name, contextProperty.Name); } } return combinedProperties; } private bool TryGetContextPropertyValue(LogEventInfo logEvent, TargetPropertyWithContext contextProperty, out object propertyValue) { var propertyType = contextProperty.PropertyType ?? typeof(string); var isStringType = propertyType == typeof(string); if (!isStringType && contextProperty.Layout.TryGetRawValue(logEvent, out var rawValue)) { if (propertyType == typeof(object)) { propertyValue = rawValue; return contextProperty.IncludeEmptyValue || propertyValue != null; } else if (rawValue?.GetType() == propertyType) { propertyValue = rawValue; return true; } } var propertyStringValue = RenderLogEvent(contextProperty.Layout, logEvent) ?? string.Empty; if (!contextProperty.IncludeEmptyValue && string.IsNullOrEmpty(propertyStringValue)) { propertyValue = null; return false; } if (isStringType) { propertyValue = propertyStringValue; return true; } if (string.IsNullOrEmpty(propertyStringValue) && propertyType.IsValueType()) { propertyValue = Activator.CreateInstance(propertyType); return true; } propertyValue = PropertyTypeConverter.Convert(propertyStringValue, propertyType, null, CultureInfo.InvariantCulture); return true; } /// <summary> /// Takes snapshot of <see cref="GlobalDiagnosticsContext"/> for the <see cref="LogEventInfo"/> /// </summary> /// <param name="logEvent"></param> /// <param name="contextProperties">Optional pre-allocated dictionary for the snapshot</param> /// <returns>Dictionary with GDC context if any, else null</returns> protected virtual IDictionary<string, object> CaptureContextGdc(LogEventInfo logEvent, IDictionary<string, object> contextProperties) { var globalNames = GlobalDiagnosticsContext.GetNames(); if (globalNames.Count == 0) return contextProperties; contextProperties = contextProperties ?? CreateNewDictionary(globalNames.Count); bool checkForDuplicates = contextProperties.Count > 0; foreach (string propertyName in globalNames) { var propertyValue = GlobalDiagnosticsContext.GetObject(propertyName); if (SerializeItemValue(logEvent, propertyName, propertyValue, out propertyValue)) { AddContextProperty(logEvent, propertyName, propertyValue, checkForDuplicates, contextProperties); } } return contextProperties; } /// <summary> /// Takes snapshot of <see cref="MappedDiagnosticsContext"/> for the <see cref="LogEventInfo"/> /// </summary> /// <param name="logEvent"></param> /// <param name="contextProperties">Optional pre-allocated dictionary for the snapshot</param> /// <returns>Dictionary with MDC context if any, else null</returns> protected virtual IDictionary<string, object> CaptureContextMdc(LogEventInfo logEvent, IDictionary<string, object> contextProperties) { var names = MappedDiagnosticsContext.GetNames(); if (names.Count == 0) return contextProperties; contextProperties = contextProperties ?? CreateNewDictionary(names.Count); bool checkForDuplicates = contextProperties.Count > 0; foreach (var name in names) { object value = MappedDiagnosticsContext.GetObject(name); if (SerializeMdcItem(logEvent, name, value, out var serializedValue)) { AddContextProperty(logEvent, name, serializedValue, checkForDuplicates, contextProperties); } } return contextProperties; } /// <summary> /// Take snapshot of a single object value from <see cref="MappedDiagnosticsContext"/> /// </summary> /// <param name="logEvent">Log event</param> /// <param name="name">MDC key</param> /// <param name="value">MDC value</param> /// <param name="serializedValue">Snapshot of MDC value</param> /// <returns>Include object value in snapshot</returns> protected virtual bool SerializeMdcItem(LogEventInfo logEvent, string name, object value, out object serializedValue) { if (string.IsNullOrEmpty(name)) { serializedValue = null; return false; } return SerializeItemValue(logEvent, name, value, out serializedValue); } #if !SILVERLIGHT /// <summary> /// Takes snapshot of <see cref="MappedDiagnosticsLogicalContext"/> for the <see cref="LogEventInfo"/> /// </summary> /// <param name="logEvent"></param> /// <param name="contextProperties">Optional pre-allocated dictionary for the snapshot</param> /// <returns>Dictionary with MDLC context if any, else null</returns> protected virtual IDictionary<string, object> CaptureContextMdlc(LogEventInfo logEvent, IDictionary<string, object> contextProperties) { var names = MappedDiagnosticsLogicalContext.GetNames(); if (names.Count == 0) return contextProperties; contextProperties = contextProperties ?? CreateNewDictionary(names.Count); bool checkForDuplicates = contextProperties.Count > 0; foreach (var name in names) { object value = MappedDiagnosticsLogicalContext.GetObject(name); if (SerializeMdlcItem(logEvent, name, value, out var serializedValue)) { AddContextProperty(logEvent, name, serializedValue, checkForDuplicates, contextProperties); } } return contextProperties; } /// <summary> /// Take snapshot of a single object value from <see cref="MappedDiagnosticsLogicalContext"/> /// </summary> /// <param name="logEvent">Log event</param> /// <param name="name">MDLC key</param> /// <param name="value">MDLC value</param> /// <param name="serializedValue">Snapshot of MDLC value</param> /// <returns>Include object value in snapshot</returns> protected virtual bool SerializeMdlcItem(LogEventInfo logEvent, string name, object value, out object serializedValue) { if (string.IsNullOrEmpty(name)) { serializedValue = null; return false; } return SerializeItemValue(logEvent, name, value, out serializedValue); } #endif /// <summary> /// Takes snapshot of <see cref="NestedDiagnosticsContext"/> for the <see cref="LogEventInfo"/> /// </summary> /// <param name="logEvent"></param> /// <returns>Dictionary with NDC context if any, else null</returns> protected virtual IList<object> CaptureContextNdc(LogEventInfo logEvent) { var stack = NestedDiagnosticsContext.GetAllObjects(); if (stack.Length == 0) return stack; IList<object> filteredStack = null; for (int i = 0; i < stack.Length; ++i) { var ndcValue = stack[i]; if (SerializeNdcItem(logEvent, ndcValue, out var serializedValue)) { if (filteredStack != null) filteredStack.Add(serializedValue); else stack[i] = serializedValue; } else { if (filteredStack == null) { filteredStack = new List<object>(stack.Length); for (int j = 0; j < i; ++j) filteredStack.Add(stack[j]); } } } return filteredStack ?? stack; } /// <summary> /// Take snapshot of a single object value from <see cref="NestedDiagnosticsContext"/> /// </summary> /// <param name="logEvent">Log event</param> /// <param name="value">NDC value</param> /// <param name="serializedValue">Snapshot of NDC value</param> /// <returns>Include object value in snapshot</returns> protected virtual bool SerializeNdcItem(LogEventInfo logEvent, object value, out object serializedValue) { return SerializeItemValue(logEvent, null, value, out serializedValue); } #if !SILVERLIGHT /// <summary> /// Takes snapshot of <see cref="NestedDiagnosticsLogicalContext"/> for the <see cref="LogEventInfo"/> /// </summary> /// <param name="logEvent"></param> /// <returns>Dictionary with NDLC context if any, else null</returns> protected virtual IList<object> CaptureContextNdlc(LogEventInfo logEvent) { var stack = NestedDiagnosticsLogicalContext.GetAllObjects(); if (stack.Length == 0) return stack; IList<object> filteredStack = null; for (int i = 0; i < stack.Length; ++i) { var ndcValue = stack[i]; if (SerializeNdlcItem(logEvent, ndcValue, out var serializedValue)) { if (filteredStack != null) filteredStack.Add(serializedValue); else stack[i] = serializedValue; } else { if (filteredStack == null) { filteredStack = new List<object>(stack.Length); for (int j = 0; j < i; ++j) filteredStack.Add(stack[j]); } } } return filteredStack ?? stack; } /// <summary> /// Take snapshot of a single object value from <see cref="NestedDiagnosticsLogicalContext"/> /// </summary> /// <param name="logEvent">Log event</param> /// <param name="value">NDLC value</param> /// <param name="serializedValue">Snapshot of NDLC value</param> /// <returns>Include object value in snapshot</returns> protected virtual bool SerializeNdlcItem(LogEventInfo logEvent, object value, out object serializedValue) { return SerializeItemValue(logEvent, null, value, out serializedValue); } #endif /// <summary> /// Take snapshot of a single object value /// </summary> /// <param name="logEvent">Log event</param> /// <param name="name">Key Name (null when NDC / NDLC)</param> /// <param name="value">Object Value</param> /// <param name="serializedValue">Snapshot of value</param> /// <returns>Include object value in snapshot</returns> protected virtual bool SerializeItemValue(LogEventInfo logEvent, string name, object value, out object serializedValue) { if (value == null) { serializedValue = null; return true; } if (value is string || Convert.GetTypeCode(value) != TypeCode.Object || value is Guid || value is TimeSpan || value is DateTimeOffset) { serializedValue = value; // Already immutable, snapshot is not needed return true; } // Make snapshot of the context value serializedValue = Convert.ToString(value, logEvent.FormatProvider ?? LoggingConfiguration?.DefaultCultureInfo); return true; } [ThreadSafe] [ThreadAgnostic] private class TargetWithContextLayout : Layout, IIncludeContext, IUsesStackTrace { public Layout TargetLayout { get => _targetLayout; set => _targetLayout = ReferenceEquals(this, value) ? _targetLayout : value; } private Layout _targetLayout; /// <summary>Internal Layout that allows capture of MDC context</summary> internal LayoutContextMdc MdcLayout { get; } /// <summary>Internal Layout that allows capture of NDC context</summary> internal LayoutContextNdc NdcLayout { get; } #if !SILVERLIGHT /// <summary>Internal Layout that allows capture of MDLC context</summary> internal LayoutContextMdlc MdlcLayout { get; } /// <summary>Internal Layout that allows capture of NDLC context</summary> internal LayoutContextNdlc NdlcLayout { get; } #endif public bool IncludeAllProperties { get; set; } public bool IncludeCallSite { get; set; } public bool IncludeCallSiteStackTrace { get; set; } public bool IncludeMdc { get => MdcLayout.IsActive; set => MdcLayout.IsActive = value; } public bool IncludeNdc { get => NdcLayout.IsActive; set => NdcLayout.IsActive = value; } #if !SILVERLIGHT public bool IncludeMdlc { get => MdlcLayout.IsActive; set => MdlcLayout.IsActive = value; } public bool IncludeNdlc { get => NdlcLayout.IsActive; set => NdlcLayout.IsActive = value; } #endif StackTraceUsage IUsesStackTrace.StackTraceUsage { get { if (IncludeCallSiteStackTrace) { #if !SILVERLIGHT return StackTraceUsage.WithSource; #else return StackTraceUsage.Max; #endif } if (IncludeCallSite) { return StackTraceUsage.WithoutSource; } return StackTraceUsage.None; } } public TargetWithContextLayout(TargetWithContext owner, Layout targetLayout) { TargetLayout = targetLayout; MdcLayout = new LayoutContextMdc(owner); NdcLayout = new LayoutContextNdc(owner); #if !SILVERLIGHT MdlcLayout = new LayoutContextMdlc(owner); NdlcLayout = new LayoutContextNdlc(owner); #endif } protected override void InitializeLayout() { base.InitializeLayout(); if (IncludeMdc || IncludeNdc) ThreadAgnostic = false; #if !SILVERLIGHT if (IncludeMdlc || IncludeNdlc) ThreadAgnostic = false; #endif if (IncludeAllProperties) MutableUnsafe = true; // TODO Need to convert Properties to an immutable state } public override string ToString() { return TargetLayout?.ToString() ?? base.ToString(); } public override void Precalculate(LogEventInfo logEvent) { if (!(TargetLayout?.ThreadAgnostic ?? true) || (TargetLayout?.MutableUnsafe ?? false)) { TargetLayout.Precalculate(logEvent); if (logEvent.TryGetCachedLayoutValue(TargetLayout, out var cachedLayout)) { // Also cache the result as belonging to this Layout, for fast lookup logEvent.AddCachedLayoutValue(this, cachedLayout); } } PrecalculateContext(logEvent); } internal override void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target) { if (!(TargetLayout?.ThreadAgnostic ?? true) || (TargetLayout?.MutableUnsafe ?? false)) { TargetLayout.PrecalculateBuilder(logEvent, target); if (logEvent.TryGetCachedLayoutValue(TargetLayout, out var cachedLayout)) { // Also cache the result as belonging to this Layout, for fast lookup logEvent.AddCachedLayoutValue(this, cachedLayout); } } PrecalculateContext(logEvent); } private void PrecalculateContext(LogEventInfo logEvent) { if (IncludeMdc) MdcLayout.Precalculate(logEvent); if (IncludeNdc) NdcLayout.Precalculate(logEvent); #if !SILVERLIGHT if (IncludeMdlc) MdlcLayout.Precalculate(logEvent); if (IncludeNdlc) NdlcLayout.Precalculate(logEvent); #endif } protected override string GetFormattedMessage(LogEventInfo logEvent) { return TargetLayout?.Render(logEvent) ?? string.Empty; } protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { TargetLayout?.RenderAppendBuilder(logEvent, target, false); } [ThreadSafe] public class LayoutContextMdc : Layout { private readonly TargetWithContext _owner; public bool IsActive { get; set; } public LayoutContextMdc(TargetWithContext owner) { _owner = owner; } protected override string GetFormattedMessage(LogEventInfo logEvent) { CaptureContext(logEvent); return string.Empty; } public override void Precalculate(LogEventInfo logEvent) { CaptureContext(logEvent); } private void CaptureContext(LogEventInfo logEvent) { if (IsActive) { var contextMdc = _owner.CaptureContextMdc(logEvent, null); logEvent.AddCachedLayoutValue(this, contextMdc); } } } #if !SILVERLIGHT [ThreadSafe] public class LayoutContextMdlc : Layout { private readonly TargetWithContext _owner; public bool IsActive { get; set; } public LayoutContextMdlc(TargetWithContext owner) { _owner = owner; } protected override string GetFormattedMessage(LogEventInfo logEvent) { CaptureContext(logEvent); return string.Empty; } public override void Precalculate(LogEventInfo logEvent) { CaptureContext(logEvent); } private void CaptureContext(LogEventInfo logEvent) { if (IsActive) { var contextMdlc = _owner.CaptureContextMdlc(logEvent, null); logEvent.AddCachedLayoutValue(this, contextMdlc); } } } #endif [ThreadSafe] public class LayoutContextNdc : Layout { private readonly TargetWithContext _owner; public bool IsActive { get; set; } public LayoutContextNdc(TargetWithContext owner) { _owner = owner; } protected override string GetFormattedMessage(LogEventInfo logEvent) { CaptureContext(logEvent); return string.Empty; } public override void Precalculate(LogEventInfo logEvent) { CaptureContext(logEvent); } private void CaptureContext(LogEventInfo logEvent) { if (IsActive) { var contextNdc = _owner.CaptureContextNdc(logEvent); logEvent.AddCachedLayoutValue(this, contextNdc); } } } #if !SILVERLIGHT [ThreadSafe] public class LayoutContextNdlc : Layout { private readonly TargetWithContext _owner; public bool IsActive { get; set; } public LayoutContextNdlc(TargetWithContext owner) { _owner = owner; } protected override string GetFormattedMessage(LogEventInfo logEvent) { CaptureContext(logEvent); return string.Empty; } public override void Precalculate(LogEventInfo logEvent) { CaptureContext(logEvent); } private void CaptureContext(LogEventInfo logEvent) { if (IsActive) { var contextNdlc = _owner.CaptureContextNdlc(logEvent); logEvent.AddCachedLayoutValue(this, contextNdlc); } } } #endif } } }
using System; using System.Collections.Generic; using RestSharp; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IRemoteAccessApi { /// <summary> /// Retrieve computer details /// </summary> /// <param name="depth">Recursion depth in response model</param> /// <returns>ComputerSet</returns> ComputerSet GetComputer (int? depth); /// <summary> /// Retrieve Jenkins details /// </summary> /// <returns>Hudson</returns> Hudson GetJenkins (); /// <summary> /// Retrieve job details /// </summary> /// <param name="name">Name of the job</param> /// <returns>FreeStyleProject</returns> FreeStyleProject GetJob (string name); /// <summary> /// Retrieve job configuration /// </summary> /// <param name="name">Name of the job</param> /// <returns>string</returns> string GetJobConfig (string name); /// <summary> /// Retrieve job&#39;s last build details /// </summary> /// <param name="name">Name of the job</param> /// <returns>FreeStyleBuild</returns> FreeStyleBuild GetJobLastBuild (string name); /// <summary> /// Retrieve job&#39;s build progressive text output /// </summary> /// <param name="name">Name of the job</param> /// <param name="number">Build number</param> /// <param name="start">Starting point of progressive text output</param> /// <returns></returns> void GetJobProgressiveText (string name, string number, string start); /// <summary> /// Retrieve queue details /// </summary> /// <returns>Queue</returns> Queue GetQueue (); /// <summary> /// Retrieve queued item details /// </summary> /// <param name="number">Queue number</param> /// <returns>Queue</returns> Queue GetQueueItem (string number); /// <summary> /// Retrieve view details /// </summary> /// <param name="name">Name of the view</param> /// <returns>ListView</returns> ListView GetView (string name); /// <summary> /// Retrieve view configuration /// </summary> /// <param name="name">Name of the view</param> /// <returns>string</returns> string GetViewConfig (string name); /// <summary> /// Retrieve Jenkins headers /// </summary> /// <returns></returns> void HeadJenkins (); /// <summary> /// Create a new job using job configuration, or copied from an existing job /// </summary> /// <param name="name">Name of the new job</param> /// <param name="from">Existing job to copy from</param> /// <param name="mode">Set to &#39;copy&#39; for copying an existing job</param> /// <param name="jenkinsCrumb">CSRF protection token</param> /// <param name="contentType">Content type header application/xml</param> /// <param name="body">Job configuration in config.xml format</param> /// <returns></returns> void PostCreateItem (string name, string from, string mode, string jenkinsCrumb, string contentType, string body); /// <summary> /// Create a new view using view configuration /// </summary> /// <param name="name">Name of the new view</param> /// <param name="jenkinsCrumb">CSRF protection token</param> /// <param name="contentType">Content type header application/xml</param> /// <param name="body">View configuration in config.xml format</param> /// <returns></returns> void PostCreateView (string name, string jenkinsCrumb, string contentType, string body); /// <summary> /// Build a job /// </summary> /// <param name="name">Name of the job</param> /// <param name="json"></param> /// <param name="token"></param> /// <param name="jenkinsCrumb">CSRF protection token</param> /// <returns></returns> void PostJobBuild (string name, string json, string token, string jenkinsCrumb); /// <summary> /// Update job configuration /// </summary> /// <param name="name">Name of the job</param> /// <param name="body">Job configuration in config.xml format</param> /// <param name="jenkinsCrumb">CSRF protection token</param> /// <returns></returns> void PostJobConfig (string name, string body, string jenkinsCrumb); /// <summary> /// Delete a job /// </summary> /// <param name="name">Name of the job</param> /// <param name="jenkinsCrumb">CSRF protection token</param> /// <returns></returns> void PostJobDelete (string name, string jenkinsCrumb); /// <summary> /// Disable a job /// </summary> /// <param name="name">Name of the job</param> /// <param name="jenkinsCrumb">CSRF protection token</param> /// <returns></returns> void PostJobDisable (string name, string jenkinsCrumb); /// <summary> /// Enable a job /// </summary> /// <param name="name">Name of the job</param> /// <param name="jenkinsCrumb">CSRF protection token</param> /// <returns></returns> void PostJobEnable (string name, string jenkinsCrumb); /// <summary> /// Stop a job /// </summary> /// <param name="name">Name of the job</param> /// <param name="jenkinsCrumb">CSRF protection token</param> /// <returns></returns> void PostJobLastBuildStop (string name, string jenkinsCrumb); /// <summary> /// Update view configuration /// </summary> /// <param name="name">Name of the view</param> /// <param name="body">View configuration in config.xml format</param> /// <param name="jenkinsCrumb">CSRF protection token</param> /// <returns></returns> void PostViewConfig (string name, string body, string jenkinsCrumb); } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public class RemoteAccessApi : IRemoteAccessApi { /// <summary> /// Initializes a new instance of the <see cref="RemoteAccessApi"/> class. /// </summary> /// <param name="apiClient"> an instance of ApiClient (optional)</param> /// <returns></returns> public RemoteAccessApi(ApiClient apiClient = null) { if (apiClient == null) // use the default one in Configuration this.ApiClient = Configuration.DefaultApiClient; else this.ApiClient = apiClient; } /// <summary> /// Initializes a new instance of the <see cref="RemoteAccessApi"/> class. /// </summary> /// <returns></returns> public RemoteAccessApi(String basePath) { this.ApiClient = new ApiClient(basePath); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <param name="basePath">The base path</param> /// <value>The base path</value> public void SetBasePath(String basePath) { this.ApiClient.BasePath = basePath; } /// <summary> /// Gets the base path of the API client. /// </summary> /// <param name="basePath">The base path</param> /// <value>The base path</value> public String GetBasePath(String basePath) { return this.ApiClient.BasePath; } /// <summary> /// Gets or sets the API client. /// </summary> /// <value>An instance of the ApiClient</value> public ApiClient ApiClient {get; set;} /// <summary> /// Retrieve computer details /// </summary> /// <param name="depth">Recursion depth in response model</param> /// <returns>ComputerSet</returns> public ComputerSet GetComputer (int? depth) { // verify the required parameter 'depth' is set if (depth == null) throw new ApiException(400, "Missing required parameter 'depth' when calling GetComputer"); var path = "/computer/api/json"; path = path.Replace("{format}", "json"); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; if (depth != null) queryParams.Add("depth", ApiClient.ParameterToString(depth)); // query parameter // authentication setting, if any String[] authSettings = new String[] { "jenkins_auth" }; // make the HTTP request IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetComputer: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling GetComputer: " + response.ErrorMessage, response.ErrorMessage); return (ComputerSet) ApiClient.Deserialize(response.Content, typeof(ComputerSet), response.Headers); } /// <summary> /// Retrieve Jenkins details /// </summary> /// <returns>Hudson</returns> public Hudson GetJenkins () { var path = "/api/json"; path = path.Replace("{format}", "json"); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; // authentication setting, if any String[] authSettings = new String[] { "jenkins_auth" }; // make the HTTP request IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetJenkins: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling GetJenkins: " + response.ErrorMessage, response.ErrorMessage); return (Hudson) ApiClient.Deserialize(response.Content, typeof(Hudson), response.Headers); } /// <summary> /// Retrieve job details /// </summary> /// <param name="name">Name of the job</param> /// <returns>FreeStyleProject</returns> public FreeStyleProject GetJob (string name) { // verify the required parameter 'name' is set if (name == null) throw new ApiException(400, "Missing required parameter 'name' when calling GetJob"); var path = "/job/{name}/api/json"; path = path.Replace("{format}", "json"); path = path.Replace("{" + "name" + "}", ApiClient.ParameterToString(name)); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; // authentication setting, if any String[] authSettings = new String[] { "jenkins_auth" }; // make the HTTP request IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetJob: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling GetJob: " + response.ErrorMessage, response.ErrorMessage); return (FreeStyleProject) ApiClient.Deserialize(response.Content, typeof(FreeStyleProject), response.Headers); } /// <summary> /// Retrieve job configuration /// </summary> /// <param name="name">Name of the job</param> /// <returns>string</returns> public string GetJobConfig (string name) { // verify the required parameter 'name' is set if (name == null) throw new ApiException(400, "Missing required parameter 'name' when calling GetJobConfig"); var path = "/job/{name}/config.xml"; path = path.Replace("{format}", "json"); path = path.Replace("{" + "name" + "}", ApiClient.ParameterToString(name)); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; // authentication setting, if any String[] authSettings = new String[] { "jenkins_auth" }; // make the HTTP request IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetJobConfig: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling GetJobConfig: " + response.ErrorMessage, response.ErrorMessage); return (string) ApiClient.Deserialize(response.Content, typeof(string), response.Headers); } /// <summary> /// Retrieve job&#39;s last build details /// </summary> /// <param name="name">Name of the job</param> /// <returns>FreeStyleBuild</returns> public FreeStyleBuild GetJobLastBuild (string name) { // verify the required parameter 'name' is set if (name == null) throw new ApiException(400, "Missing required parameter 'name' when calling GetJobLastBuild"); var path = "/job/{name}/lastBuild/api/json"; path = path.Replace("{format}", "json"); path = path.Replace("{" + "name" + "}", ApiClient.ParameterToString(name)); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; // authentication setting, if any String[] authSettings = new String[] { "jenkins_auth" }; // make the HTTP request IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetJobLastBuild: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling GetJobLastBuild: " + response.ErrorMessage, response.ErrorMessage); return (FreeStyleBuild) ApiClient.Deserialize(response.Content, typeof(FreeStyleBuild), response.Headers); } /// <summary> /// Retrieve job&#39;s build progressive text output /// </summary> /// <param name="name">Name of the job</param> /// <param name="number">Build number</param> /// <param name="start">Starting point of progressive text output</param> /// <returns></returns> public void GetJobProgressiveText (string name, string number, string start) { // verify the required parameter 'name' is set if (name == null) throw new ApiException(400, "Missing required parameter 'name' when calling GetJobProgressiveText"); // verify the required parameter 'number' is set if (number == null) throw new ApiException(400, "Missing required parameter 'number' when calling GetJobProgressiveText"); // verify the required parameter 'start' is set if (start == null) throw new ApiException(400, "Missing required parameter 'start' when calling GetJobProgressiveText"); var path = "/job/{name}/{number}/logText/progressiveText"; path = path.Replace("{format}", "json"); path = path.Replace("{" + "name" + "}", ApiClient.ParameterToString(name)); path = path.Replace("{" + "number" + "}", ApiClient.ParameterToString(number)); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; if (start != null) queryParams.Add("start", ApiClient.ParameterToString(start)); // query parameter // authentication setting, if any String[] authSettings = new String[] { "jenkins_auth" }; // make the HTTP request IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetJobProgressiveText: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling GetJobProgressiveText: " + response.ErrorMessage, response.ErrorMessage); return; } /// <summary> /// Retrieve queue details /// </summary> /// <returns>Queue</returns> public Queue GetQueue () { var path = "/queue/api/json"; path = path.Replace("{format}", "json"); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; // authentication setting, if any String[] authSettings = new String[] { "jenkins_auth" }; // make the HTTP request IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetQueue: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling GetQueue: " + response.ErrorMessage, response.ErrorMessage); return (Queue) ApiClient.Deserialize(response.Content, typeof(Queue), response.Headers); } /// <summary> /// Retrieve queued item details /// </summary> /// <param name="number">Queue number</param> /// <returns>Queue</returns> public Queue GetQueueItem (string number) { // verify the required parameter 'number' is set if (number == null) throw new ApiException(400, "Missing required parameter 'number' when calling GetQueueItem"); var path = "/queue/item/{number}/api/json"; path = path.Replace("{format}", "json"); path = path.Replace("{" + "number" + "}", ApiClient.ParameterToString(number)); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; // authentication setting, if any String[] authSettings = new String[] { "jenkins_auth" }; // make the HTTP request IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetQueueItem: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling GetQueueItem: " + response.ErrorMessage, response.ErrorMessage); return (Queue) ApiClient.Deserialize(response.Content, typeof(Queue), response.Headers); } /// <summary> /// Retrieve view details /// </summary> /// <param name="name">Name of the view</param> /// <returns>ListView</returns> public ListView GetView (string name) { // verify the required parameter 'name' is set if (name == null) throw new ApiException(400, "Missing required parameter 'name' when calling GetView"); var path = "/view/{name}/api/json"; path = path.Replace("{format}", "json"); path = path.Replace("{" + "name" + "}", ApiClient.ParameterToString(name)); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; // authentication setting, if any String[] authSettings = new String[] { "jenkins_auth" }; // make the HTTP request IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetView: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling GetView: " + response.ErrorMessage, response.ErrorMessage); return (ListView) ApiClient.Deserialize(response.Content, typeof(ListView), response.Headers); } /// <summary> /// Retrieve view configuration /// </summary> /// <param name="name">Name of the view</param> /// <returns>string</returns> public string GetViewConfig (string name) { // verify the required parameter 'name' is set if (name == null) throw new ApiException(400, "Missing required parameter 'name' when calling GetViewConfig"); var path = "/view/{name}/config.xml"; path = path.Replace("{format}", "json"); path = path.Replace("{" + "name" + "}", ApiClient.ParameterToString(name)); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; // authentication setting, if any String[] authSettings = new String[] { "jenkins_auth" }; // make the HTTP request IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetViewConfig: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling GetViewConfig: " + response.ErrorMessage, response.ErrorMessage); return (string) ApiClient.Deserialize(response.Content, typeof(string), response.Headers); } /// <summary> /// Retrieve Jenkins headers /// </summary> /// <returns></returns> public void HeadJenkins () { var path = "/api/json"; path = path.Replace("{format}", "json"); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; // authentication setting, if any String[] authSettings = new String[] { "jenkins_auth" }; // make the HTTP request IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.HEAD, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling HeadJenkins: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling HeadJenkins: " + response.ErrorMessage, response.ErrorMessage); return; } /// <summary> /// Create a new job using job configuration, or copied from an existing job /// </summary> /// <param name="name">Name of the new job</param> /// <param name="from">Existing job to copy from</param> /// <param name="mode">Set to &#39;copy&#39; for copying an existing job</param> /// <param name="jenkinsCrumb">CSRF protection token</param> /// <param name="contentType">Content type header application/xml</param> /// <param name="body">Job configuration in config.xml format</param> /// <returns></returns> public void PostCreateItem (string name, string from, string mode, string jenkinsCrumb, string contentType, string body) { // verify the required parameter 'name' is set if (name == null) throw new ApiException(400, "Missing required parameter 'name' when calling PostCreateItem"); var path = "/createItem"; path = path.Replace("{format}", "json"); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; if (name != null) queryParams.Add("name", ApiClient.ParameterToString(name)); // query parameter if (from != null) queryParams.Add("from", ApiClient.ParameterToString(from)); // query parameter if (mode != null) queryParams.Add("mode", ApiClient.ParameterToString(mode)); // query parameter if (jenkinsCrumb != null) headerParams.Add("Jenkins-Crumb", ApiClient.ParameterToString(jenkinsCrumb)); // header parameter if (contentType != null) headerParams.Add("Content-Type", ApiClient.ParameterToString(contentType)); // header parameter postBody = ApiClient.Serialize(body); // http body (model) parameter // authentication setting, if any String[] authSettings = new String[] { "jenkins_auth" }; // make the HTTP request IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling PostCreateItem: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling PostCreateItem: " + response.ErrorMessage, response.ErrorMessage); return; } /// <summary> /// Create a new view using view configuration /// </summary> /// <param name="name">Name of the new view</param> /// <param name="jenkinsCrumb">CSRF protection token</param> /// <param name="contentType">Content type header application/xml</param> /// <param name="body">View configuration in config.xml format</param> /// <returns></returns> public void PostCreateView (string name, string jenkinsCrumb, string contentType, string body) { // verify the required parameter 'name' is set if (name == null) throw new ApiException(400, "Missing required parameter 'name' when calling PostCreateView"); var path = "/createView"; path = path.Replace("{format}", "json"); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; if (name != null) queryParams.Add("name", ApiClient.ParameterToString(name)); // query parameter if (jenkinsCrumb != null) headerParams.Add("Jenkins-Crumb", ApiClient.ParameterToString(jenkinsCrumb)); // header parameter if (contentType != null) headerParams.Add("Content-Type", ApiClient.ParameterToString(contentType)); // header parameter postBody = ApiClient.Serialize(body); // http body (model) parameter // authentication setting, if any String[] authSettings = new String[] { "jenkins_auth" }; // make the HTTP request IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling PostCreateView: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling PostCreateView: " + response.ErrorMessage, response.ErrorMessage); return; } /// <summary> /// Build a job /// </summary> /// <param name="name">Name of the job</param> /// <param name="json"></param> /// <param name="token"></param> /// <param name="jenkinsCrumb">CSRF protection token</param> /// <returns></returns> public void PostJobBuild (string name, string json, string token, string jenkinsCrumb) { // verify the required parameter 'name' is set if (name == null) throw new ApiException(400, "Missing required parameter 'name' when calling PostJobBuild"); // verify the required parameter 'json' is set if (json == null) throw new ApiException(400, "Missing required parameter 'json' when calling PostJobBuild"); var path = "/job/{name}/build"; path = path.Replace("{format}", "json"); path = path.Replace("{" + "name" + "}", ApiClient.ParameterToString(name)); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; if (json != null) queryParams.Add("json", ApiClient.ParameterToString(json)); // query parameter if (token != null) queryParams.Add("token", ApiClient.ParameterToString(token)); // query parameter if (jenkinsCrumb != null) headerParams.Add("Jenkins-Crumb", ApiClient.ParameterToString(jenkinsCrumb)); // header parameter // authentication setting, if any String[] authSettings = new String[] { "jenkins_auth" }; // make the HTTP request IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling PostJobBuild: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling PostJobBuild: " + response.ErrorMessage, response.ErrorMessage); return; } /// <summary> /// Update job configuration /// </summary> /// <param name="name">Name of the job</param> /// <param name="body">Job configuration in config.xml format</param> /// <param name="jenkinsCrumb">CSRF protection token</param> /// <returns></returns> public void PostJobConfig (string name, string body, string jenkinsCrumb) { // verify the required parameter 'name' is set if (name == null) throw new ApiException(400, "Missing required parameter 'name' when calling PostJobConfig"); // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling PostJobConfig"); var path = "/job/{name}/config.xml"; path = path.Replace("{format}", "json"); path = path.Replace("{" + "name" + "}", ApiClient.ParameterToString(name)); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; if (jenkinsCrumb != null) headerParams.Add("Jenkins-Crumb", ApiClient.ParameterToString(jenkinsCrumb)); // header parameter postBody = ApiClient.Serialize(body); // http body (model) parameter // authentication setting, if any String[] authSettings = new String[] { "jenkins_auth" }; // make the HTTP request IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling PostJobConfig: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling PostJobConfig: " + response.ErrorMessage, response.ErrorMessage); return; } /// <summary> /// Delete a job /// </summary> /// <param name="name">Name of the job</param> /// <param name="jenkinsCrumb">CSRF protection token</param> /// <returns></returns> public void PostJobDelete (string name, string jenkinsCrumb) { // verify the required parameter 'name' is set if (name == null) throw new ApiException(400, "Missing required parameter 'name' when calling PostJobDelete"); var path = "/job/{name}/doDelete"; path = path.Replace("{format}", "json"); path = path.Replace("{" + "name" + "}", ApiClient.ParameterToString(name)); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; if (jenkinsCrumb != null) headerParams.Add("Jenkins-Crumb", ApiClient.ParameterToString(jenkinsCrumb)); // header parameter // authentication setting, if any String[] authSettings = new String[] { "jenkins_auth" }; // make the HTTP request IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling PostJobDelete: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling PostJobDelete: " + response.ErrorMessage, response.ErrorMessage); return; } /// <summary> /// Disable a job /// </summary> /// <param name="name">Name of the job</param> /// <param name="jenkinsCrumb">CSRF protection token</param> /// <returns></returns> public void PostJobDisable (string name, string jenkinsCrumb) { // verify the required parameter 'name' is set if (name == null) throw new ApiException(400, "Missing required parameter 'name' when calling PostJobDisable"); var path = "/job/{name}/disable"; path = path.Replace("{format}", "json"); path = path.Replace("{" + "name" + "}", ApiClient.ParameterToString(name)); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; if (jenkinsCrumb != null) headerParams.Add("Jenkins-Crumb", ApiClient.ParameterToString(jenkinsCrumb)); // header parameter // authentication setting, if any String[] authSettings = new String[] { "jenkins_auth" }; // make the HTTP request IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling PostJobDisable: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling PostJobDisable: " + response.ErrorMessage, response.ErrorMessage); return; } /// <summary> /// Enable a job /// </summary> /// <param name="name">Name of the job</param> /// <param name="jenkinsCrumb">CSRF protection token</param> /// <returns></returns> public void PostJobEnable (string name, string jenkinsCrumb) { // verify the required parameter 'name' is set if (name == null) throw new ApiException(400, "Missing required parameter 'name' when calling PostJobEnable"); var path = "/job/{name}/enable"; path = path.Replace("{format}", "json"); path = path.Replace("{" + "name" + "}", ApiClient.ParameterToString(name)); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; if (jenkinsCrumb != null) headerParams.Add("Jenkins-Crumb", ApiClient.ParameterToString(jenkinsCrumb)); // header parameter // authentication setting, if any String[] authSettings = new String[] { "jenkins_auth" }; // make the HTTP request IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling PostJobEnable: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling PostJobEnable: " + response.ErrorMessage, response.ErrorMessage); return; } /// <summary> /// Stop a job /// </summary> /// <param name="name">Name of the job</param> /// <param name="jenkinsCrumb">CSRF protection token</param> /// <returns></returns> public void PostJobLastBuildStop (string name, string jenkinsCrumb) { // verify the required parameter 'name' is set if (name == null) throw new ApiException(400, "Missing required parameter 'name' when calling PostJobLastBuildStop"); var path = "/job/{name}/lastBuild/stop"; path = path.Replace("{format}", "json"); path = path.Replace("{" + "name" + "}", ApiClient.ParameterToString(name)); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; if (jenkinsCrumb != null) headerParams.Add("Jenkins-Crumb", ApiClient.ParameterToString(jenkinsCrumb)); // header parameter // authentication setting, if any String[] authSettings = new String[] { "jenkins_auth" }; // make the HTTP request IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling PostJobLastBuildStop: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling PostJobLastBuildStop: " + response.ErrorMessage, response.ErrorMessage); return; } /// <summary> /// Update view configuration /// </summary> /// <param name="name">Name of the view</param> /// <param name="body">View configuration in config.xml format</param> /// <param name="jenkinsCrumb">CSRF protection token</param> /// <returns></returns> public void PostViewConfig (string name, string body, string jenkinsCrumb) { // verify the required parameter 'name' is set if (name == null) throw new ApiException(400, "Missing required parameter 'name' when calling PostViewConfig"); // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling PostViewConfig"); var path = "/view/{name}/config.xml"; path = path.Replace("{format}", "json"); path = path.Replace("{" + "name" + "}", ApiClient.ParameterToString(name)); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; if (jenkinsCrumb != null) headerParams.Add("Jenkins-Crumb", ApiClient.ParameterToString(jenkinsCrumb)); // header parameter postBody = ApiClient.Serialize(body); // http body (model) parameter // authentication setting, if any String[] authSettings = new String[] { "jenkins_auth" }; // make the HTTP request IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling PostViewConfig: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling PostViewConfig: " + response.ErrorMessage, response.ErrorMessage); return; } } }
// Copyright 2007-2012 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit { using System; using System.Collections.Generic; using System.Diagnostics; using Context; using Diagnostics.Introspection; using Events; using Exceptions; using Logging; using Magnum; using Magnum.Extensions; using Magnum.Reflection; using Monitoring; using Pipeline; using Pipeline.Configuration; using Stact; using Threading; using Util; /// <summary> /// A service bus is used to attach message handlers (services) to endpoints, as well as /// communicate with other service bus instances in a distributed application /// </summary> [DebuggerDisplay("{DebugDisplay}")] public class ServiceBus : IControlBus { static readonly ILog _log; ConsumerPool _consumerPool; int _consumerThreadLimit = Environment.ProcessorCount*4; ServiceBusInstancePerformanceCounters _counters; volatile bool _disposed; UntypedChannel _eventChannel; ChannelConnection _performanceCounterConnection; int _receiveThreadLimit = 1; TimeSpan _receiveTimeout = 3.Seconds(); IServiceContainer _serviceContainer; volatile bool _started; static ServiceBus() { try { _log = Logger.Get(typeof(ServiceBus)); } catch (Exception ex) { throw new ConfigurationException("log4net isn't referenced", ex); } } /// <summary> /// Creates an instance of the ServiceBus, which implements IServiceBus. This is normally /// not called and should be created using the ServiceBusConfigurator to ensure proper defaults /// and operation. /// </summary> public ServiceBus(IEndpoint endpointToListenOn, IEndpointCache endpointCache, bool enablePerformanceCounters) { ReceiveTimeout = TimeSpan.FromSeconds(3); Guard.AgainstNull(endpointToListenOn, "endpointToListenOn", "This parameter cannot be null"); Guard.AgainstNull(endpointCache, "endpointFactory", "This parameter cannot be null"); Endpoint = endpointToListenOn; EndpointCache = endpointCache; _eventChannel = new ChannelAdapter(); _serviceContainer = new ServiceContainer(this); OutboundPipeline = new OutboundPipelineConfigurator(this).Pipeline; InboundPipeline = InboundPipelineConfigurator.CreateDefault(this); ControlBus = this; if(enablePerformanceCounters) InitializePerformanceCounters(); } public int ConcurrentReceiveThreads { get { return _receiveThreadLimit; } set { if (_started) throw new ConfigurationException( "The receive thread limit cannot be changed once the bus is in motion. Beep! Beep!"); _receiveThreadLimit = value; } } public int MaximumConsumerThreads { get { return _consumerThreadLimit; } set { if (_started) throw new ConfigurationException( "The consumer thread limit cannot be changed once the bus is in motion. Beep! Beep!"); _consumerThreadLimit = value; } } public TimeSpan ReceiveTimeout { get { return _receiveTimeout; } set { if (_started) throw new ConfigurationException( "The receive timeout cannot be changed once the bus is in motion. Beep! Beep!"); _receiveTimeout = value; } } public TimeSpan ShutdownTimeout { get; set; } public UntypedChannel EventChannel { get { return _eventChannel; } } [UsedImplicitly] protected string DebugDisplay { get { return string.Format("{0}: ", Endpoint.Address); } } public IEndpointCache EndpointCache { get; private set; } public void Dispose() { Dispose(true); } public void Publish<T>(T message) where T : class { Publish(message, NoContext); } /// <summary> /// Publishes a message to all subscribed consumers for the message type /// </summary> /// <typeparam name="T">The type of the message</typeparam> /// <param name="message">The messages to be published</param> /// <param name="contextCallback">The callback to perform operations on the context</param> public void Publish<T>(T message, Action<IPublishContext<T>> contextCallback) where T : class { PublishContext<T> context = ContextStorage.CreatePublishContext(message); context.SetSourceAddress(Endpoint.Address.Uri); contextCallback(context); IList<Exception> exceptions = new List<Exception>(); int publishedCount = 0; foreach (var consumer in OutboundPipeline.Enumerate(context)) { try { consumer(context); publishedCount++; } catch (Exception ex) { _log.Error(string.Format("'{0}' threw an exception publishing message '{1}'", consumer.GetType().FullName, message.GetType().FullName), ex); exceptions.Add(ex); } } context.Complete(); if (publishedCount == 0) { context.NotifyNoSubscribers(); } _eventChannel.Send(new MessagePublished { MessageType = typeof(T), ConsumerCount = publishedCount, Duration = context.Duration, }); if (exceptions.Count > 0) throw new PublishException(typeof(T), exceptions); } public void Publish(object message) { if (message == null) throw new ArgumentNullException("message"); BusObjectPublisherCache.Instance[message.GetType()].Publish(this, message); } public void Publish(object message, Type messageType) { if (message == null) throw new ArgumentNullException("message"); if (messageType == null) throw new ArgumentNullException("messageType"); BusObjectPublisherCache.Instance[messageType].Publish(this, message); } public void Publish(object message, Action<IPublishContext> contextCallback) { if (message == null) throw new ArgumentNullException("message"); if (contextCallback == null) throw new ArgumentNullException("contextCallback"); BusObjectPublisherCache.Instance[message.GetType()].Publish(this, message, contextCallback); } public void Publish(object message, Type messageType, Action<IPublishContext> contextCallback) { if (message == null) throw new ArgumentNullException("message"); if (messageType == null) throw new ArgumentNullException("messageType"); if (contextCallback == null) throw new ArgumentNullException("contextCallback"); BusObjectPublisherCache.Instance[messageType].Publish(this, message, contextCallback); } /// <summary> /// <see cref="IServiceBus.Publish{T}"/>: this is a "dynamically" /// typed overload - give it an interface as its type parameter, /// and a loosely typed dictionary of values and the MassTransit /// underlying infrastructure will populate an object instance /// with the passed values. It actually does this with DynamicProxy /// in the background. /// </summary> /// <typeparam name="T">The type of the interface or /// non-sealed class with all-virtual members.</typeparam> /// <param name="bus">The bus to publish on.</param> /// <param name="values">The dictionary of values to place in the /// object instance to implement the interface.</param> public void Publish<T>(object values) where T : class { if (values == null) throw new ArgumentNullException("values"); var message = InterfaceImplementationExtensions.InitializeProxy<T>(values); Publish(message, x => { }); } /// <summary> /// <see cref="Publish{T}(MassTransit.IServiceBus,object)"/>: this /// overload further takes an action; it allows you to set <see cref="IPublishContext"/> /// meta-data. Also <see cref="IServiceBus.Publish{T}"/>. /// </summary> /// <typeparam name="T">The type of the message to publish</typeparam> /// <param name="bus">The bus to publish the message on.</param> /// <param name="values">The dictionary of values to become hydrated and /// published under the type of the interface.</param> /// <param name="contextCallback">The context callback.</param> public void Publish<T>(object values, Action<IPublishContext<T>> contextCallback) where T : class { if (values == null) throw new ArgumentNullException("values"); var message = InterfaceImplementationExtensions.InitializeProxy<T>(values); Publish(message, contextCallback); } public IOutboundMessagePipeline OutboundPipeline { get; private set; } public IInboundMessagePipeline InboundPipeline { get; private set; } /// <summary> /// The endpoint associated with this instance /// </summary> public IEndpoint Endpoint { get; private set; } public UnsubscribeAction Configure(Func<IInboundPipelineConfigurator, UnsubscribeAction> configure) { return InboundPipeline.Configure(configure); } [Obsolete("This method is being removed in favor of just using another bus instance.", false)] public IServiceBus ControlBus { get; set; } public IEndpoint GetEndpoint(Uri address) { return EndpointCache.GetEndpoint(address); } public void Inspect(DiagnosticsProbe probe) { new StandardDiagnosticsInfo().WriteCommonItems(probe); probe.Add("mt.version", typeof(IServiceBus).Assembly.GetName().Version); probe.Add("mt.receive_from", Endpoint.Address); probe.Add("mt.control_bus", ControlBus.Endpoint.Address); probe.Add("mt.max_consumer_threads", MaximumConsumerThreads); probe.Add("mt.concurrent_receive_threads", ConcurrentReceiveThreads); probe.Add("mt.receive_timeout", ReceiveTimeout); EndpointCache.Inspect(probe); _serviceContainer.Inspect(probe); OutboundPipeline.View(pipe => probe.Add("zz.mt.outbound_pipeline", pipe)); InboundPipeline.View(pipe => probe.Add("zz.mt.inbound_pipeline", pipe)); } public IBusService GetService(Type type) { return _serviceContainer.GetService(type); } public bool TryGetService(Type type, out IBusService result) { return _serviceContainer.TryGetService(type, out result); } void NoContext<T>(IPublishContext<T> context) where T : class { } public void Start() { if (_started) return; try { _serviceContainer.Start(); _consumerPool = new ThreadPoolConsumerPool(this, _eventChannel, _receiveTimeout) { MaximumConsumerCount = MaximumConsumerThreads, }; _consumerPool.Start(); } catch (Exception) { if (_consumerPool != null) _consumerPool.Dispose(); throw; } _started = true; } public void AddService(BusServiceLayer layer, IBusService service) { _serviceContainer.AddService(layer, service); } protected virtual void Dispose(bool disposing) { if (_disposed) return; if (disposing) { if (_consumerPool != null) { _consumerPool.Stop(); _consumerPool.Dispose(); _consumerPool = null; } if (_serviceContainer != null) { _serviceContainer.Stop(); _serviceContainer.Dispose(); _serviceContainer = null; } if (ControlBus != this) ControlBus.Dispose(); if (_performanceCounterConnection != null) { _performanceCounterConnection.Dispose(); _performanceCounterConnection = null; } _eventChannel = null; Endpoint = null; if (_counters != null) { _counters.Dispose(); _counters = null; } EndpointCache.Dispose(); } _disposed = true; } void InitializePerformanceCounters() { try { string instanceName = string.Format("{0}_{1}{2}", Endpoint.Address.Uri.Scheme, Endpoint.Address.Uri.Host, Endpoint.Address.Uri.AbsolutePath.Replace("/", "_")); _counters = new ServiceBusInstancePerformanceCounters(instanceName); _performanceCounterConnection = _eventChannel.Connect(x => { x.AddConsumerOf<MessageReceived>() .UsingConsumer(message => { _counters.ReceiveCount.Increment(); _counters.ReceiveRate.Increment(); _counters.ReceiveDuration.IncrementBy( (long)message.ReceiveDuration.TotalMilliseconds); _counters.ReceiveDurationBase.Increment(); _counters.ConsumerDuration.IncrementBy( (long)message.ConsumeDuration.TotalMilliseconds); _counters.ConsumerDurationBase.Increment(); }); x.AddConsumerOf<MessagePublished>() .UsingConsumer(message => { _counters.PublishCount.Increment(); _counters.PublishRate.Increment(); _counters.PublishDuration.IncrementBy((long)message.Duration.TotalMilliseconds); _counters.PublishDurationBase.Increment(); _counters.SentCount.IncrementBy(message.ConsumerCount); _counters.SendRate.IncrementBy(message.ConsumerCount); }); x.AddConsumerOf<ThreadPoolEvent>() .UsingConsumer(message => { _counters.ReceiveThreadCount.Set(message.ReceiverCount); _counters.ConsumerThreadCount.Set(message.ConsumerCount); }); }); } catch (Exception ex) { _log.Warn( "The performance counters could not be created, try running the program in the Administrator role. Just once.", ex); } } } }
using UnityEngine; using System.Collections; [System.Serializable] public class tk2dTextMeshData { public int version = 0; public tk2dFontData font; public string text = ""; public Color color = Color.white; public Color color2 = Color.white; public bool useGradient = false; public int textureGradient = 0; public TextAnchor anchor = TextAnchor.LowerLeft; public int renderLayer = 0; public Vector3 scale = Vector3.one; public bool kerning = false; public int maxChars = 16; public bool inlineStyling = false; public bool formatting = false; public int wordWrapWidth = 0; public float spacing = 0.0f; public float lineSpacing = 0.0f; } [ExecuteInEditMode] [RequireComponent(typeof(MeshFilter))] [RequireComponent(typeof(MeshRenderer))] [AddComponentMenu("2D Toolkit/Text/tk2dTextMesh")] /// <summary> /// Text mesh /// </summary> public class tk2dTextMesh : MonoBehaviour, tk2dRuntime.ISpriteCollectionForceBuild { tk2dFontData _fontInst; string _formattedText = ""; // This stuff now kept in tk2dTextMeshData. Remove in future version. [SerializeField] tk2dFontData _font = null; [SerializeField] string _text = ""; [SerializeField] Color _color = Color.white; [SerializeField] Color _color2 = Color.white; [SerializeField] bool _useGradient = false; [SerializeField] int _textureGradient = 0; [SerializeField] TextAnchor _anchor = TextAnchor.LowerLeft; [SerializeField] Vector3 _scale = new Vector3(1.0f, 1.0f, 1.0f); [SerializeField] bool _kerning = false; [SerializeField] int _maxChars = 16; [SerializeField] bool _inlineStyling = false; [SerializeField] bool _formatting = false; [SerializeField] int _wordWrapWidth = 0; [SerializeField] float spacing = 0.0f; [SerializeField] float lineSpacing = 0.0f; // Holding the data in this struct for the next version [SerializeField] tk2dTextMeshData data = new tk2dTextMeshData(); // Batcher needs to grab this public string FormattedText { get {return _formattedText;} } void UpgradeData() { if (data.version != 1) { data.font = _font; data.text = _text; data.color = _color; data.color2 = _color2; data.useGradient = _useGradient; data.textureGradient = _textureGradient; data.anchor = _anchor; data.scale = _scale; data.kerning = _kerning; data.maxChars = _maxChars; data.inlineStyling = _inlineStyling; data.formatting = _formatting; data.wordWrapWidth = _wordWrapWidth; data.spacing = spacing; data.lineSpacing = lineSpacing; } data.version = 1; } Vector3[] vertices; Vector2[] uvs; Vector2[] uv2; Color32[] colors; Color32[] untintedColors; static int GetInlineStyleCommandLength(int cmdSymbol) { int val = 0; switch (cmdSymbol) { case 'c': val = 5; break; // cRGBA case 'C': val = 9; break; // CRRGGBBAA case 'g': val = 9; break; // gRGBARGBA case 'G': val = 17; break; // GRRGGBBAARRGGBBAA } return val; } /// <summary> /// Formats the string using the current settings, and returns the formatted string. /// You can use this if you need to calculate how many lines your string is going to be wrapped to. /// </summary> public string FormatText(string unformattedString) { string returnValue = ""; FormatText(ref returnValue, unformattedString); return returnValue; } void FormatText() { FormatText(ref _formattedText, data.text); } void FormatText(ref string _targetString, string _source) { InitInstance(); if (formatting == false || wordWrapWidth == 0 || _fontInst.texelSize == Vector2.zero) { _targetString = _source; return; } float lineWidth = _fontInst.texelSize.x * wordWrapWidth; System.Text.StringBuilder target = new System.Text.StringBuilder(_source.Length); float widthSoFar = 0.0f; float wordStart = 0.0f; int targetWordStartIndex = -1; int fmtWordStartIndex = -1; bool ignoreNextCharacter = false; for (int i = 0; i < _source.Length; ++i) { char idx = _source[i]; tk2dFontChar chr; bool inlineHatChar = (idx == '^'); if (_fontInst.useDictionary) { if (!_fontInst.charDict.ContainsKey(idx)) idx = (char)0; chr = _fontInst.charDict[idx]; } else { if (idx >= _fontInst.chars.Length) idx = (char)0; // should be space chr = _fontInst.chars[idx]; } if (inlineHatChar) idx = '^'; if (ignoreNextCharacter) { ignoreNextCharacter = false; continue; } if (data.inlineStyling && idx == '^' && i + 1 < _source.Length) { if (_source[i + 1] == '^') { ignoreNextCharacter = true; target.Append('^'); // add the second hat that we'll skip } else { int cmdLength = GetInlineStyleCommandLength(_source[i + 1]); int skipLength = 1 + cmdLength; // The ^ plus the command for (int j = 0; j < skipLength; ++j) { if (i + j < _source.Length) { target.Append(_source[i + j]); } } i += skipLength - 1; continue; } } if (idx == '\n') { widthSoFar = 0.0f; wordStart = 0.0f; targetWordStartIndex = target.Length; fmtWordStartIndex = i; } else if (idx == ' '/* || idx == '.' || idx == ',' || idx == ':' || idx == ';' || idx == '!'*/) { /*if ((widthSoFar + chr.p1.x * data.scale.x) > lineWidth) { target.Append('\n'); widthSoFar = chr.advance * data.scale.x; } else {*/ widthSoFar += (chr.advance + data.spacing) * data.scale.x; //} wordStart = widthSoFar; targetWordStartIndex = target.Length; fmtWordStartIndex = i; } else { if ((widthSoFar + chr.p1.x * data.scale.x) > lineWidth) { // If the last word started after the start of the line if (wordStart > 0.0f) { wordStart = 0.0f; widthSoFar = 0.0f; // rewind target.Remove(targetWordStartIndex + 1, target.Length - targetWordStartIndex - 1); target.Append('\n'); i = fmtWordStartIndex; continue; // don't add this character } else { target.Append('\n'); widthSoFar = (chr.advance + data.spacing) * data.scale.x; } } else { widthSoFar += (chr.advance + data.spacing) * data.scale.x; } } target.Append(idx); } _targetString = target.ToString(); } [System.FlagsAttribute] enum UpdateFlags { UpdateNone = 0, UpdateText = 1, // update text vertices & uvs UpdateColors = 2, // only colors have changed UpdateBuffers = 4, // update buffers (maxchars has changed) }; UpdateFlags updateFlags = UpdateFlags.UpdateBuffers; Mesh mesh; MeshFilter meshFilter; void SetNeedUpdate(UpdateFlags uf) { if (updateFlags == UpdateFlags.UpdateNone) { updateFlags |= uf; tk2dUpdateManager.QueueCommit(this); } else { // Already queued updateFlags |= uf; } } // accessors /// <summary>Gets or sets the font. Call <see cref="Commit"/> to commit changes.</summary> public tk2dFontData font { get { UpgradeData(); return data.font; } set { UpgradeData(); data.font = value; _fontInst = data.font.inst; SetNeedUpdate( UpdateFlags.UpdateText ); UpdateMaterial(); } } /// <summary>Enables or disables formatting. Call <see cref="Commit"/> to commit changes.</summary> public bool formatting { get { UpgradeData(); return data.formatting; } set { UpgradeData(); if (data.formatting != value) { data.formatting = value; SetNeedUpdate( UpdateFlags.UpdateText ); } } } /// <summary>Change word wrap width. This only works when formatting is enabled. /// Call <see cref="Commit"/> to commit changes.</summary> public int wordWrapWidth { get { UpgradeData(); return data.wordWrapWidth; } set { UpgradeData(); if (data.wordWrapWidth != value) { data.wordWrapWidth = value; SetNeedUpdate(UpdateFlags.UpdateText); } } } /// <summary>Gets or sets the text. Call <see cref="Commit"/> to commit changes.</summary> public string text { get { UpgradeData(); return data.text; } set { UpgradeData(); data.text = value; SetNeedUpdate(UpdateFlags.UpdateText); } } /// <summary>Gets or sets the color. Call <see cref="Commit"/> to commit changes.</summary> public Color color { get { UpgradeData(); return data.color; } set { UpgradeData(); data.color = value; SetNeedUpdate(UpdateFlags.UpdateColors); } } /// <summary>Gets or sets the secondary color (used in the gradient). Call <see cref="Commit"/> to commit changes.</summary> public Color color2 { get { UpgradeData(); return data.color2; } set { UpgradeData(); data.color2 = value; SetNeedUpdate(UpdateFlags.UpdateColors); } } /// <summary>Use vertex vertical gradient. Call <see cref="Commit"/> to commit changes.</summary> public bool useGradient { get { UpgradeData(); return data.useGradient; } set { UpgradeData(); data.useGradient = value; SetNeedUpdate(UpdateFlags.UpdateColors); } } /// <summary>Gets or sets the text anchor. Call <see cref="Commit"/> to commit changes.</summary> public TextAnchor anchor { get { UpgradeData(); return data.anchor; } set { UpgradeData(); data.anchor = value; SetNeedUpdate(UpdateFlags.UpdateText); } } /// <summary>Gets or sets the scale. Call <see cref="Commit"/> to commit changes.</summary> public Vector3 scale { get { UpgradeData(); return data.scale; } set { UpgradeData(); data.scale = value; SetNeedUpdate(UpdateFlags.UpdateText); } } /// <summary>Gets or sets kerning state. Call <see cref="Commit"/> to commit changes.</summary> public bool kerning { get { UpgradeData(); return data.kerning; } set { UpgradeData(); data.kerning = value; SetNeedUpdate(UpdateFlags.UpdateText); } } /// <summary>Gets or sets maxChars. Call <see cref="Commit"/> to commit changes. /// NOTE: This will free & allocate memory, avoid using at runtime. /// </summary> public int maxChars { get { UpgradeData(); return data.maxChars; } set { UpgradeData(); data.maxChars = value; SetNeedUpdate(UpdateFlags.UpdateBuffers); } } /// <summary>Gets or sets the default texture gradient. /// You can also change texture gradient inline by using ^1 - ^9 sequences within your text. /// Call <see cref="Commit"/> to commit changes.</summary> public int textureGradient { get { UpgradeData(); return data.textureGradient; } set { UpgradeData(); data.textureGradient = value % font.gradientCount; SetNeedUpdate(UpdateFlags.UpdateText); } } /// <summary>Enables or disables inline styling (texture gradient). Call <see cref="Commit"/> to commit changes.</summary> public bool inlineStyling { get { UpgradeData(); return data.inlineStyling; } set { UpgradeData(); data.inlineStyling = value; SetNeedUpdate(UpdateFlags.UpdateText); } } /// <summary>Additional spacing between characters. /// This can be negative to bring characters closer together. /// Call <see cref="Commit"/> to commit changes.</summary> public float Spacing { get { UpgradeData(); return data.spacing; } set { UpgradeData(); if (data.spacing != value) { data.spacing = value; SetNeedUpdate(UpdateFlags.UpdateText); } } } /// <summary>Additional line spacing for multieline text. /// This can be negative to bring lines closer together. /// Call <see cref="Commit"/> to commit changes.</summary> public float LineSpacing { get { UpgradeData(); return data.lineSpacing; } set { UpgradeData(); if (data.lineSpacing != value) { data.lineSpacing = value; SetNeedUpdate(UpdateFlags.UpdateText); } } } /// <summary> /// Gets or sets the sorting order /// The sorting order lets you override draw order for sprites which are at the same z position /// It is similar to offsetting in z - the sprite stays at the original position /// This corresponds to the renderer.sortingOrder property in Unity 4.3 /// </summary> public int SortingOrder { get { #if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) return data.renderLayer; #else return CachedRenderer.sortingOrder; #endif } set { #if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) if (data.renderLayer != value) { data.renderLayer = value; SetNeedUpdate(UpdateFlags.UpdateText); } #else if (CachedRenderer.sortingOrder != value) { data.renderLayer = value; // for awake CachedRenderer.sortingOrder = value; #if UNITY_EDITOR tk2dUtil.SetDirty(CachedRenderer); #endif } #endif } } void InitInstance() { if (data != null && data.font != null) { _fontInst = data.font.inst; _fontInst.InitDictionary(); } } #if UNITY_EDITOR void OnValidate() { MeshFilter meshFilter = GetComponent<MeshFilter>(); if (meshFilter != null) { meshFilter.sharedMesh = mesh; } } #endif Renderer _cachedRenderer = null; Renderer CachedRenderer { get { if (_cachedRenderer == null) { _cachedRenderer = GetComponent<Renderer>(); } return _cachedRenderer; } } // Use this for initialization void Awake() { UpgradeData(); if (data.font != null) _fontInst = data.font.inst; // force rebuild when awakened, for when the object has been pooled, etc // this is probably not the best way to do it updateFlags = UpdateFlags.UpdateBuffers; if (data.font != null) { Init(); UpdateMaterial(); } // Sensibly reset, so tk2dUpdateManager can deal with this properly updateFlags = UpdateFlags.UpdateNone; } #if UNITY_EDITOR private void OnEnable() { if (GetComponent<Renderer>() != null && data != null && data.font != null && data.font.inst != null && GetComponent<Renderer>().sharedMaterial == null && data.font.inst.needMaterialInstance) { ForceBuild(); } } #endif protected void OnDestroy() { if (meshFilter == null) { meshFilter = GetComponent<MeshFilter>(); } if (meshFilter != null) { mesh = meshFilter.sharedMesh; } if (mesh) { DestroyImmediate(mesh, true); meshFilter.mesh = null; } } bool useInlineStyling { get { return inlineStyling && _fontInst.textureGradients; } } /// <summary> /// Returns the number of characters drawn for the currently active string. /// This may be less than string.Length - some characters are used as escape codes for switching texture gradient ^0-^9 /// Also, there might be more characters in the string than have been allocated for the textmesh, in which case /// the string will be truncated. /// </summary> public int NumDrawnCharacters() { int charsDrawn = NumTotalCharacters(); if (charsDrawn > data.maxChars) charsDrawn = data.maxChars; return charsDrawn; } /// <summary> /// Returns the number of characters excluding texture gradient escape codes. /// </summary> public int NumTotalCharacters() { InitInstance(); if ((updateFlags & (UpdateFlags.UpdateText | UpdateFlags.UpdateBuffers)) != 0) FormatText(); int numChars = 0; for (int i = 0; i < _formattedText.Length; ++i) { int idx = _formattedText[i]; bool inlineHatChar = (idx == '^'); if (_fontInst.useDictionary) { if (!_fontInst.charDict.ContainsKey(idx)) idx = 0; } else { if (idx >= _fontInst.chars.Length) idx = 0; // should be space } if (inlineHatChar) idx = '^'; if (idx == '\n') { continue; } else if (data.inlineStyling) { if (idx == '^' && i + 1 < _formattedText.Length) { if (_formattedText[i + 1] == '^') { ++i; } else { i += GetInlineStyleCommandLength(_formattedText[i + 1]); continue; } } } ++numChars; } return numChars; } [System.Obsolete("Use GetEstimatedMeshBoundsForString().size instead")] public Vector2 GetMeshDimensionsForString(string str) { return tk2dTextGeomGen.GetMeshDimensionsForString(str, tk2dTextGeomGen.Data( data, _fontInst, _formattedText )); } /// <summary> /// Calculates an estimated bounds for the given string if it were rendered /// using the current settings. /// This expects an unformatted string and will wrap the string if required. /// </summary> public Bounds GetEstimatedMeshBoundsForString( string str ) { InitInstance(); tk2dTextGeomGen.GeomData geomData = tk2dTextGeomGen.Data( data, _fontInst, _formattedText ); Vector2 dims = tk2dTextGeomGen.GetMeshDimensionsForString( FormatText( str ), geomData); float offsetY = tk2dTextGeomGen.GetYAnchorForHeight(dims.y, geomData); float offsetX = tk2dTextGeomGen.GetXAnchorForWidth(dims.x, geomData); float lineHeight = (_fontInst.lineHeight + data.lineSpacing) * data.scale.y; return new Bounds( new Vector3(offsetX + dims.x * 0.5f, offsetY + dims.y * 0.5f + lineHeight, 0), Vector3.Scale(dims, new Vector3(1, -1, 1)) ); } public void Init(bool force) { if (force) { SetNeedUpdate(UpdateFlags.UpdateBuffers); } Init(); } public void Init() { if (_fontInst && ((updateFlags & UpdateFlags.UpdateBuffers) != 0 || mesh == null)) { _fontInst.InitDictionary(); FormatText(); var geomData = tk2dTextGeomGen.Data( data, _fontInst, _formattedText ); // volatile data int numVertices; int numIndices; tk2dTextGeomGen.GetTextMeshGeomDesc(out numVertices, out numIndices, geomData); vertices = new Vector3[numVertices]; uvs = new Vector2[numVertices]; colors = new Color32[numVertices]; untintedColors = new Color32[numVertices]; if (_fontInst.textureGradients) { uv2 = new Vector2[numVertices]; } int[] triangles = new int[numIndices]; int target = tk2dTextGeomGen.SetTextMeshGeom(vertices, uvs, uv2, untintedColors, 0, geomData); if (!_fontInst.isPacked) { Color32 topColor = data.color; Color32 bottomColor = data.useGradient ? data.color2 : data.color; for (int i = 0; i < numVertices; ++i) { Color32 c = ((i % 4) < 2) ? topColor : bottomColor; byte red = (byte)(((int)untintedColors[i].r * (int)c.r) / 255); byte green = (byte)(((int)untintedColors[i].g * (int)c.g) / 255); byte blue = (byte)(((int)untintedColors[i].b * (int)c.b) / 255); byte alpha = (byte)(((int)untintedColors[i].a * (int)c.a) / 255); if (_fontInst.premultipliedAlpha) { red = (byte)(((int)red * (int)alpha) / 255); green = (byte)(((int)green * (int)alpha) / 255); blue = (byte)(((int)blue * (int)alpha) / 255); } colors[i] = new Color32(red, green, blue, alpha); } } else { colors = untintedColors; } tk2dTextGeomGen.SetTextMeshIndices(triangles, 0, 0, geomData, target); if (mesh == null) { if (meshFilter == null) meshFilter = GetComponent<MeshFilter>(); mesh = new Mesh(); #if !UNITY_3_5 mesh.MarkDynamic(); #endif mesh.hideFlags = HideFlags.DontSave; meshFilter.mesh = mesh; } else { mesh.Clear(); } mesh.vertices = vertices; mesh.uv = uvs; if (font.textureGradients) { mesh.uv2 = uv2; } mesh.triangles = triangles; mesh.colors32 = colors; mesh.RecalculateBounds(); mesh.bounds = tk2dBaseSprite.AdjustedMeshBounds( mesh.bounds, data.renderLayer ); updateFlags = UpdateFlags.UpdateNone; } } /// <summary> /// Calling commit is no longer required on text meshes. /// You can still call commit to manually commit all changes so far in the frame. /// </summary> public void Commit() { tk2dUpdateManager.FlushQueues(); } // Do not call this, its meant fo internal use public void DoNotUse__CommitInternal() { // Make sure instance is set up, might not be when calling from Awake. InitInstance(); // make sure fonts dictionary is initialized properly before proceeding if (_fontInst == null) { return; } _fontInst.InitDictionary(); // Can come in here without anything initalized when // instantiated in code if ((updateFlags & UpdateFlags.UpdateBuffers) != 0 || mesh == null) { Init(); } else { if ((updateFlags & UpdateFlags.UpdateText) != 0) { FormatText(); var geomData = tk2dTextGeomGen.Data( data, _fontInst, _formattedText ); int target = tk2dTextGeomGen.SetTextMeshGeom(vertices, uvs, uv2, untintedColors, 0, geomData); for (int i = target; i < data.maxChars; ++i) { // was/is unnecessary to fill anything else vertices[i * 4 + 0] = vertices[i * 4 + 1] = vertices[i * 4 + 2] = vertices[i * 4 + 3] = Vector3.zero; } mesh.vertices = vertices; mesh.uv = uvs; if (_fontInst.textureGradients) { mesh.uv2 = uv2; } if (_fontInst.isPacked) { colors = untintedColors; mesh.colors32 = colors; } if (data.inlineStyling) { SetNeedUpdate(UpdateFlags.UpdateColors); } mesh.RecalculateBounds(); mesh.bounds = tk2dBaseSprite.AdjustedMeshBounds( mesh.bounds, data.renderLayer ); } if (!font.isPacked && (updateFlags & UpdateFlags.UpdateColors) != 0) // packed fonts don't support tinting { Color32 topColor = data.color; Color32 bottomColor = data.useGradient ? data.color2 : data.color; for (int i = 0; i < colors.Length; ++i) { Color32 c = ((i % 4) < 2) ? topColor : bottomColor; byte red = (byte)(((int)untintedColors[i].r * (int)c.r) / 255); byte green = (byte)(((int)untintedColors[i].g * (int)c.g) / 255); byte blue = (byte)(((int)untintedColors[i].b * (int)c.b) / 255); byte alpha = (byte)(((int)untintedColors[i].a * (int)c.a) / 255); if (_fontInst.premultipliedAlpha) { red = (byte)(((int)red * (int)alpha) / 255); green = (byte)(((int)green * (int)alpha) / 255); blue = (byte)(((int)blue * (int)alpha) / 255); } colors[i] = new Color32(red, green, blue, alpha); } mesh.colors32 = colors; } } updateFlags = UpdateFlags.UpdateNone; } /// <summary> /// Makes the text mesh pixel perfect to the active camera. /// Automatically detects <see cref="tk2dCamera"/> if present /// Otherwise uses Camera.main /// </summary> public void MakePixelPerfect() { float s = 1.0f; tk2dCamera cam = tk2dCamera.CameraForLayer(gameObject.layer); if (cam != null) { if (_fontInst.version < 1) { Debug.LogError("Need to rebuild font."); } float zdist = (transform.position.z - cam.transform.position.z); float textMeshSize = (_fontInst.invOrthoSize * _fontInst.halfTargetHeight); s = cam.GetSizeAtDistance(zdist) * textMeshSize; } else if (Camera.main) { if (Camera.main.orthographic) { s = Camera.main.orthographicSize; } else { float zdist = (transform.position.z - Camera.main.transform.position.z); s = tk2dPixelPerfectHelper.CalculateScaleForPerspectiveCamera(Camera.main.fieldOfView, zdist); } s *= _fontInst.invOrthoSize; } scale = new Vector3(Mathf.Sign(scale.x) * s, Mathf.Sign(scale.y) * s, Mathf.Sign(scale.z) * s); } // tk2dRuntime.ISpriteCollectionEditor public bool UsesSpriteCollection(tk2dSpriteCollectionData spriteCollection) { if (data.font != null && data.font.spriteCollection != null) return data.font.spriteCollection == spriteCollection; // No easy way to identify this at this stage return true; } void UpdateMaterial() { if (GetComponent<Renderer>().sharedMaterial != _fontInst.materialInst) GetComponent<Renderer>().material = _fontInst.materialInst; } public void ForceBuild() { if (data.font != null) { _fontInst = data.font.inst; UpdateMaterial(); } Init(true); } #if UNITY_EDITOR void OnDrawGizmos() { if (mesh != null) { Bounds b = mesh.bounds; Gizmos.color = Color.clear; Gizmos.matrix = transform.localToWorldMatrix; Gizmos.DrawCube(b.center, b.extents * 2); Gizmos.matrix = Matrix4x4.identity; Gizmos.color = Color.white; } } #endif }
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; namespace Org.OpenAPITools.Model { /// <summary> /// GithubContent /// </summary> [DataContract(Name = "GithubContent")] public partial class GithubContent : IEquatable<GithubContent>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="GithubContent" /> class. /// </summary> /// <param name="name">name.</param> /// <param name="sha">sha.</param> /// <param name="_class">_class.</param> /// <param name="repo">repo.</param> /// <param name="size">size.</param> /// <param name="owner">owner.</param> /// <param name="path">path.</param> /// <param name="base64Data">base64Data.</param> public GithubContent(string name = default(string), string sha = default(string), string _class = default(string), string repo = default(string), int size = default(int), string owner = default(string), string path = default(string), string base64Data = default(string)) { this.Name = name; this.Sha = sha; this.Class = _class; this.Repo = repo; this.Size = size; this.Owner = owner; this.Path = path; this.Base64Data = base64Data; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name = "name", EmitDefaultValue = false)] public string Name { get; set; } /// <summary> /// Gets or Sets Sha /// </summary> [DataMember(Name = "sha", EmitDefaultValue = false)] public string Sha { get; set; } /// <summary> /// Gets or Sets Class /// </summary> [DataMember(Name = "_class", EmitDefaultValue = false)] public string Class { get; set; } /// <summary> /// Gets or Sets Repo /// </summary> [DataMember(Name = "repo", EmitDefaultValue = false)] public string Repo { get; set; } /// <summary> /// Gets or Sets Size /// </summary> [DataMember(Name = "size", EmitDefaultValue = false)] public int Size { get; set; } /// <summary> /// Gets or Sets Owner /// </summary> [DataMember(Name = "owner", EmitDefaultValue = false)] public string Owner { get; set; } /// <summary> /// Gets or Sets Path /// </summary> [DataMember(Name = "path", EmitDefaultValue = false)] public string Path { get; set; } /// <summary> /// Gets or Sets Base64Data /// </summary> [DataMember(Name = "base64Data", EmitDefaultValue = false)] public string Base64Data { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class GithubContent {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Sha: ").Append(Sha).Append("\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append(" Repo: ").Append(Repo).Append("\n"); sb.Append(" Size: ").Append(Size).Append("\n"); sb.Append(" Owner: ").Append(Owner).Append("\n"); sb.Append(" Path: ").Append(Path).Append("\n"); sb.Append(" Base64Data: ").Append(Base64Data).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 Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.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 GithubContent); } /// <summary> /// Returns true if GithubContent instances are equal /// </summary> /// <param name="input">Instance of GithubContent to be compared</param> /// <returns>Boolean</returns> public bool Equals(GithubContent input) { if (input == null) { return false; } return ( this.Name == input.Name || (this.Name != null && this.Name.Equals(input.Name)) ) && ( this.Sha == input.Sha || (this.Sha != null && this.Sha.Equals(input.Sha)) ) && ( this.Class == input.Class || (this.Class != null && this.Class.Equals(input.Class)) ) && ( this.Repo == input.Repo || (this.Repo != null && this.Repo.Equals(input.Repo)) ) && ( this.Size == input.Size || this.Size.Equals(input.Size) ) && ( this.Owner == input.Owner || (this.Owner != null && this.Owner.Equals(input.Owner)) ) && ( this.Path == input.Path || (this.Path != null && this.Path.Equals(input.Path)) ) && ( this.Base64Data == input.Base64Data || (this.Base64Data != null && this.Base64Data.Equals(input.Base64Data)) ); } /// <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.Name != null) { hashCode = (hashCode * 59) + this.Name.GetHashCode(); } if (this.Sha != null) { hashCode = (hashCode * 59) + this.Sha.GetHashCode(); } if (this.Class != null) { hashCode = (hashCode * 59) + this.Class.GetHashCode(); } if (this.Repo != null) { hashCode = (hashCode * 59) + this.Repo.GetHashCode(); } hashCode = (hashCode * 59) + this.Size.GetHashCode(); if (this.Owner != null) { hashCode = (hashCode * 59) + this.Owner.GetHashCode(); } if (this.Path != null) { hashCode = (hashCode * 59) + this.Path.GetHashCode(); } if (this.Base64Data != null) { hashCode = (hashCode * 59) + this.Base64Data.GetHashCode(); } return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
#region Header /** * JsonWriter.cs * Stream-like facility to output JSON text. * * The authors disclaim copyright to this source code. For more details, see * the COPYING file included with this distribution. **/ #endregion using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace LitJson { internal enum Condition { InArray, InObject, NotAProperty, Property, Value } internal class WriterContext { public int Count; public bool InArray; public bool InObject; public bool ExpectingValue; public int Padding; } public class JsonWriter { #region Fields private static NumberFormatInfo number_format; private WriterContext context; private Stack<WriterContext> ctx_stack; private bool has_reached_end; private char[] hex_seq; private int indentation; private int indent_value; private StringBuilder inst_string_builder; private bool pretty_print; private bool validate; private TextWriter writer; #endregion #region Properties public int IndentValue { get { return indent_value; } set { indentation = (indentation / indent_value) * value; indent_value = value; } } public bool PrettyPrint { get { return pretty_print; } set { pretty_print = value; } } public TextWriter TextWriter { get { return writer; } } public bool Validate { get { return validate; } set { validate = value; } } #endregion #region Constructors static JsonWriter () { number_format = NumberFormatInfo.InvariantInfo; } public JsonWriter () { inst_string_builder = new StringBuilder (); writer = new StringWriter (inst_string_builder); Init (); } public JsonWriter (StringBuilder sb) : this (new StringWriter (sb)) { } public JsonWriter (TextWriter writer) { if (writer == null) throw new ArgumentNullException ("writer"); this.writer = writer; Init (); } #endregion #region Private Methods private void DoValidation (Condition cond) { if (! context.ExpectingValue) context.Count++; if (! validate) return; if (has_reached_end) throw new JsonException ( "A complete JSON symbol has already been written"); switch (cond) { case Condition.InArray: if (! context.InArray) throw new JsonException ( "Can't close an array here"); break; case Condition.InObject: if (! context.InObject || context.ExpectingValue) throw new JsonException ( "Can't close an object here"); break; case Condition.NotAProperty: if (context.InObject && ! context.ExpectingValue) throw new JsonException ( "Expected a property"); break; case Condition.Property: if (! context.InObject || context.ExpectingValue) throw new JsonException ( "Can't add a property here"); break; case Condition.Value: if (! context.InArray && (! context.InObject || ! context.ExpectingValue)) throw new JsonException ( "Can't add a value here"); break; } } private void Init () { has_reached_end = false; hex_seq = new char[4]; indentation = 0; indent_value = 4; pretty_print = false; validate = true; ctx_stack = new Stack<WriterContext> (); context = new WriterContext (); ctx_stack.Push (context); } private static void IntToHex (int n, char[] hex) { int num; for (int i = 0; i < 4; i++) { num = n % 16; if (num < 10) hex[3 - i] = (char) ('0' + num); else hex[3 - i] = (char) ('A' + (num - 10)); n >>= 4; } } private void Indent () { if (pretty_print) indentation += indent_value; } private void Put (string str) { if (pretty_print && ! context.ExpectingValue) for (int i = 0; i < indentation; i++) writer.Write (' '); writer.Write (str); } private void PutNewline () { PutNewline (true); } private void PutNewline (bool add_comma) { if (add_comma && ! context.ExpectingValue && context.Count > 1) writer.Write (','); if (pretty_print && ! context.ExpectingValue) writer.Write ('\n'); } private void PutString (string str) { Put (String.Empty); writer.Write ('"'); int n = str.Length; for (int i = 0; i < n; i++) { switch (str[i]) { case '\n': writer.Write ("\\n"); continue; case '\r': writer.Write ("\\r"); continue; case '\t': writer.Write ("\\t"); continue; case '"': case '\\': writer.Write ('\\'); writer.Write (str[i]); continue; case '\f': writer.Write ("\\f"); continue; case '\b': writer.Write ("\\b"); continue; } if ((int) str[i] >= 32 && (int) str[i] <= 126) { writer.Write (str[i]); continue; } // Default, turn into a \uXXXX sequence IntToHex ((int) str[i], hex_seq); writer.Write ("\\u"); writer.Write (hex_seq); } writer.Write ('"'); } private void Unindent () { if (pretty_print) indentation -= indent_value; } #endregion public override string ToString () { if (inst_string_builder == null) return String.Empty; return inst_string_builder.ToString (); } public void Reset () { has_reached_end = false; ctx_stack.Clear (); context = new WriterContext (); ctx_stack.Push (context); if (inst_string_builder != null) inst_string_builder.Remove (0, inst_string_builder.Length); } public void Write (bool boolean) { DoValidation (Condition.Value); PutNewline (); Put (boolean ? "true" : "false"); context.ExpectingValue = false; } public void Write (decimal number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } public void Write (double number) { DoValidation (Condition.Value); PutNewline (); string str = Convert.ToString (number, number_format); Put (str); if (str.IndexOf ('.') == -1 && str.IndexOf ('E') == -1) writer.Write (".0"); context.ExpectingValue = false; } public void Write (int number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } public void Write (long number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } public void Write (string str) { DoValidation (Condition.Value); PutNewline (); if (str == null) Put ("null"); else PutString (str); context.ExpectingValue = false; } #pragma warning disable 3021 [CLSCompliant(false)] #pragma warning restore 3021 public void Write (ulong number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } public void WriteArrayEnd () { DoValidation (Condition.InArray); PutNewline (false); ctx_stack.Pop (); if (ctx_stack.Count == 1) has_reached_end = true; else { context = ctx_stack.Peek (); context.ExpectingValue = false; } Unindent (); Put ("]"); } public void WriteArrayStart () { DoValidation (Condition.NotAProperty); PutNewline (); Put ("["); context = new WriterContext (); context.InArray = true; ctx_stack.Push (context); Indent (); } public void WriteObjectEnd () { DoValidation (Condition.InObject); PutNewline (false); ctx_stack.Pop (); if (ctx_stack.Count == 1) has_reached_end = true; else { context = ctx_stack.Peek (); context.ExpectingValue = false; } Unindent (); Put ("}"); } public void WriteObjectStart () { DoValidation (Condition.NotAProperty); PutNewline (); Put ("{"); context = new WriterContext (); context.InObject = true; ctx_stack.Push (context); Indent (); } public void WritePropertyName (string property_name) { DoValidation (Condition.Property); PutNewline (); PutString (property_name); if (pretty_print) { if (property_name.Length > context.Padding) context.Padding = property_name.Length; for (int i = context.Padding - property_name.Length; i >= 0; i--) writer.Write (' '); writer.Write (": "); } else writer.Write (':'); context.ExpectingValue = true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.Runtime.Serialization; using System.Configuration.Assemblies; using Internal.Reflection.Augments; namespace System.Reflection { public sealed class AssemblyName : ICloneable, IDeserializationCallback, ISerializable { public AssemblyName() { HashAlgorithm = AssemblyHashAlgorithm.None; VersionCompatibility = AssemblyVersionCompatibility.SameMachine; _flags = AssemblyNameFlags.None; } public AssemblyName(string assemblyName) : this() { if (assemblyName == null) throw new ArgumentNullException(nameof(assemblyName)); RuntimeAssemblyName runtimeAssemblyName = AssemblyNameParser.Parse(assemblyName); runtimeAssemblyName.CopyToAssemblyName(this); } public object Clone() { AssemblyName n = new AssemblyName(); n.Name = Name; n._publicKey = (byte[])_publicKey?.Clone(); n._publicKeyToken = (byte[])_publicKeyToken?.Clone(); n.CultureInfo = CultureInfo; n.Version = (Version)Version?.Clone(); n._flags = _flags; n.CodeBase = CodeBase; n.HashAlgorithm = HashAlgorithm; n.VersionCompatibility = VersionCompatibility; return n; } public ProcessorArchitecture ProcessorArchitecture { get { int x = (((int)_flags) & 0x70) >> 4; if (x > 5) x = 0; return (ProcessorArchitecture)x; } set { int x = ((int)value) & 0x07; if (x <= 5) { _flags = (AssemblyNameFlags)((int)_flags & 0xFFFFFF0F); _flags |= (AssemblyNameFlags)(x << 4); } } } public AssemblyContentType ContentType { get { int x = (((int)_flags) & 0x00000E00) >> 9; if (x > 1) x = 0; return (AssemblyContentType)x; } set { int x = ((int)value) & 0x07; if (x <= 1) { _flags = (AssemblyNameFlags)((int)_flags & 0xFFFFF1FF); _flags |= (AssemblyNameFlags)(x << 9); } } } public string CultureName { get { return CultureInfo?.Name; } set { CultureInfo = (value == null) ? null : new CultureInfo(value); } } public CultureInfo CultureInfo { get; set; } public AssemblyNameFlags Flags { get { return (AssemblyNameFlags)((uint)_flags & 0xFFFFF10F); } set { _flags &= unchecked((AssemblyNameFlags)0x00000EF0); _flags |= (value & unchecked((AssemblyNameFlags)0xFFFFF10F)); } } public string FullName { get { if (this.Name == null) return string.Empty; // Do not call GetPublicKeyToken() here - that latches the result into AssemblyName which isn't a side effect we want. byte[] pkt = _publicKeyToken ?? AssemblyNameHelpers.ComputePublicKeyToken(_publicKey); return AssemblyNameFormatter.ComputeDisplayName(Name, Version, CultureName, pkt, Flags, ContentType); } } public string Name { get; set; } public Version Version { get; set; } public string CodeBase { get; set; } public AssemblyHashAlgorithm HashAlgorithm { get; set; } public AssemblyVersionCompatibility VersionCompatibility { get; set; } public StrongNameKeyPair KeyPair { get; set; } public string EscapedCodeBase { get { if (CodeBase == null) return null; else return EscapeCodeBase(CodeBase); } } public byte[] GetPublicKey() { return _publicKey; } public byte[] GetPublicKeyToken() { if (_publicKeyToken == null) _publicKeyToken = AssemblyNameHelpers.ComputePublicKeyToken(_publicKey); return _publicKeyToken; } public void SetPublicKey(byte[] publicKey) { _publicKey = publicKey; if (publicKey == null) _flags &= ~AssemblyNameFlags.PublicKey; else _flags |= AssemblyNameFlags.PublicKey; } public void SetPublicKeyToken(byte[] publicKeyToken) { _publicKeyToken = publicKeyToken; } public override string ToString() { string s = FullName; if (s == null) return base.ToString(); else return s; } public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } public void OnDeserialization(object sender) { throw new PlatformNotSupportedException(); } public static AssemblyName GetAssemblyName(string assemblyFile) { throw new NotImplementedException(); } // TODO: https://github.com/dotnet/corert/issues/3253 /// <summary> /// Compares the simple names disregarding Version, Culture and PKT. While this clearly does not /// match the intent of this api, this api has been broken this way since its debut and we cannot /// change its behavior now. /// </summary> public static bool ReferenceMatchesDefinition(AssemblyName reference, AssemblyName definition) { if (object.ReferenceEquals(reference, definition)) return true; if (reference == null) throw new ArgumentNullException(nameof(reference)); if (definition == null) throw new ArgumentNullException(nameof(definition)); string refName = reference.Name ?? string.Empty; string defName = definition.Name ?? string.Empty; return refName.Equals(defName, StringComparison.OrdinalIgnoreCase); } internal static string EscapeCodeBase(string codebase) { throw new PlatformNotSupportedException(); } private AssemblyNameFlags _flags; private byte[] _publicKey; private byte[] _publicKeyToken; } }
//------------------------------------------------------------------------------ // <copyright company="Microsoft Corporation"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using System.Diagnostics; using System.Data; using System.Data.Common; using System.Collections; using System.ComponentModel; using System.Collections.Generic; using EMDRGatherer.Microsoft.Data.ConnectionUI.Dialog; namespace Microsoft.Data.ConnectionUI { public class AdoDotNetConnectionProperties : IDataConnectionProperties, ICustomTypeDescriptor { public AdoDotNetConnectionProperties(string providerName) { Debug.Assert(providerName != null); _providerName = providerName; // Create an underlying connection string builder object DbProviderFactory factory = DbProviderFactories.GetFactory(providerName); Debug.Assert(factory != null); _connectionStringBuilder = factory.CreateConnectionStringBuilder(); Debug.Assert(_connectionStringBuilder != null); _connectionStringBuilder.BrowsableConnectionString = false; } public virtual void Reset() { _connectionStringBuilder.Clear(); OnPropertyChanged(EventArgs.Empty); } public virtual void Parse(string s) { _connectionStringBuilder.ConnectionString = s; OnPropertyChanged(EventArgs.Empty); } public virtual bool IsExtensible { get { return !_connectionStringBuilder.IsFixedSize; } } public virtual void Add(string propertyName) { if (!_connectionStringBuilder.ContainsKey(propertyName)) { _connectionStringBuilder.Add(propertyName, String.Empty); OnPropertyChanged(EventArgs.Empty); } } public virtual bool Contains(string propertyName) { return _connectionStringBuilder.ContainsKey(propertyName); } public virtual object this[string propertyName] { get { // Property name must not be null if (propertyName == null) { throw new ArgumentNullException("propertyName"); } // If property doesn't exist, just return null object testValue = null; if (!_connectionStringBuilder.TryGetValue(propertyName, out testValue)) { return null; } // If property value has been set, return this value if (_connectionStringBuilder.ShouldSerialize(propertyName)) { return _connectionStringBuilder[propertyName]; } // Get the property's default value (if any) object val = _connectionStringBuilder[propertyName]; // If a default value exists, return it if (val != null) { return val; } // No value has been set and no default value exists, so return DBNull.Value return DBNull.Value; } set { // Property name must not be null if (propertyName == null) { throw new ArgumentNullException("propertyName"); } // Remove the value _connectionStringBuilder.Remove(propertyName); // Handle cases where value is DBNull.Value if (value == DBNull.Value) { // Leave the property in the reset state OnPropertyChanged(EventArgs.Empty); return; } // Get the property's default value (if any) object val = null; _connectionStringBuilder.TryGetValue(propertyName, out val); // Set the value _connectionStringBuilder[propertyName] = value; // If the value is equal to the default, remove it again if (Object.Equals(val, value)) { _connectionStringBuilder.Remove(propertyName); } OnPropertyChanged(EventArgs.Empty); } } public virtual void Remove(string propertyName) { if (_connectionStringBuilder.ContainsKey(propertyName)) { _connectionStringBuilder.Remove(propertyName); OnPropertyChanged(EventArgs.Empty); } } public event EventHandler PropertyChanged; public virtual void Reset(string propertyName) { if (_connectionStringBuilder.ContainsKey(propertyName)) { _connectionStringBuilder.Remove(propertyName); OnPropertyChanged(EventArgs.Empty); } } public virtual bool IsComplete { get { return true; } } public virtual void Test() { string testString = ToTestString(); // If the connection string is empty, don't even bother testing if (testString == null || testString.Length == 0) { throw new InvalidOperationException(Strings.AdoDotNetConnectionProperties_NoProperties); } // Create a connection object DbConnection connection = null; DbProviderFactory factory = DbProviderFactories.GetFactory(_providerName); Debug.Assert(factory != null); connection = factory.CreateConnection(); Debug.Assert(connection != null); // Try to open it try { connection.ConnectionString = testString; connection.Open(); Inspect(connection); } finally { connection.Dispose(); } } public override string ToString() { return ToFullString(); } public virtual string ToFullString() { return _connectionStringBuilder.ConnectionString; } public virtual string ToDisplayString() { PropertyDescriptorCollection sensitiveProperties = GetProperties(new Attribute[] { PasswordPropertyTextAttribute.Yes }); List<KeyValuePair<string, object>> savedValues = new List<KeyValuePair<string, object>>(); foreach (PropertyDescriptor sensitiveProperty in sensitiveProperties) { string propertyName = sensitiveProperty.DisplayName; if (ConnectionStringBuilder.ShouldSerialize(propertyName)) { savedValues.Add(new KeyValuePair<string, object>(propertyName, ConnectionStringBuilder[propertyName])); ConnectionStringBuilder.Remove(propertyName); } } try { return ConnectionStringBuilder.ConnectionString; } finally { foreach (KeyValuePair<string, object> savedValue in savedValues) { if (savedValue.Value != null) { ConnectionStringBuilder[savedValue.Key] = savedValue.Value; } } } } public DbConnectionStringBuilder ConnectionStringBuilder { get { return _connectionStringBuilder; } } protected virtual PropertyDescriptor DefaultProperty { get { return TypeDescriptor.GetDefaultProperty(_connectionStringBuilder, true); } } protected virtual PropertyDescriptorCollection GetProperties(Attribute[] attributes) { return TypeDescriptor.GetProperties(_connectionStringBuilder, attributes); } protected virtual void OnPropertyChanged(EventArgs e) { if (PropertyChanged != null) { PropertyChanged(this, e); } } protected virtual string ToTestString() { return _connectionStringBuilder.ConnectionString; } protected virtual void Inspect(DbConnection connection) { } #region ICustomTypeDescriptor implementation string ICustomTypeDescriptor.GetClassName() { return TypeDescriptor.GetClassName(_connectionStringBuilder, true); } string ICustomTypeDescriptor.GetComponentName() { return TypeDescriptor.GetComponentName(_connectionStringBuilder, true); } AttributeCollection ICustomTypeDescriptor.GetAttributes() { return TypeDescriptor.GetAttributes(_connectionStringBuilder, true); } object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(_connectionStringBuilder, editorBaseType, true); } TypeConverter ICustomTypeDescriptor.GetConverter() { return TypeDescriptor.GetConverter(_connectionStringBuilder, true); } PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { return DefaultProperty; } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { return GetProperties(new Attribute[0]); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { return GetProperties(attributes); } EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(_connectionStringBuilder, true); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { return TypeDescriptor.GetEvents(_connectionStringBuilder, true); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(_connectionStringBuilder, attributes, true); } object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { return _connectionStringBuilder; } #endregion private string _providerName; private DbConnectionStringBuilder _connectionStringBuilder; } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="RebufferableBinaryReader.cs" company="Jake Woods"> // Copyright (c) 2013 Jake Woods // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies // or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR // ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // </copyright> // <author>Jake Woods</author> // <summary> // Provides methods to interpret and read a stream as either character or binary // data similar to a and provides the ability to push // data onto the front of the stream. // </summary> // -------------------------------------------------------------------------------------------------------------------- using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; namespace HttpMultipartParser { /// <summary> /// Provides methods to interpret and read a stream as either character or binary /// data similar to a <see cref="BinaryReader" /> and provides the ability to push /// data onto the front of the stream. /// </summary> public class RebufferableBinaryReader { #region Fields /// <summary> /// The size of the buffer to use when reading new data. /// </summary> private readonly int bufferSize; /// <summary> /// The encoding to use for character based operations. /// </summary> private readonly Encoding encoding; /// <summary> /// The stream to read raw data from. /// </summary> private readonly Stream stream; /// <summary> /// The stream stack to store buffered data. /// </summary> private readonly BinaryStreamStack streamStack; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="RebufferableBinaryReader" /> class. /// Default encoding of UTF8 will be used. /// </summary> /// <param name="input"> /// The input stream to read from. /// </param> public RebufferableBinaryReader(Stream input) : this(input, new UTF8Encoding(false)) { } /// <summary> /// Initializes a new instance of the <see cref="RebufferableBinaryReader" /> class. /// </summary> /// <param name="input"> /// The input stream to read from. /// </param> /// <param name="encoding"> /// The encoding to use for character based operations. /// </param> /// <param name="bufferSize"> /// The buffer size to use for new buffers. /// </param> public RebufferableBinaryReader(Stream input, Encoding encoding, int bufferSize = 4096) { stream = input; streamStack = new BinaryStreamStack(encoding); this.encoding = encoding; this.bufferSize = bufferSize; } #endregion #region Public Methods and Operators /// <summary> /// Adds data to the front of the stream. The most recently buffered data will /// be read first. /// </summary> /// <param name="data"> /// The data to buffer. /// </param> public void Buffer(byte[] data) { streamStack.Push(data); } /// <summary> /// Adds data to the front of the stream. The most recently buffered data will /// be read first. /// </summary> /// <param name="data"> /// The data to buffer. /// </param> /// <param name="offset"> /// The zero-based byte offset in buffer at which to begin copying bytes to the current stream. /// </param> /// <param name="count"> /// The maximum number of bytes to write. /// </param> public void Buffer(byte[] data, int offset, int count) { streamStack.Push(data, offset, count); } /// <summary> /// Adds the string to the front of the stream. The most recently buffered data will /// be read first. /// </summary> /// <param name="data"> /// The data. /// </param> public void Buffer(string data) { streamStack.Push(encoding.GetBytes(data)); } /// <summary> /// Reads a single byte as an integer from the stream. Returns -1 if no /// data is left to read. /// </summary> /// <returns> /// The <see cref="byte" /> that was read. /// </returns> public int Read() { int value = -1; while (value == -1) { if (!streamStack.HasData()) { if (StreamData() == 0) { return -1; } } value = streamStack.Read(); } return value; } /// <summary> /// Reads the specified number of bytes from the stream, starting from a /// specified point in the byte array. /// </summary> /// <param name="buffer"> /// The buffer to read data into. /// </param> /// <param name="index"> /// The index of buffer to start reading into. /// </param> /// <param name="count"> /// The number of bytes to read into the buffer. /// </param> /// <returns> /// The number of bytes read into buffer. This might be less than the number of bytes requested if that many bytes are not available, /// or it might be zero if the end of the stream is reached. /// </returns> public int Read(byte[] buffer, int index, int count) { int amountRead = 0; while (amountRead < count) { if (!streamStack.HasData()) { if (StreamData() == 0) { return amountRead; } } amountRead += streamStack.Read(buffer, index + amountRead, count - amountRead); } return amountRead; } /// <summary> /// Reads the specified number of characters from the stream, starting from a /// specified point in the byte array. /// </summary> /// <param name="buffer"> /// The buffer to read data into. /// </param> /// <param name="index"> /// The index of buffer to start reading into. /// </param> /// <param name="count"> /// The number of characters to read into the buffer. /// </param> /// <returns> /// The number of characters read into buffer. This might be less than the number of /// characters requested if that many characters are not available, /// or it might be zero if the end of the stream is reached. /// </returns> public int Read(char[] buffer, int index, int count) { int amountRead = 0; while (amountRead < count) { if (!streamStack.HasData()) { if (StreamData() == 0) { return amountRead; } } amountRead += streamStack.Read(buffer, index + amountRead, count - amountRead); } return amountRead; } /// <summary> /// Reads a series of bytes delimited by the byte encoding of newline for this platform. /// The newline bytes will not be included in the return data. /// </summary> /// <returns> /// A byte array containing all the data up to but not including the next newline in the stack. /// </returns> public byte[] ReadByteLine() { using (var builder = Utilities.MemoryStreamManager.GetStream($"{typeof(RebufferableBinaryReader).FullName}.{nameof(ReadByteLine)}")) { while (true) { if (!streamStack.HasData()) { if (StreamData() == 0) { return builder.Length > 0 ? builder.ToArray() : null; } } byte[] line = streamStack.ReadByteLine(out bool hitStreamEnd); builder.Write(line, 0, line.Length); if (!hitStreamEnd) { return builder.ToArray(); } } } } /// <summary> /// Reads a line from the stack delimited by the newline for this platform. The newline /// characters will not be included in the stream. /// </summary> /// <returns> /// The <see cref="string" /> containing the line or null if end of stream. /// </returns> public string ReadLine() { byte[] data = ReadByteLine(); return data == null ? null : encoding.GetString(data); } /// <summary> /// Asynchronously reads a single byte as an integer from the stream. /// Returns -1 if no data is left to read. /// </summary> /// <param name="cancellationToken"> /// The cancellation token. /// </param> /// <returns> /// The <see cref="byte" /> that was read. /// </returns> public async Task<int> ReadAsync(CancellationToken cancellationToken = default) { int value = -1; while (value == -1) { if (!streamStack.HasData()) { var bytesRead = await StreamDataAsync(cancellationToken).ConfigureAwait(false); if (bytesRead == 0) { return -1; } } value = streamStack.Read(); } return value; } /// <summary> /// Asynchronously reads the specified number of bytes from the stream, starting from a /// specified point in the byte array. /// </summary> /// <param name="buffer"> /// The buffer to read data into. /// </param> /// <param name="index"> /// The index of buffer to start reading into. /// </param> /// <param name="count"> /// The number of bytes to read into the buffer. /// </param> /// <param name="cancellationToken"> /// The cancellation token. /// </param> /// <returns> /// The number of bytes read into buffer. This might be less than the number of bytes requested if that many bytes are not available, /// or it might be zero if the end of the stream is reached. /// </returns> public async Task<int> ReadAsync(byte[] buffer, int index, int count, CancellationToken cancellationToken = default) { int amountRead = 0; while (amountRead < count) { if (!streamStack.HasData()) { var bytesRead = await StreamDataAsync(cancellationToken).ConfigureAwait(false); if (bytesRead == 0) { return amountRead; } } amountRead += streamStack.Read(buffer, index + amountRead, count - amountRead); } return amountRead; } /// <summary> /// Asynchronously reads the specified number of characters from the stream, starting from a /// specified point in the byte array. /// </summary> /// <param name="buffer"> /// The buffer to read data into. /// </param> /// <param name="index"> /// The index of buffer to start reading into. /// </param> /// <param name="count"> /// The number of characters to read into the buffer. /// </param> /// <param name="cancellationToken"> /// The cancellation token. /// </param> /// <returns> /// The number of characters read into buffer. This might be less than the number of /// characters requested if that many characters are not available, /// or it might be zero if the end of the stream is reached. /// </returns> public async Task<int> ReadAsync(char[] buffer, int index, int count, CancellationToken cancellationToken = default) { int amountRead = 0; while (amountRead < count) { if (!streamStack.HasData()) { var bytesRead = await StreamDataAsync(cancellationToken).ConfigureAwait(false); if (bytesRead == 0) { return amountRead; } } amountRead += streamStack.Read(buffer, index + amountRead, count - amountRead); } return amountRead; } /// <summary> /// Asynchronously reads a series of bytes delimited by the byte encoding of newline for this platform. /// The newline bytes will not be included in the return data. /// </summary> /// <param name="cancellationToken"> /// The cancellation token. /// </param> /// <returns> /// A byte array containing all the data up to but not including the next newline in the stack. /// </returns> public async Task<byte[]> ReadByteLineAsync(CancellationToken cancellationToken = default) { using (var builder = Utilities.MemoryStreamManager.GetStream($"{typeof(RebufferableBinaryReader).FullName}.{nameof(ReadByteLineAsync)}")) { while (true) { if (!streamStack.HasData()) { var bytesRead = await StreamDataAsync(cancellationToken).ConfigureAwait(false); if (bytesRead == 0) { return builder.Length > 0 ? builder.ToArray() : null; } } byte[] line = streamStack.ReadByteLine(out bool hitStreamEnd); await builder.WriteAsync(line, 0, line.Length, cancellationToken).ConfigureAwait(false); if (!hitStreamEnd) { return builder.ToArray(); } } } } /// <summary> /// Asynchronously reads a line from the stack delimited by the newline for this platform. The newline /// characters will not be included in the stream. /// </summary> /// <param name="cancellationToken"> /// The cancellation token. /// </param> /// <returns> /// The <see cref="string" /> containing the line or null if end of stream. /// </returns> public async Task<string> ReadLineAsync(CancellationToken cancellationToken = default) { byte[] data = await ReadByteLineAsync(cancellationToken).ConfigureAwait(false); return data == null ? null : encoding.GetString(data); } #endregion #region Methods /// <summary> /// Determines the byte order marking offset (if any) from the /// given buffer. /// </summary> /// <param name="buffer"> /// The buffer to examine. /// </param> /// <returns> /// The <see cref="int" /> representing the length of the byte order marking. /// </returns> private int GetBomOffset(byte[] buffer) { byte[] bom = encoding.GetPreamble(); bool usesBom = true; for (int i = 0; i < bom.Length; ++i) { if (bom[i] != buffer[i]) { usesBom = false; } } return usesBom ? bom.Length : 0; } /// <summary> /// Reads more data from the stream into the stream stack. /// </summary> /// <returns> /// The number of bytes read into the stream stack as an <see cref="int" />. /// </returns> private int StreamData() { var buffer = Utilities.ArrayPool.Rent(bufferSize); int amountRead = stream.Read(buffer, 0, bufferSize); PushToStack(buffer, amountRead); Utilities.ArrayPool.Return(buffer); return amountRead; } /// <summary> /// Asynchronously reads more data from the stream into the stream stack. /// </summary> /// <param name="cancellationToken"> /// The cancellation token. /// </param> /// <returns> /// The number of bytes read into the stream stack as an <see cref="int" />. /// </returns> private async Task<int> StreamDataAsync(CancellationToken cancellationToken = default) { var buffer = Utilities.ArrayPool.Rent(bufferSize); int amountRead = await stream.ReadAsync(buffer, 0, bufferSize, cancellationToken).ConfigureAwait(false); PushToStack(buffer, amountRead); Utilities.ArrayPool.Return(buffer); return amountRead; } /// <summary> /// Push the data read from the stram into the stream stack. /// </summary> /// <param name="buffer"> /// The data that was read from the stream. /// </param> /// <param name="amountRead"> /// The number of bytes read from the stream. /// </param> private void PushToStack(byte[] buffer, int amountRead) { // We need to check if our stream is using our encodings // BOM, if it is we need to jump it. int bomOffset = GetBomOffset(buffer); // Sometimes we'll get a buffer that's smaller then we expect, chop it down // for the reader: if (amountRead - bomOffset > 0) { streamStack.Push(buffer, bomOffset, amountRead - bomOffset); } } #endregion } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: PipeSecurity ** ** ** Purpose: Managed ACL wrapper for Pipes. ** ** ===========================================================*/ using System; using System.Collections; using System.Security.AccessControl; using System.Security.Permissions; using System.Security.Principal; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; using System.IO; using System.Runtime.Versioning; namespace System.IO.Pipes { [Flags] public enum PipeAccessRights { // No None field - An ACE with the value 0 cannot grant nor deny. ReadData = 0x000001, WriteData = 0x000002, // Not that all client named pipes require ReadAttributes access even if the user does not specify it. // (This is because CreateFile slaps on the requirement before calling NTCreateFile (at least in WinXP SP2)). ReadAttributes = 0x000080, WriteAttributes = 0x000100, // These aren't really needed since there is no operation that requires this access, but they are left here // so that people can specify ACLs that others can open by specifying a PipeDirection rather than a // PipeAccessRights (PipeDirection.In/Out maps to GENERIC_READ/WRITE access). ReadExtendedAttributes = 0x000008, WriteExtendedAttributes = 0x000010, CreateNewInstance = 0x000004, // AppendData // Again, this is not needed but it should be here so that our FullControl matches windows. Delete = 0x010000, ReadPermissions = 0x020000, ChangePermissions = 0x040000, TakeOwnership = 0x080000, Synchronize = 0x100000, FullControl = ReadData | WriteData | ReadAttributes | ReadExtendedAttributes | WriteAttributes | WriteExtendedAttributes | CreateNewInstance | Delete | ReadPermissions | ChangePermissions | TakeOwnership | Synchronize, Read = ReadData | ReadAttributes | ReadExtendedAttributes | ReadPermissions, Write = WriteData | WriteAttributes | WriteExtendedAttributes, // | CreateNewInstance, For security, I really don't this CreateNewInstance belongs here. ReadWrite = Read | Write, // These are somewhat similar to what you get if you use PipeDirection: //In = ReadData | ReadAttributes | ReadExtendedAttributes | ReadPermissions, //Out = WriteData | WriteAttributes | WriteExtendedAttributes | ChangePermissions | CreateNewInstance | ReadAttributes, // NOTE: Not sure if ReadAttributes should really be here //InOut = In | Out, AccessSystemSecurity = 0x01000000, // Allow changes to SACL. } [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] public sealed class PipeAccessRule : AccessRule { #region Constructors // // Constructor for creating access rules for pipe objects // public PipeAccessRule( String identity, PipeAccessRights rights, AccessControlType type) : this( new NTAccount(identity), AccessMaskFromRights(rights, type), false, type) { } public PipeAccessRule( IdentityReference identity, PipeAccessRights rights, AccessControlType type) : this( identity, AccessMaskFromRights(rights, type), false, type) { } // // Internal constructor to be called by public constructors // and the access rights factory methods // internal PipeAccessRule( IdentityReference identity, int accessMask, bool isInherited, AccessControlType type) : base( identity, accessMask, isInherited, InheritanceFlags.None, // these do not apply to pipes PropagationFlags.None, // these do not apply to pipes type) { } #endregion #region Public properties public PipeAccessRights PipeAccessRights { get { return RightsFromAccessMask(base.AccessMask); } } #endregion #region Access mask to rights translation // ACL's on pipes have a SYNCHRONIZE bit, and CreateFile ALWAYS asks for it. // So for allows, let's always include this bit, and for denies, let's never // include this bit unless we're denying full control. This is the right // thing for users, even if it does make the model look asymmetrical from a // purist point of view. internal static int AccessMaskFromRights(PipeAccessRights rights, AccessControlType controlType) { if (rights < (PipeAccessRights)0 || rights > (PipeAccessRights.FullControl | PipeAccessRights.AccessSystemSecurity)) throw new ArgumentOutOfRangeException("rights", SR.GetString(SR.ArgumentOutOfRange_NeedValidPipeAccessRights)); if (controlType == AccessControlType.Allow) { rights |= PipeAccessRights.Synchronize; } else if (controlType == AccessControlType.Deny) { if (rights != PipeAccessRights.FullControl) { rights &= ~PipeAccessRights.Synchronize; } } return (int)rights; } internal static PipeAccessRights RightsFromAccessMask(int accessMask) { return (PipeAccessRights)accessMask; } #endregion } [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] public sealed class PipeAuditRule : AuditRule { #region Constructors public PipeAuditRule( IdentityReference identity, PipeAccessRights rights, AuditFlags flags) : this( identity, AccessMaskFromRights(rights), false, flags) { } public PipeAuditRule( String identity, PipeAccessRights rights, AuditFlags flags) : this( new NTAccount(identity), AccessMaskFromRights(rights), false, flags) { } internal PipeAuditRule( IdentityReference identity, int accessMask, bool isInherited, AuditFlags flags) : base( identity, accessMask, isInherited, InheritanceFlags.None, PropagationFlags.None, flags) { } #endregion #region Private methods private static int AccessMaskFromRights(PipeAccessRights rights) { if (rights < (PipeAccessRights)0 || rights > (PipeAccessRights.FullControl | PipeAccessRights.AccessSystemSecurity)) { throw new ArgumentOutOfRangeException("rights", SR.GetString(SR.ArgumentOutOfRange_NeedValidPipeAccessRights)); } return (int)rights; } #endregion #region Public properties public PipeAccessRights PipeAccessRights { get { return PipeAccessRule.RightsFromAccessMask(base.AccessMask); } } #endregion } [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] public class PipeSecurity : NativeObjectSecurity { public PipeSecurity() : base(false, ResourceType.KernelObject) { } // Used by PipeStream.GetAccessControl [System.Security.SecuritySafeCritical] internal PipeSecurity(SafePipeHandle safeHandle, AccessControlSections includeSections) : base(false, ResourceType.KernelObject, safeHandle, includeSections) { } public void AddAccessRule(PipeAccessRule rule) { if (rule == null) throw new ArgumentNullException("rule"); base.AddAccessRule(rule); } public void SetAccessRule(PipeAccessRule rule) { if (rule == null) throw new ArgumentNullException("rule"); base.SetAccessRule(rule); } public void ResetAccessRule(PipeAccessRule rule) { if (rule == null) throw new ArgumentNullException("rule"); base.ResetAccessRule(rule); } public bool RemoveAccessRule(PipeAccessRule rule) { if (rule == null) { throw new ArgumentNullException("rule"); } // If the rule to be removed matches what is there currently then // remove it unaltered. That is, don't mask off the Synchronize bit. AuthorizationRuleCollection rules = GetAccessRules(true, true, rule.IdentityReference.GetType()); for (int i = 0; i < rules.Count; i++) { PipeAccessRule fsrule = rules[i] as PipeAccessRule; if ((fsrule != null) && (fsrule.PipeAccessRights == rule.PipeAccessRights) && (fsrule.IdentityReference == rule.IdentityReference) && (fsrule.AccessControlType == rule.AccessControlType)) { return base.RemoveAccessRule(rule); } } // It didn't exactly match any of the current rules so remove this way: // mask off the synchronize bit (that is automatically added for Allow) // before removing the ACL. The logic here should be same as Deny and hence // fake a call to AccessMaskFromRights as though the ACL is for Deny if (rule.PipeAccessRights != PipeAccessRights.FullControl) { return base.RemoveAccessRule(new PipeAccessRule( rule.IdentityReference, PipeAccessRule.AccessMaskFromRights(rule.PipeAccessRights, AccessControlType.Deny), false, rule.AccessControlType)); } else { return base.RemoveAccessRule(rule); } } public void RemoveAccessRuleSpecific(PipeAccessRule rule) { if (rule == null) { throw new ArgumentNullException("rule"); } // If the rule to be removed matches what is there currently then // remove it unaltered. That is, don't mask off the Synchronize bit AuthorizationRuleCollection rules = GetAccessRules(true, true, rule.IdentityReference.GetType()); for (int i = 0; i < rules.Count; i++) { PipeAccessRule fsrule = rules[i] as PipeAccessRule; if ((fsrule != null) && (fsrule.PipeAccessRights == rule.PipeAccessRights) && (fsrule.IdentityReference == rule.IdentityReference) && (fsrule.AccessControlType == rule.AccessControlType)) { base.RemoveAccessRuleSpecific(rule); return; } } // It wasn't an exact match so try masking the sychronize bit (that is // automatically added for Allow) before removing the ACL. The logic // here should be same as Deny and hence fake a call to // AccessMaskFromRights as though the ACL is for Deny if (rule.PipeAccessRights != PipeAccessRights.FullControl) { base.RemoveAccessRuleSpecific(new PipeAccessRule(rule.IdentityReference, PipeAccessRule.AccessMaskFromRights(rule.PipeAccessRights, AccessControlType.Deny), false, rule.AccessControlType)); } else { base.RemoveAccessRuleSpecific(rule); } } public void AddAuditRule(PipeAuditRule rule) { base.AddAuditRule(rule); } public void SetAuditRule(PipeAuditRule rule) { base.SetAuditRule(rule); } public bool RemoveAuditRule(PipeAuditRule rule) { return base.RemoveAuditRule(rule); } public void RemoveAuditRuleAll(PipeAuditRule rule) { base.RemoveAuditRuleAll(rule); } public void RemoveAuditRuleSpecific(PipeAuditRule rule) { base.RemoveAuditRuleSpecific(rule); } public override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) { // Throw if inheritance flags or propagation flags set. Have to include in signature // since this is an override if (inheritanceFlags != InheritanceFlags.None) { throw new ArgumentException(SR.GetString(SR.Argument_NonContainerInvalidAnyFlag), "inheritanceFlags"); } if (propagationFlags != PropagationFlags.None) { throw new ArgumentException(SR.GetString(SR.Argument_NonContainerInvalidAnyFlag), "propagationFlags"); } return new PipeAccessRule( identityReference, accessMask, isInherited, type); } public sealed override AuditRule AuditRuleFactory( IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) { // Throw if inheritance flags or propagation flags set. Have to include in signature // since this is an override if (inheritanceFlags != InheritanceFlags.None) { throw new ArgumentException(SR.GetString(SR.Argument_NonContainerInvalidAnyFlag), "inheritanceFlags"); } if (propagationFlags != PropagationFlags.None) { throw new ArgumentException(SR.GetString(SR.Argument_NonContainerInvalidAnyFlag), "propagationFlags"); } return new PipeAuditRule( identityReference, accessMask, isInherited, flags); } #region Private Methods private AccessControlSections GetAccessControlSectionsFromChanges() { AccessControlSections persistRules = AccessControlSections.None; if (AccessRulesModified) persistRules = AccessControlSections.Access; if (AuditRulesModified) persistRules |= AccessControlSections.Audit; if (OwnerModified) persistRules |= AccessControlSections.Owner; if (GroupModified) persistRules |= AccessControlSections.Group; return persistRules; } #endregion #region Protected Methods // Use this in your own Persist after you have demanded any appropriate CAS permissions. // Note that you will want your version to be internal and use a specialized Safe Handle. [System.Security.SecurityCritical] [SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)] protected internal void Persist(SafeHandle handle) { WriteLock(); try { AccessControlSections persistRules = GetAccessControlSectionsFromChanges(); base.Persist(handle, persistRules); OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false; } finally { WriteUnlock(); } } // Use this in your own Persist after you have demanded any appropriate CAS permissions. // Note that you will want your version to be internal. [System.Security.SecurityCritical] [SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)] protected internal void Persist(String name) { WriteLock(); try { AccessControlSections persistRules = GetAccessControlSectionsFromChanges(); base.Persist(name, persistRules); OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false; } finally { WriteUnlock(); } } #endregion #region some overrides public override Type AccessRightType { get { return typeof(PipeAccessRights); } } public override Type AccessRuleType { get { return typeof(PipeAccessRule); } } public override Type AuditRuleType { get { return typeof(PipeAuditRule); } } #endregion } }
// // Copyright (c) 2008-2011, Kenneth Bell // // 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 DiscUtils.Ntfs { using System; using System.Collections.Generic; using System.Globalization; using System.IO; /// <summary> /// Class representing the $MFT file on disk, including mirror. /// </summary> /// <remarks>This class only understands basic record structure, and is /// ignorant of files that span multiple records. This class should only /// be used by the NtfsFileSystem and File classes.</remarks> internal class MasterFileTable : IDiagnosticTraceable, IDisposable { /// <summary> /// MFT index of the MFT file itself. /// </summary> public const long MftIndex = 0; /// <summary> /// MFT index of the MFT Mirror file. /// </summary> public const long MftMirrorIndex = 1; /// <summary> /// MFT Index of the Log file. /// </summary> public const long LogFileIndex = 2; /// <summary> /// MFT Index of the Volume file. /// </summary> public const long VolumeIndex = 3; /// <summary> /// MFT Index of the Attribute Definition file. /// </summary> public const long AttrDefIndex = 4; /// <summary> /// MFT Index of the Root Directory. /// </summary> public const long RootDirIndex = 5; /// <summary> /// MFT Index of the Bitmap file. /// </summary> public const long BitmapIndex = 6; /// <summary> /// MFT Index of the Boot sector(s). /// </summary> public const long BootIndex = 7; /// <summary> /// MFT Index of the Bad Bluster file. /// </summary> public const long BadClusIndex = 8; /// <summary> /// MFT Index of the Security Descriptor file. /// </summary> public const long SecureIndex = 9; /// <summary> /// MFT Index of the Uppercase mapping file. /// </summary> public const long UpCaseIndex = 10; /// <summary> /// MFT Index of the Optional Extensions directory. /// </summary> public const long ExtendIndex = 11; /// <summary> /// First MFT Index available for 'normal' files. /// </summary> private const uint FirstAvailableMftIndex = 24; private File _self; private Bitmap _bitmap; private Stream _recordStream; private ObjectCache<long, FileRecord> _recordCache; private int _recordLength; private int _bytesPerSector; public MasterFileTable(INtfsContext context) { BiosParameterBlock bpb = context.BiosParameterBlock; _recordCache = new ObjectCache<long, FileRecord>(); _recordLength = bpb.MftRecordSize; _bytesPerSector = bpb.BytesPerSector; // Temporary record stream - until we've bootstrapped the MFT properly _recordStream = new SubStream(context.RawStream, bpb.MftCluster * bpb.SectorsPerCluster * bpb.BytesPerSector, 24 * _recordLength); } public int RecordSize { get { return _recordLength; } } /// <summary> /// Gets the MFT records directly from the MFT stream - bypassing the record cache. /// </summary> public IEnumerable<FileRecord> Records { get { using (Stream mftStream = _self.OpenStream(AttributeType.Data, null, FileAccess.Read)) { uint index = 0; while (mftStream.Position < mftStream.Length) { byte[] recordData = Utilities.ReadFully(mftStream, _recordLength); if (Utilities.BytesToString(recordData, 0, 4) != "FILE") { continue; } FileRecord record = new FileRecord(_bytesPerSector); record.FromBytes(recordData, 0); record.LoadedIndex = index; yield return record; index++; } } } } public void Dispose() { if (_recordStream != null) { _recordStream.Dispose(); _recordStream = null; } if (_bitmap != null) { _bitmap.Dispose(); _bitmap = null; } GC.SuppressFinalize(this); } public FileRecord GetBootstrapRecord() { _recordStream.Position = 0; byte[] mftSelfRecordData = Utilities.ReadFully(_recordStream, _recordLength); FileRecord mftSelfRecord = new FileRecord(_bytesPerSector); mftSelfRecord.FromBytes(mftSelfRecordData, 0); _recordCache[MftIndex] = mftSelfRecord; return mftSelfRecord; } public void Initialize(File file) { _self = file; if (_recordStream != null) { _recordStream.Dispose(); } NtfsStream bitmapStream = _self.GetStream(AttributeType.Bitmap, null); _bitmap = new Bitmap(bitmapStream.Open(FileAccess.ReadWrite), long.MaxValue); NtfsStream recordsStream = _self.GetStream(AttributeType.Data, null); _recordStream = recordsStream.Open(FileAccess.ReadWrite); } public File InitializeNew(INtfsContext context, long firstBitmapCluster, ulong numBitmapClusters, long firstRecordsCluster, ulong numRecordsClusters) { BiosParameterBlock bpb = context.BiosParameterBlock; FileRecord fileRec = new FileRecord(bpb.BytesPerSector, bpb.MftRecordSize, (uint)MftIndex); fileRec.Flags = FileRecordFlags.InUse; fileRec.SequenceNumber = 1; _recordCache[MftIndex] = fileRec; _self = new File(context, fileRec); StandardInformation.InitializeNewFile(_self, FileAttributeFlags.Hidden | FileAttributeFlags.System); NtfsStream recordsStream = _self.CreateStream(AttributeType.Data, null, firstRecordsCluster, numRecordsClusters, (uint)bpb.BytesPerCluster); _recordStream = recordsStream.Open(FileAccess.ReadWrite); Wipe(_recordStream); NtfsStream bitmapStream = _self.CreateStream(AttributeType.Bitmap, null, firstBitmapCluster, numBitmapClusters, (uint)bpb.BytesPerCluster); using (Stream s = bitmapStream.Open(FileAccess.ReadWrite)) { Wipe(s); s.SetLength(8); _bitmap = new Bitmap(s, long.MaxValue); } _recordLength = context.BiosParameterBlock.MftRecordSize; _bytesPerSector = context.BiosParameterBlock.BytesPerSector; _bitmap.MarkPresentRange(0, 1); // Write the MFT's own record to itself byte[] buffer = new byte[_recordLength]; fileRec.ToBytes(buffer, 0); _recordStream.Position = 0; _recordStream.Write(buffer, 0, _recordLength); _recordStream.Flush(); return _self; } public FileRecord AllocateRecord(FileRecordFlags flags, bool isMft) { long index; if (isMft) { // Have to take a lot of care extending the MFT itself, to ensure we never end up unable to // bootstrap the file system via the MFT itself - hence why special records are reserved // for MFT's own MFT record overflow. for (int i = 15; i > 11; --i) { FileRecord r = GetRecord(i, false); if (r.BaseFile.SequenceNumber == 0) { r.Reset(); r.Flags |= FileRecordFlags.InUse; WriteRecord(r); return r; } } throw new IOException("MFT too fragmented - unable to allocate MFT overflow record"); } else { index = _bitmap.AllocateFirstAvailable(FirstAvailableMftIndex); } if (index * _recordLength >= _recordStream.Length) { // Note: 64 is significant, since bitmap extends by 8 bytes (=64 bits) at a time. long newEndIndex = Utilities.RoundUp(index + 1, 64); _recordStream.SetLength(newEndIndex * _recordLength); for (long i = index; i < newEndIndex; ++i) { FileRecord record = new FileRecord(_bytesPerSector, _recordLength, (uint)i); WriteRecord(record); } } FileRecord newRecord = GetRecord(index, true); newRecord.ReInitialize(_bytesPerSector, _recordLength, (uint)index); _recordCache[index] = newRecord; newRecord.Flags = FileRecordFlags.InUse | flags; WriteRecord(newRecord); _self.UpdateRecordInMft(); return newRecord; } public FileRecord AllocateRecord(long index, FileRecordFlags flags) { _bitmap.MarkPresent(index); FileRecord newRecord = new FileRecord(_bytesPerSector, _recordLength, (uint)index); _recordCache[index] = newRecord; newRecord.Flags = FileRecordFlags.InUse | flags; WriteRecord(newRecord); _self.UpdateRecordInMft(); return newRecord; } public void RemoveRecord(FileRecordReference fileRef) { FileRecord record = GetRecord(fileRef.MftIndex, false); record.Reset(); WriteRecord(record); _recordCache.Remove(fileRef.MftIndex); _bitmap.MarkAbsent(fileRef.MftIndex); _self.UpdateRecordInMft(); } public FileRecord GetRecord(FileRecordReference fileReference) { FileRecord result = GetRecord(fileReference.MftIndex, false); if (result != null) { if (fileReference.SequenceNumber != 0 && result.SequenceNumber != 0) { if (fileReference.SequenceNumber != result.SequenceNumber) { throw new IOException("Attempt to get an MFT record with an old reference"); } } } return result; } public FileRecord GetRecord(long index, bool ignoreMagic) { return GetRecord(index, ignoreMagic, false); } public FileRecord GetRecord(long index, bool ignoreMagic, bool ignoreBitmap) { if (ignoreBitmap || _bitmap == null || _bitmap.IsPresent(index)) { FileRecord result = _recordCache[index]; if (result != null) { return result; } if ((index + 1) * _recordLength <= _recordStream.Length) { _recordStream.Position = index * _recordLength; byte[] recordBuffer = Utilities.ReadFully(_recordStream, _recordLength); result = new FileRecord(_bytesPerSector); result.FromBytes(recordBuffer, 0, ignoreMagic); result.LoadedIndex = (uint)index; } else { result = new FileRecord(_bytesPerSector, _recordLength, (uint)index); } _recordCache[index] = result; return result; } return null; } public void WriteRecord(FileRecord record) { int recordSize = record.Size; if (recordSize > _recordLength) { throw new IOException("Attempting to write over-sized MFT record"); } byte[] buffer = new byte[_recordLength]; record.ToBytes(buffer, 0); _recordStream.Position = record.MasterFileTableIndex * (long)_recordLength; _recordStream.Write(buffer, 0, _recordLength); _recordStream.Flush(); // We may have modified our own meta-data by extending the data stream, so // make sure our records are up-to-date. if (_self.MftRecordIsDirty) { DirectoryEntry dirEntry = _self.DirectoryEntry; if (dirEntry != null) { dirEntry.UpdateFrom(_self); } _self.UpdateRecordInMft(); } // Need to update Mirror. OpenRaw is OK because this is short duration, and we don't // extend or otherwise modify any meta-data, just the content of the Data stream. if (record.MasterFileTableIndex < 4 && _self.Context.GetFileByIndex != null) { File mftMirror = _self.Context.GetFileByIndex(MftMirrorIndex); if (mftMirror != null) { using (Stream s = mftMirror.OpenStream(AttributeType.Data, null, FileAccess.ReadWrite)) { s.Position = record.MasterFileTableIndex * (long)_recordLength; s.Write(buffer, 0, _recordLength); } } } } public long GetRecordOffset(FileRecordReference fileReference) { return fileReference.MftIndex * _recordLength; } public ClusterMap GetClusterMap() { int totalClusters = (int)Utilities.Ceil(_self.Context.BiosParameterBlock.TotalSectors64, _self.Context.BiosParameterBlock.SectorsPerCluster); ClusterRoles[] clusterToRole = new ClusterRoles[totalClusters]; object[] clusterToFile = new object[totalClusters]; Dictionary<object, string[]> fileToPaths = new Dictionary<object, string[]>(); for (int i = 0; i < totalClusters; ++i) { clusterToRole[i] = ClusterRoles.Free; } foreach (FileRecord fr in Records) { if (fr.BaseFile.Value != 0 || (fr.Flags & FileRecordFlags.InUse) == 0) { continue; } File f = new File(_self.Context, fr); foreach (var stream in f.AllStreams) { string fileId; if (stream.AttributeType == AttributeType.Data && !string.IsNullOrEmpty(stream.Name)) { fileId = f.IndexInMft.ToString(CultureInfo.InvariantCulture) + ":" + stream.Name; fileToPaths[fileId] = Utilities.Map(f.Names, n => n + ":" + stream.Name); } else { fileId = f.IndexInMft.ToString(CultureInfo.InvariantCulture); fileToPaths[fileId] = f.Names.ToArray(); } ClusterRoles roles = ClusterRoles.None; if (f.IndexInMft < MasterFileTable.FirstAvailableMftIndex) { roles |= ClusterRoles.SystemFile; if (f.IndexInMft == MasterFileTable.BootIndex) { roles |= ClusterRoles.BootArea; } } else { roles |= ClusterRoles.DataFile; } if (stream.AttributeType != AttributeType.Data) { roles |= ClusterRoles.Metadata; } foreach (var range in stream.GetClusters()) { for (long cluster = range.Offset; cluster < range.Offset + range.Count; ++cluster) { clusterToRole[cluster] = roles; clusterToFile[cluster] = fileId; } } } } return new ClusterMap(clusterToRole, clusterToFile, fileToPaths); } public void Dump(TextWriter writer, string indent) { writer.WriteLine(indent + "MASTER FILE TABLE"); writer.WriteLine(indent + " Record Length: " + _recordLength); foreach (var record in Records) { record.Dump(writer, indent + " "); foreach (AttributeRecord attr in record.Attributes) { attr.Dump(writer, indent + " "); } } } private static void Wipe(Stream s) { s.Position = 0; byte[] buffer = new byte[64 * Sizes.OneKiB]; int numWiped = 0; while (numWiped < s.Length) { int toWrite = (int)Math.Min(buffer.Length, s.Length - s.Position); s.Write(buffer, 0, toWrite); numWiped += toWrite; } } } }
using System; using System.Collections.Generic; namespace CslaGenerator.Metadata { /// <summary> /// A strongly-typed collection of <see cref="Rule"/> objects. /// </summary> [Serializable] public class RuleCollection : List<Rule> { } //public class RuleCollection : ICollection, IList, IEnumerable, ICloneable //{ // #region Interfaces // /// <summary> // /// Supports type-safe iteration over a <see cref="RuleCollection"/>. // /// </summary> // public interface IRuleCollectionEnumerator // { // /// <summary> // /// Gets the current element in the collection. // /// </summary> // Rule Current {get;} // /// <summary> // /// Advances the enumerator to the next element in the collection. // /// </summary> // /// <exception cref="InvalidOperationException"> // /// The collection was modified after the enumerator was created. // /// </exception> // /// <returns> // /// <c>true</c> if the enumerator was successfully advanced to the next element; // /// <c>false</c> if the enumerator has passed the end of the collection. // /// </returns> // bool MoveNext(); // /// <summary> // /// Sets the enumerator to its initial position, before the first element in the collection. // /// </summary> // void Reset(); // } // #endregion // private const int DEFAULT_CAPACITY = 16; // #region Implementation (data) // private Rule[] m_array; // private int m_count = 0; // [XmlIgnore] // private int m_version = 0; // #endregion // #region Static Wrappers // /// <summary> // /// Creates a synchronized (thread-safe) wrapper for a // /// <c>RuleCollection</c> instance. // /// </summary> // /// <returns> // /// An <c>RuleCollection</c> wrapper that is synchronized (thread-safe). // /// </returns> // public static RuleCollection Synchronized(RuleCollection list) // { // if(list==null) // throw new ArgumentNullException("list"); // return new SyncRuleCollection(list); // } // /// <summary> // /// Creates a read-only wrapper for a // /// <c>RuleCollection</c> instance. // /// </summary> // /// <returns> // /// An <c>RuleCollection</c> wrapper that is read-only. // /// </returns> // public static RuleCollection ReadOnly(RuleCollection list) // { // if(list==null) // throw new ArgumentNullException("list"); // return new ReadOnlyRuleCollection(list); // } // #endregion // #region Construction // /// <summary> // /// Initializes a new instance of the <c>RuleCollection</c> class // /// that is empty and has the default initial capacity. // /// </summary> // public RuleCollection() // { // m_array = new Rule[DEFAULT_CAPACITY]; // } // /// <summary> // /// Initializes a new instance of the <c>RuleCollection</c> class // /// that has the specified initial capacity. // /// </summary> // /// <param name="capacity"> // /// The number of elements that the new <c>RuleCollection</c> is initially capable of storing. // /// </param> // public RuleCollection(int capacity) // { // m_array = new Rule[capacity]; // } // /// <summary> // /// Initializes a new instance of the <c>RuleCollection</c> class // /// that contains elements copied from the specified <c>RuleCollection</c>. // /// </summary> // /// <param name="c">The <c>RuleCollection</c> whose elements are copied to the new collection.</param> // public RuleCollection(RuleCollection c) // { // m_array = new Rule[c.Count]; // AddRange(c); // } // /// <summary> // /// Initializes a new instance of the <c>RuleCollection</c> class // /// that contains elements copied from the specified <see cref="Rule"/> array. // /// </summary> // /// <param name="a">The <see cref="Rule"/> array whose elements are copied to the new list.</param> // public RuleCollection(Rule[] a) // { // m_array = new Rule[a.Length]; // AddRange(a); // } // protected enum Tag // { // Default // } // protected RuleCollection(Tag t) // { // m_array = null; // } // #endregion // #region Operations (type-safe ICollection) // /// <summary> // /// Gets the number of elements actually contained in the <c>RuleCollection</c>. // /// </summary> // public virtual int Count // { // get { return m_count; } // } // /// <summary> // /// Copies the entire <c>RuleCollection</c> to a one-dimensional // /// <see cref="Rule"/> array. // /// </summary> // /// <param name="array">The one-dimensional <see cref="Rule"/> array to copy to.</param> // public virtual void CopyTo(Rule[] array) // { // this.CopyTo(array, 0); // } // /// <summary> // /// Copies the entire <c>RuleCollection</c> to a one-dimensional // /// <see cref="Rule"/> array, starting at the specified index of the target array. // /// </summary> // /// <param name="array">The one-dimensional <see cref="Rule"/> array to copy to.</param> // /// <param name="start">The zero-based index in <paramref name="array"/> at which copying begins.</param> // public virtual void CopyTo(Rule[] array, int start) // { // if (m_count > array.GetUpperBound(0) + 1 - start) // throw new System.ArgumentException("Destination array was not long enough."); // Array.Copy(m_array, 0, array, start, m_count); // } // /// <summary> // /// Gets a value indicating whether access to the collection is synchronized (thread-safe). // /// </summary> // /// <returns>true if access to the ICollection is synchronized (thread-safe); otherwise, false.</returns> // public virtual bool IsSynchronized // { // get { return m_array.IsSynchronized; } // } // /// <summary> // /// Gets an object that can be used to synchronize access to the collection. // /// </summary> // public virtual object SyncRoot // { // get { return m_array.SyncRoot; } // } // #endregion // #region Operations (type-safe IList) // /// <summary> // /// Gets or sets the <see cref="Rule"/> at the specified index. // /// </summary> // /// <param name="index">The zero-based index of the element to get or set.</param> // /// <exception cref="ArgumentOutOfRangeException"> // /// <para><paramref name="index"/> is less than zero</para> // /// <para>-or-</para> // /// <para><paramref name="index"/> is equal to or greater than <see cref="RuleCollection.Count"/>.</para> // /// </exception> // public virtual Rule this[int index] // { // get // { // ValidateIndex(index); // throws // return m_array[index]; // } // set // { // ValidateIndex(index); // throws // ++m_version; // m_array[index] = value; // } // } // /// <summary> // /// Adds a <see cref="Rule"/> to the end of the <c>RuleCollection</c>. // /// </summary> // /// <param name="item">The <see cref="Rule"/> to be added to the end of the <c>RuleCollection</c>.</param> // /// <returns>The index at which the value has been added.</returns> // public virtual int Add(Rule item) // { // if (m_count == m_array.Length) // EnsureCapacity(m_count + 1); // m_array[m_count] = item; // m_version++; // return m_count++; // } // /// <summary> // /// Removes all elements from the <c>RuleCollection</c>. // /// </summary> // public virtual void Clear() // { // ++m_version; // m_array = new Rule[DEFAULT_CAPACITY]; // m_count = 0; // } // /// <summary> // /// Creates a shallow copy of the <see cref="RuleCollection"/>. // /// </summary> // public virtual object Clone() // { // RuleCollection newColl = new RuleCollection(m_count); // Array.Copy(m_array, 0, newColl.m_array, 0, m_count); // newColl.m_count = m_count; // newColl.m_version = m_version; // return newColl; // } // /// <summary> // /// Determines whether a given <see cref="Rule"/> is in the <c>RuleCollection</c>. // /// </summary> // /// <param name="item">The <see cref="Rule"/> to check for.</param> // /// <returns><c>true</c> if <paramref name="item"/> is found in the <c>RuleCollection</c>; otherwise, <c>false</c>.</returns> // public virtual bool Contains(Rule item) // { // for (int i=0; i != m_count; ++i) // if (m_array[i].Equals(item)) // return true; // return false; // } // /// <summary> // /// Returns the zero-based index of the first occurrence of a <see cref="Rule"/> // /// in the <c>RuleCollection</c>. // /// </summary> // /// <param name="item">The <see cref="Rule"/> to locate in the <c>RuleCollection</c>.</param> // /// <returns> // /// The zero-based index of the first occurrence of <paramref name="item"/> // /// in the entire <c>RuleCollection</c>, if found; otherwise, -1. // /// </returns> // public virtual int IndexOf(Rule item) // { // for (int i=0; i != m_count; ++i) // if (m_array[i].Equals(item)) // return i; // return -1; // } // /// <summary> // /// Inserts an element into the <c>RuleCollection</c> at the specified index. // /// </summary> // /// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param> // /// <param name="item">The <see cref="Rule"/> to insert.</param> // /// <exception cref="ArgumentOutOfRangeException"> // /// <para><paramref name="index"/> is less than zero</para> // /// <para>-or-</para> // /// <para><paramref name="index"/> is equal to or greater than <see cref="RuleCollection.Count"/>.</para> // /// </exception> // public virtual void Insert(int index, Rule item) // { // ValidateIndex(index, true); // throws // if (m_count == m_array.Length) // EnsureCapacity(m_count + 1); // if (index < m_count) // { // Array.Copy(m_array, index, m_array, index + 1, m_count - index); // } // m_array[index] = item; // m_count++; // m_version++; // } // /// <summary> // /// Removes the first occurrence of a specific <see cref="Rule"/> from the <c>RuleCollection</c>. // /// </summary> // /// <param name="item">The <see cref="Rule"/> to remove from the <c>RuleCollection</c>.</param> // /// <exception cref="ArgumentException"> // /// The specified <see cref="Rule"/> was not found in the <c>RuleCollection</c>. // /// </exception> // public virtual void Remove(Rule item) // { // int i = IndexOf(item); // if (i < 0) // throw new System.ArgumentException("Cannot remove the specified item because it was not found in the specified Collection."); // ++m_version; // RemoveAt(i); // } // /// <summary> // /// Removes the element at the specified index of the <c>RuleCollection</c>. // /// </summary> // /// <param name="index">The zero-based index of the element to remove.</param> // /// <exception cref="ArgumentOutOfRangeException"> // /// <para><paramref name="index"/> is less than zero</para> // /// <para>-or-</para> // /// <para><paramref name="index"/> is equal to or greater than <see cref="RuleCollection.Count"/>.</para> // /// </exception> // public virtual void RemoveAt(int index) // { // ValidateIndex(index); // throws // m_count--; // if (index < m_count) // { // Array.Copy(m_array, index + 1, m_array, index, m_count - index); // } // // We can't set the deleted entry equal to null, because it might be a value type. // // Instead, we'll create an empty single-element array of the right type and copy it // // over the entry we want to erase. // Rule[] temp = new Rule[1]; // Array.Copy(temp, 0, m_array, m_count, 1); // m_version++; // } // /// <summary> // /// Gets a value indicating whether the collection has a fixed size. // /// </summary> // /// <value>true if the collection has a fixed size; otherwise, false. The default is false</value> // public virtual bool IsFixedSize // { // get { return false; } // } // /// <summary> // /// gets a value indicating whether the <B>IList</B> is read-only. // /// </summary> // /// <value>true if the collection is read-only; otherwise, false. The default is false</value> // public virtual bool IsReadOnly // { // get { return false; } // } // #endregion // #region Operations (type-safe IEnumerable) // /// <summary> // /// Returns an enumerator that can iterate through the <c>RuleCollection</c>. // /// </summary> // /// <returns>An <see cref="Enumerator"/> for the entire <c>RuleCollection</c>.</returns> // public virtual IRuleCollectionEnumerator GetEnumerator() // { // return new Enumerator(this); // } // #endregion // #region Public helpers (just to mimic some nice features of ArrayList) // /// <summary> // /// Gets or sets the number of elements the <c>RuleCollection</c> can contain. // /// </summary> // public virtual int Capacity // { // get { return m_array.Length; } // set // { // if (value < m_count) // value = m_count; // if (value != m_array.Length) // { // if (value > 0) // { // Rule[] temp = new Rule[value]; // Array.Copy(m_array, temp, m_count); // m_array = temp; // } // else // { // m_array = new Rule[DEFAULT_CAPACITY]; // } // } // } // } // /// <summary> // /// Adds the elements of another <c>RuleCollection</c> to the current <c>RuleCollection</c>. // /// </summary> // /// <param name="x">The <c>RuleCollection</c> whose elements should be added to the end of the current <c>RuleCollection</c>.</param> // /// <returns>The new <see cref="RuleCollection.Count"/> of the <c>RuleCollection</c>.</returns> // public virtual int AddRange(RuleCollection x) // { // if (m_count + x.Count >= m_array.Length) // EnsureCapacity(m_count + x.Count); // Array.Copy(x.m_array, 0, m_array, m_count, x.Count); // m_count += x.Count; // m_version++; // return m_count; // } // /// <summary> // /// Adds the elements of a <see cref="Rule"/> array to the current <c>RuleCollection</c>. // /// </summary> // /// <param name="x">The <see cref="Rule"/> array whose elements should be added to the end of the <c>RuleCollection</c>.</param> // /// <returns>The new <see cref="RuleCollection.Count"/> of the <c>RuleCollection</c>.</returns> // public virtual int AddRange(Rule[] x) // { // if (m_count + x.Length >= m_array.Length) // EnsureCapacity(m_count + x.Length); // Array.Copy(x, 0, m_array, m_count, x.Length); // m_count += x.Length; // m_version++; // return m_count; // } // /// <summary> // /// Sets the capacity to the actual number of elements. // /// </summary> // public virtual void TrimToSize() // { // this.Capacity = m_count; // } // #endregion // #region Implementation (helpers) // /// <exception cref="ArgumentOutOfRangeException"> // /// <para><paramref name="index"/> is less than zero</para> // /// <para>-or-</para> // /// <para><paramref name="index"/> is equal to or greater than <see cref="RuleCollection.Count"/>.</para> // /// </exception> // private void ValidateIndex(int i) // { // ValidateIndex(i, false); // } // /// <exception cref="ArgumentOutOfRangeException"> // /// <para><paramref name="index"/> is less than zero</para> // /// <para>-or-</para> // /// <para><paramref name="index"/> is equal to or greater than <see cref="RuleCollection.Count"/>.</para> // /// </exception> // private void ValidateIndex(int i, bool allowEqualEnd) // { // int max = (allowEqualEnd)?(m_count):(m_count-1); // if (i < 0 || i > max) // throw new System.ArgumentOutOfRangeException("Index was out of range. Must be non-negative and less than the size of the collection.", (object)i, "Specified argument was out of the range of valid values."); // } // private void EnsureCapacity(int min) // { // int newCapacity = ((m_array.Length == 0) ? DEFAULT_CAPACITY : m_array.Length * 2); // if (newCapacity < min) // newCapacity = min; // this.Capacity = newCapacity; // } // #endregion // #region Implementation (ICollection) // void ICollection.CopyTo(Array array, int start) // { // this.CopyTo((Rule[])array, start); // } // #endregion // #region Implementation (IList) // object IList.this[int i] // { // get { return (object)this[i]; } // set { this[i] = (Rule)value; } // } // int IList.Add(object x) // { // return this.Add((Rule)x); // } // bool IList.Contains(object x) // { // return this.Contains((Rule)x); // } // int IList.IndexOf(object x) // { // return this.IndexOf((Rule)x); // } // void IList.Insert(int pos, object x) // { // this.Insert(pos, (Rule)x); // } // void IList.Remove(object x) // { // this.Remove((Rule)x); // } // void IList.RemoveAt(int pos) // { // this.RemoveAt(pos); // } // #endregion // #region Implementation (IEnumerable) // IEnumerator IEnumerable.GetEnumerator() // { // return (IEnumerator)(this.GetEnumerator()); // } // #endregion // #region Nested enumerator class // /// <summary> // /// Supports simple iteration over a <see cref="RuleCollection"/>. // /// </summary> // private class Enumerator : IEnumerator, IRuleCollectionEnumerator // { // #region Implementation (data) // private RuleCollection m_collection; // private int m_index; // private int m_version; // #endregion // #region Construction // /// <summary> // /// Initializes a new instance of the <c>Enumerator</c> class. // /// </summary> // /// <param name="tc"></param> // internal Enumerator(RuleCollection tc) // { // m_collection = tc; // m_index = -1; // m_version = tc.m_version; // } // #endregion // #region Operations (type-safe IEnumerator) // /// <summary> // /// Gets the current element in the collection. // /// </summary> // public Rule Current // { // get { return m_collection[m_index]; } // } // /// <summary> // /// Advances the enumerator to the next element in the collection. // /// </summary> // /// <exception cref="InvalidOperationException"> // /// The collection was modified after the enumerator was created. // /// </exception> // /// <returns> // /// <c>true</c> if the enumerator was successfully advanced to the next element; // /// <c>false</c> if the enumerator has passed the end of the collection. // /// </returns> // public bool MoveNext() // { // if (m_version != m_collection.m_version) // throw new System.InvalidOperationException("Collection was modified; enumeration operation may not execute."); // ++m_index; // return (m_index < m_collection.Count) ? true : false; // } // /// <summary> // /// Sets the enumerator to its initial position, before the first element in the collection. // /// </summary> // public void Reset() // { // m_index = -1; // } // #endregion // #region Implementation (IEnumerator) // object IEnumerator.Current // { // get { return (object)(this.Current); } // } // #endregion // } // #endregion // #region Nested Syncronized Wrapper class // [Serializable] // private class SyncRuleCollection : RuleCollection, System.Runtime.Serialization.IDeserializationCallback // { // #region Implementation (data) // private const int timeout = 0; // infinite // private RuleCollection collection; // [XmlIgnore] // private System.Threading.ReaderWriterLock rwLock; // #endregion // #region Construction // internal SyncRuleCollection(RuleCollection list) : base(Tag.Default) // { // rwLock = new System.Threading.ReaderWriterLock(); // collection = list; // } // #endregion // #region IDeserializationCallback Members // void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(object sender) // { // rwLock = new System.Threading.ReaderWriterLock(); // } // #endregion // #region Type-safe ICollection // public override void CopyTo(Rule[] array) // { // rwLock.AcquireReaderLock(timeout); // try // { // collection.CopyTo(array); // } // finally // { // rwLock.ReleaseReaderLock(); // } // } // public override void CopyTo(Rule[] array, int start) // { // rwLock.AcquireReaderLock(timeout); // try // { // collection.CopyTo(array, start); // } // finally // { // rwLock.ReleaseReaderLock(); // } // } // public override int Count // { // get // { // int count = 0; // rwLock.AcquireReaderLock(timeout); // try // { // count = collection.Count; // } // finally // { // rwLock.ReleaseReaderLock(); // } // return count; // } // } // public override bool IsSynchronized // { // get { return true; } // } // public override object SyncRoot // { // get { return collection.SyncRoot; } // } // #endregion // #region Type-safe IList // public override Rule this[int i] // { // get // { // Rule thisItem; // rwLock.AcquireReaderLock(timeout); // try // { // thisItem = collection[i]; // } // finally // { // rwLock.ReleaseReaderLock(); // } // return thisItem; // } // set // { // rwLock.AcquireWriterLock(timeout); // try // { // collection[i] = value; // } // finally // { // rwLock.ReleaseWriterLock(); // } // } // } // public override int Add(Rule x) // { // int result = 0; // rwLock.AcquireWriterLock(timeout); // try // { // result = collection.Add(x); // } // finally // { // rwLock.ReleaseWriterLock(); // } // return result; // } // public override void Clear() // { // rwLock.AcquireWriterLock(timeout); // try // { // collection.Clear(); // } // finally // { // rwLock.ReleaseWriterLock(); // } // } // public override bool Contains(Rule x) // { // bool result = false; // rwLock.AcquireReaderLock(timeout); // try // { // result = collection.Contains(x); // } // finally // { // rwLock.ReleaseReaderLock(); // } // return result; // } // public override int IndexOf(Rule x) // { // int result = 0; // rwLock.AcquireReaderLock(timeout); // try // { // result = collection.IndexOf(x); // } // finally // { // rwLock.ReleaseReaderLock(); // } // return result; // } // public override void Insert(int pos, Rule x) // { // rwLock.AcquireWriterLock(timeout); // try // { // collection.Insert(pos,x); // } // finally // { // rwLock.ReleaseWriterLock(); // } // } // public override void Remove(Rule x) // { // rwLock.AcquireWriterLock(timeout); // try // { // collection.Remove(x); // } // finally // { // rwLock.ReleaseWriterLock(); // } // } // public override void RemoveAt(int pos) // { // rwLock.AcquireWriterLock(timeout); // try // { // collection.RemoveAt(pos); // } // finally // { // rwLock.ReleaseWriterLock(); // } // } // public override bool IsFixedSize // { // get { return collection.IsFixedSize; } // } // public override bool IsReadOnly // { // get { return collection.IsReadOnly; } // } // #endregion // #region Type-safe IEnumerable // public override IRuleCollectionEnumerator GetEnumerator() // { // IRuleCollectionEnumerator enumerator = null; // rwLock.AcquireReaderLock(timeout); // try // { // enumerator = collection.GetEnumerator(); // } // finally // { // rwLock.ReleaseReaderLock(); // } // return enumerator; // } // #endregion // #region Public Helpers // // (just to mimic some nice features of ArrayList) // public override int Capacity // { // get // { // int result = 0; // rwLock.AcquireReaderLock(timeout); // try // { // result = collection.Capacity; // } // finally // { // rwLock.ReleaseReaderLock(); // } // return result; // } // set // { // rwLock.AcquireWriterLock(timeout); // try // { // collection.Capacity = value; // } // finally // { // rwLock.ReleaseWriterLock(); // } // } // } // public override int AddRange(RuleCollection x) // { // int result = 0; // rwLock.AcquireWriterLock(timeout); // try // { // result = collection.AddRange(x); // } // finally // { // rwLock.ReleaseWriterLock(); // } // return result; // } // public override int AddRange(Rule[] x) // { // int result = 0; // rwLock.AcquireWriterLock(timeout); // try // { // result = collection.AddRange(x); // } // finally // { // rwLock.ReleaseWriterLock(); // } // return result; // } // #endregion // } // #endregion // #region Nested Read Only Wrapper class // private class ReadOnlyRuleCollection : RuleCollection // { // #region Implementation (data) // private RuleCollection m_collection; // #endregion // #region Construction // internal ReadOnlyRuleCollection(RuleCollection list) : base(Tag.Default) // { // m_collection = list; // } // #endregion // #region Type-safe ICollection // public override void CopyTo(Rule[] array) // { // m_collection.CopyTo(array); // } // public override void CopyTo(Rule[] array, int start) // { // m_collection.CopyTo(array,start); // } // public override int Count // { // get { return m_collection.Count; } // } // public override bool IsSynchronized // { // get { return m_collection.IsSynchronized; } // } // public override object SyncRoot // { // get { return this.m_collection.SyncRoot; } // } // #endregion // #region Type-safe IList // public override Rule this[int i] // { // get { return m_collection[i]; } // set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } // } // public override int Add(Rule x) // { // throw new NotSupportedException("This is a Read Only Collection and can not be modified"); // } // public override void Clear() // { // throw new NotSupportedException("This is a Read Only Collection and can not be modified"); // } // public override bool Contains(Rule x) // { // return m_collection.Contains(x); // } // public override int IndexOf(Rule x) // { // return m_collection.IndexOf(x); // } // public override void Insert(int pos, Rule x) // { // throw new NotSupportedException("This is a Read Only Collection and can not be modified"); // } // public override void Remove(Rule x) // { // throw new NotSupportedException("This is a Read Only Collection and can not be modified"); // } // public override void RemoveAt(int pos) // { // throw new NotSupportedException("This is a Read Only Collection and can not be modified"); // } // public override bool IsFixedSize // { // get {return true;} // } // public override bool IsReadOnly // { // get {return true;} // } // #endregion // #region Type-safe IEnumerable // public override IRuleCollectionEnumerator GetEnumerator() // { // return m_collection.GetEnumerator(); // } // #endregion // #region Public Helpers // // (just to mimic some nice features of ArrayList) // public override int Capacity // { // get { return m_collection.Capacity; } // set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } // } // public override int AddRange(RuleCollection x) // { // throw new NotSupportedException("This is a Read Only Collection and can not be modified"); // } // public override int AddRange(Rule[] x) // { // throw new NotSupportedException("This is a Read Only Collection and can not be modified"); // } // #endregion // } // #endregion //} }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.hide001.hide001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.hide001.hide001; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> //<Expects Status=warning>\(28,16\).*CS0108</Expects> public class Base { public static int Status; public int this[int x] { get { Base.Status = 1; return int.MinValue; } set { Base.Status = 2; } } } public class Derived : Base { public int this[int x] { get { Base.Status = 3; return int.MaxValue; } set { if (value == int.MaxValue) Base.Status = 4; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); int x = 3; int xx = d[x]; if (xx != int.MaxValue || Base.Status != 3) return 1; d[x] = xx; if (Base.Status != 4) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.hide002.hide002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.hide002.hide002; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> //<Expects Status=warning>\(29,18\).*CS0108</Expects> public class C { } public class Base { public static int Status; public float this[C x] { get { Base.Status = 1; return float.NaN; } set { Base.Status = 2; } } } public class Derived : Base { public float this[C x] { get { Base.Status = 3; return float.NegativeInfinity; } set { if (value == float.NegativeInfinity) Base.Status = 4; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); C x = new C(); float f = d[x]; if (f != float.NegativeInfinity || Base.Status != 3) return 1; d[x] = f; if (Base.Status != 4) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.hide003.hide003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.hide003.hide003; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class C { } public class Base { public static int Status; public decimal this[C x] { get { Base.Status = 1; return decimal.One; } set { Base.Status = 2; } } } public class Derived : Base { public new decimal this[C x] { get { Base.Status = 3; return decimal.Zero; } set { Base.Status = 4; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); C x = new C(); decimal dd = d[x]; if (dd != decimal.Zero || Base.Status != 3) return 1; d[x] = dd; if (Base.Status != 4) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.overload001.overload001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.overload001.overload001; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public decimal this[short x] { get { Base.Status = 1; return decimal.MinValue; } set { if (value == decimal.MinValue) Base.Status = 2; } } } public class Derived : Base { public decimal this[int x] { get { Base.Status = 3; return decimal.MaxValue; } set { Base.Status = 4; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); short x = 3; // should call this[Derived] decimal dd = d[x]; if (dd != decimal.MaxValue || Base.Status != 3) return 1; d[x] = dd; if (Base.Status != 4) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.overload002.overload002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.overload002.overload002; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public char this[short x] { get { Base.Status = 1; return 'a'; } set { Base.Status = 2; } } } public class Derived : Base { public char this[int x] { get { Base.Status = 3; return 'b'; } set { if (value == 'b') Base.Status = 4; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); int x = 3; char c = d[x]; if (c != 'b' || Base.Status != 3) return 1; d[x] = c; if (Base.Status != 4) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.overload003.overload003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.overload003.overload003; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // Call methods with different accessibility level and selecting the right one.:) // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; protected string[] this[short x] { get { Base.Status = 1; return new string[] { "foo" } ; } set { Base.Status = 2; } } } public class Derived : Base { public string[] this[int x] { get { Base.Status = 3; return new string[] { string.Empty } ; } set { if (value.Length == 1 && value[0] == string.Empty) Base.Status = 4; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); int x = 3; string[] ss = d[x]; if (ss.Length != 1 || ss[0] != string.Empty || Base.Status != 3) return 1; d[x] = ss; if (Base.Status != 4) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.overload004.overload004 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.overload004.overload004; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // Call methods with different accessibility level and selecting the right one.:) // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public byte this[short x] { get { Base.Status = 1; return byte.MinValue; } set { if (value == byte.MinValue) Base.Status = 2; } } } public class Derived : Base { protected byte this[int x] { get { Base.Status = 3; return byte.MaxValue; } set { Base.Status = 4; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); var x = 3; byte bb = d[(short)x]; if (bb != byte.MinValue || Base.Status != 1) return 1; d[(short)x] = bb; if (Base.Status != 2) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.overload005.overload005 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.overload005.overload005; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // Call methods with different accessibility level and selecting the right one.:) // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public string this[short x] { get { Base.Status = 1; return "foo"; } set { if (value == "foo") Base.Status = 2; } } } public class Derived : Base { private string this[int x] { get { Base.Status = 3; return string.Empty; } set { Base.Status = 4; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); byte x = 3; string s = d[x]; if (s != "foo" || Base.Status != 1) return 1; d[x] = s; if (Base.Status != 2) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.overload006.overload006 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.overload006.overload006; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // Call methods with different accessibility level and selecting the right one.:) // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; internal float this[short x] { get { Base.Status = 1; return float.NegativeInfinity; } set { Base.Status = 2; } } } public class Derived : Base { public float this[int x] { get { Base.Status = 3; return float.NaN; } set { if (float.IsNaN(value)) Base.Status = 4; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); int x = 3; float f = d[x]; if (!float.IsNaN(f) || Base.Status != 3) return 1; d[x] = f; if (Base.Status != 4) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.overload007.overload007 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.overload007.overload007; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // Call methods with different accessibility level and selecting the right one.:) // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; protected internal char this[short x] { get { Base.Status = 1; return 'a'; } set { Base.Status = 2; } } } public class Derived : Base { public char this[int x] { get { Base.Status = 3; return 'b'; } set { Base.Status = 4; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); int x = 3; char c = d[x]; if (c != 'b' || Base.Status != 3) return 1; d[x] = c; if (Base.Status != 4) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.overload008.overload008 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.overload008.overload008; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // Select the best method to call. // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public int this[dynamic x] { get { Base.Status = 1; return 0; } set { Base.Status = 2; } } public int this[short x] { get { Base.Status = 3; return int.MinValue; } set { Base.Status = 4; } } } public class Derived : Base { public int this[int x] { get { Base.Status = 5; return int.MaxValue; } set { if (value == int.MaxValue) Base.Status = 6; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); dynamic x = 3; int xx = d[x]; if (xx != int.MaxValue || Base.Status != 5) return 1; d[x] = xx; if (Base.Status != 6) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr001.ovr001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr001.ovr001; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public virtual string this[int x] { get { Base.Status = 1; return string.Empty; } set { Base.Status = 2; } } } public class Derived : Base { public override string this[int x] { get { Base.Status = 3; return "foo"; } set { Base.Status = 4; } } public string this[long l] { get { Base.Status = 5; return "bar"; } set { Base.Status = 6; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); int x = 3; string ss = d[x]; if (ss != "bar" || Base.Status != 5) return 1; d[x] = ss; if (Base.Status != 6) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr002.ovr002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr002.ovr002; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public virtual int this[int x] { get { Base.Status = 1; return int.MaxValue; } set { Base.Status = 2; } } } public class Derived : Base { public override int this[int x] { get { Base.Status = 3; return int.MinValue; } set { Base.Status = 4; } } public int this[long l] { get { Base.Status = 5; return 0; } set { Base.Status = 6; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); short x = 3; int xx = d[x]; if (xx != 0 || Base.Status != 5) return 1; d[x] = xx; if (Base.Status != 6) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr003.ovr003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr003.ovr003; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public virtual string this[string x] { get { Base.Status = 1; return string.Empty; } set { Base.Status = 2; } } } public class Derived : Base { public override string this[string x] { get { Base.Status = 3; return "foo"; } set { Base.Status = 4; } } public string this[object o] { get { Base.Status = 5; return "bar"; } set { Base.Status = 6; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); string x = "3"; string ss = d[x]; if (ss != "bar" || Base.Status != 5) return 1; d[x] = ss; if (Base.Status != 6) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr004.ovr004 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr004.ovr004; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class C { } public class D : C { } public class Base { public static int Status; public virtual int this[D x] { get { Base.Status = 1; return int.MaxValue; } set { Base.Status = 2; } } } public class Derived : Base { public override int this[D x] { get { Base.Status = 3; return int.MinValue; } set { Base.Status = 4; } } public int this[C o] { get { Base.Status = 5; return 0; } set { Base.Status = 6; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); C x = new C(); int xx = d[x]; if (xx != 0 || Base.Status != 5) return 1; d[x] = xx; if (Base.Status != 6) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr005.ovr005 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr005.ovr005; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class C { } public class D : C { } public class Base { public static int Status; public virtual int this[D x] { get { Base.Status = 1; return int.MaxValue; } set { Base.Status = 2; } } } public class Derived : Base { public override int this[D x] { get { Base.Status = 3; return int.MinValue; } set { Base.Status = 4; } } public int this[C o] { get { Base.Status = 5; return 0; } set { Base.Status = 6; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); D x = new D(); int xx = d[x]; if (xx != 0 || Base.Status != 5) return 1; d[x] = xx; if (Base.Status != 6) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr006.ovr006 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr006.ovr006; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class C { } public class D : C { } public class Base { public static int Status; public virtual int this[D x] { get { Base.Status = 1; return 1; } set { Base.Status = 2; } } } public class Derived : Base { public override int this[D x] { get { Base.Status = 3; return 3; } set { Base.Status = 4; } } public int this[C o] { get { Base.Status = 5; return 5; } set { Base.Status = 6; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); C x = new D(); int xx = d[x]; if (xx != 5 || Base.Status != 5) return 1; d[x] = xx; if (Base.Status != 6) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr007.ovr007 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr007.ovr007; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class C { } public class D : C { } public class Base { public static int Status; public virtual int this[int x] { get { Base.Status = 1; return 1; } set { Base.Status = 2; } } } public class Derived : Base { public override int this[int x] { get { Base.Status = 3; return 3; } set { Base.Status = 4; } } public int this[string o] { get { Base.Status = 5; return 5; } set { Base.Status = 6; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); int x = 3; int xx = d[x]; if (xx != 3 || Base.Status != 3) return 1; d[x] = xx; if (Base.Status != 4) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr008.ovr008 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr008.ovr008; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class C { } public class Base { public static int Status; public virtual int this[int x] { get { Base.Status = 1; return 1; } set { Base.Status = 2; } } } public class Derived : Base { public override int this[int x] { get { Base.Status = 3; return 3; } set { Base.Status = 4; } } public int this[C o] { get { Base.Status = 5; return 5; } set { Base.Status = 6; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); short x = 3; int xx = d[x]; if (xx != 3 || Base.Status != 3) return 1; d[x] = xx; if (Base.Status != 4) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr009.ovr009 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr009.ovr009; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public enum E { first, second } public class Base { public static int Status; public virtual int this[string x] { get { Base.Status = 1; return 1; } set { Base.Status = 2; } } } public class Derived : Base { public override int this[string x] { get { Base.Status = 3; return 3; } set { Base.Status = 4; } } public int this[E o] { get { Base.Status = 5; return 5; } set { Base.Status = 6; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); string x = "adfs"; int xx = d[x]; if (xx != 3 || Base.Status != 3) return 1; d[x] = xx; if (Base.Status != 4) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr010.ovr010 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr010.ovr010; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class C { public static implicit operator int (C c) { return 0; } } public class Base { public static int Status; public virtual int this[C x] { get { Base.Status = 1; return 1; } set { Base.Status = 2; } } } public class Derived : Base { public override int this[C x] { get { Base.Status = 3; return 3; } set { Base.Status = 4; } } public int this[int o] { get { Base.Status = 5; return 5; } set { Base.Status = 6; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); C x = new C(); //This should go to Base.Status = 3 int xx = d[x]; if (xx != 5 || Base.Status != 5) return 1; d[x] = xx; if (Base.Status != 6) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr011.ovr011 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr011.ovr011; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class C { public static implicit operator int (C c) { return 0; } } public class Base { public static int Status; public virtual int this[C x] { get { Base.Status = 1; return 1; } set { Base.Status = 2; } } } public class Derived : Base { public override int this[C x] { get { Base.Status = 3; return 3; } set { Base.Status = 4; } } public int this[long o] { get { Base.Status = 5; return 5; } set { Base.Status = 6; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); C x = new C(); //This should go to Base.Status = 3 int xx = d[x]; if (xx != 5 || Base.Status != 5) return 1; d[x] = xx; if (Base.Status != 6) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr012.ovr012 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr012.ovr012; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public virtual int this[int x] { get { Base.Status = 1; return 1; } set { Base.Status = 2; } } public virtual int this[long y] { get { Base.Status = 3; return 3; } set { Base.Status = 4; } } } public class Derived : Base { public override int this[long x] { get { Base.Status = 5; return 5; } set { Base.Status = 6; } } } public class FurtherDerived : Derived { public override int this[int y] { get { Base.Status = 7; return 7; } set { Base.Status = 8; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new FurtherDerived(); long x = 3; int xx = d[x]; if (xx != 5 || Base.Status != 5) return 1; d[x] = xx; if (Base.Status != 6) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovrdynamic001.ovrdynamic001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovrdynamic001.ovrdynamic001; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public virtual int this[object x] { get { Base.Status = 1; return 1; } set { Base.Status = 2; } } } public class Derived : Base { public override int this[dynamic x] { get { Base.Status = 3; return 2; } set { Base.Status = 4; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); Base x = new Base(); //This should go to Base.Status = 3 int xx = d[x]; if (xx != 2 || Base.Status != 3) return 1; d[x] = xx; if (Base.Status != 4) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovrdynamic002.ovrdynamic002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovrdynamic002.ovrdynamic002; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public virtual int this[dynamic x] { get { Base.Status = 1; return 1; } set { Base.Status = 2; } } } public class Derived : Base { public override int this[object x] { get { Base.Status = 3; return 2; } set { Base.Status = 4; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); Base x = new Base(); //This should go to Base.Status = 3 int xx = d[x]; if (xx != 2 || Base.Status != 3) return 1; d[x] = xx; if (Base.Status != 4) return 1; return 0; } } // </Code> }
using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using OpenTK.Graphics.OpenGL; using nzy3D.Colors; using nzy3D.Events; using nzy3D.Maths; using nzy3D.Plot3D.Primitives.Axes; using nzy3D.Plot3D.Rendering.Canvas; using nzy3D.Plot3D.Rendering.Legends; using nzy3D.Plot3D.Rendering.View; using nzy3D.Plot3D.Transform; namespace nzy3D.Plot3D.Primitives { /// <summary> /// A <see cref="AbstractDrawable"/> defines objects that may be rendered into an OpenGL /// context provided by a <see cref="ICanvas"/>. /// <br/> /// A <see cref="AbstractDrawable"/> must basically provide a rendering function called draw() /// that receives a reference to a GL2 and a GLU context. It may also /// use a reference to a Camera in order to implement specific behaviors /// according to the Camera position. /// <br/> /// A <see cref="AbstractDrawable"/> provides services for setting the transformation factor /// that is used inside the draw function, as well as a getter of the /// object's BoundingBox3d. Note that the BoundingBox must be set by /// a concrete descendant of a <see cref="AbstractDrawable"/>. /// <br/> /// A good practice is to define a setData function for initializing a <see cref="AbstractDrawable"/> /// and building its polygons. Since each class may have its own inputs, setData /// is not part of the interface but should be used as a convention. /// When not defining a setData function, a <see cref="AbstractDrawable"/> may have its data loaded by /// an "add(Drawable)" function. /// <br/> /// Note: A <see cref="AbstractDrawable"/> may last provide the information whether it is displayed or not, /// according to a rendering into the FeedBack buffer. This is currently supported /// specifically for the <see cref="AxeBox"/> object but could be extended with some few more /// algorithm for referencing all GL2 polygons. /// /// @author Martin Pernollet /// </summary> /// <remarks></remarks> public abstract class AbstractDrawable : IGLRenderer, ISortableDraw { internal Transform.Transform _transform; internal BoundingBox3d _bbox; internal Legend _legend = null; internal List<IDrawableListener> _listeners = new List<IDrawableListener>(); internal bool _displayed = true; internal bool _legendDisplayed = false; public void Dispose() { if ((_listeners != null)) { _listeners.Clear(); } } public abstract void Draw(Rendering.View.Camera cam); internal void CallC(Color c) { GL.Color4(c.r, c.g, c.b, c.a); } internal void CallC(Color c, float alpha) { GL.Color4(c.r, c.g, c.b, alpha); } internal void CallWithAlphaFactor(Color c, float alpha) { GL.Color4(c.r, c.g, c.b, c.a * alpha); } /// <summary> /// Get / Set object's transformation that is applied at the /// beginning of a call to "draw()" /// </summary> public virtual Transform.Transform Transform { get { return _transform; } set { _transform = value; fireDrawableChanged(DrawableChangedEventArgs.FieldChanged.Transform); } } /// <summary> /// Return the BoundingBox of this object /// </summary> public virtual BoundingBox3d Bounds { get { return _bbox; } } /// <summary> /// Return the barycentre of this object, which is /// computed as the center of its bounding box. If the bounding /// box is not available, the returned value is <see cref=" Coord3d.INVALID"/> /// </summary> public virtual Coord3d Barycentre { get { if ((_bbox != null)) { return _bbox.getCenter(); } else { return Coord3d.INVALID; } } } /// <summary> /// Get / Set the display status of this object /// </summary> public virtual bool Displayed { get { return _displayed; } set { _displayed = value; fireDrawableChanged(DrawableChangedEventArgs.FieldChanged.Displayed); } } public virtual double getDistance(Rendering.View.Camera camera) { return Barycentre.distance(camera.Eye); } public virtual double getLongestDistance(Rendering.View.Camera camera) { return getDistance(camera); } public virtual double getShortestDistance(Rendering.View.Camera camera) { return getDistance(camera); } public Legend Legend { get { return _legend; } set { _legend = value; _legendDisplayed = true; fireDrawableChanged(DrawableChangedEventArgs.FieldChanged.Metadata); } } public bool HasLegend { get { return (_legend != null); } } public bool LegendDisplayed { get { return _legendDisplayed; } set { _legendDisplayed = value; } } public void addDrawableListener(IDrawableListener listener) { _listeners.Add(listener); } public void removeDrawableListener(IDrawableListener listener) { _listeners.Remove(listener); } internal void fireDrawableChanged(DrawableChangedEventArgs.FieldChanged eventType) { fireDrawableChanged(new DrawableChangedEventArgs(this, eventType)); } internal void fireDrawableChanged(DrawableChangedEventArgs e) { foreach (IDrawableListener listener in _listeners) { listener.DrawableChanged(e); } } /// <summary> /// Returns the string representation of this object /// </summary> public override string ToString() { return toString(0); } public virtual string toString(int depth) { return Utils.blanks(depth) + "(" + this.GetType().Name + ")"; } } } //======================================================= //Service provided by Telerik (www.telerik.com) //Conversion powered by NRefactory. //Twitter: @telerik //Facebook: facebook.com/telerik //=======================================================
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using XunitPlatformID = Xunit.PlatformID; namespace System.IO.Tests { public class File_Create_str : FileSystemTest { #region Utilities public virtual FileStream Create(string path) { return File.Create(path); } #endregion #region UniversalTests [Fact] public void NullPath() { Assert.Throws<ArgumentNullException>(() => Create(null)); } [Fact] public void EmptyPath() { Assert.Throws<ArgumentException>(() => Create(string.Empty)); } [Fact] public void NonExistentPath() { Assert.Throws<DirectoryNotFoundException>(() => Create(Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName()))); } [Fact] public void CreateCurrentDirectory() { Assert.Throws<UnauthorizedAccessException>(() => Create(".")); } [Fact] public void ValidCreation() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); using (FileStream stream = Create(testFile)) { Assert.True(File.Exists(testFile)); Assert.Equal(0, stream.Length); Assert.Equal(0, stream.Position); } } [Fact] [PlatformSpecific(XunitPlatformID.Windows)] public void ValidCreation_ExtendedSyntax() { DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath()); Assert.StartsWith(IOInputs.ExtendedPrefix, testDir.FullName); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); using (FileStream stream = Create(testFile)) { Assert.True(File.Exists(testFile)); Assert.Equal(0, stream.Length); Assert.Equal(0, stream.Position); } } [Fact] [PlatformSpecific(XunitPlatformID.Windows)] public void ValidCreation_LongPathExtendedSyntax() { DirectoryInfo testDir = Directory.CreateDirectory(IOServices.GetPath(IOInputs.ExtendedPrefix + TestDirectory, characterCount: 500).FullPath); Assert.StartsWith(IOInputs.ExtendedPrefix, testDir.FullName); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); using (FileStream stream = Create(testFile)) { Assert.True(File.Exists(testFile)); Assert.Equal(0, stream.Length); Assert.Equal(0, stream.Position); } } [Fact] public void CreateInParentDirectory() { string testFile = GetTestFileName(); using (FileStream stream = Create(Path.Combine(TestDirectory, "DoesntExists", "..", testFile))) { Assert.True(File.Exists(Path.Combine(TestDirectory, testFile))); } } [Fact] public void LegalSymbols() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName() + "!@#$%^&"); using (FileStream stream = Create(testFile)) { Assert.True(File.Exists(testFile)); } } [Fact] public void InvalidDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName(), GetTestFileName()); Assert.Throws<DirectoryNotFoundException>(() => Create(testFile)); } [Fact] public void FileInUse() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); using (FileStream stream = Create(testFile)) { Assert.True(File.Exists(testFile)); Assert.Throws<IOException>(() => Create(testFile)); } } [Fact] public void FileAlreadyExists() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); Create(testFile).Dispose(); Assert.True(File.Exists(testFile)); Create(testFile).Dispose(); Assert.True(File.Exists(testFile)); } [Fact] public void OverwriteReadOnly() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); Create(testFile).Dispose(); Assert.True(File.Exists(testFile)); Create(testFile).Dispose(); Assert.True(File.Exists(testFile)); } [Fact] public void LongPath() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Assert.Throws<PathTooLongException>(() => Create(Path.Combine(testDir.FullName, new string('a', 300)))); //TODO #645: File creation does not yet have long path support on Unix or Windows //using (Create(Path.Combine(testDir.FullName, new string('k', 257)))) //{ // Assert.True(File.Exists(Path.Combine(testDir.FullName, new string('k', 257)))); //} } #endregion #region PlatformSpecific [Fact] [PlatformSpecific(CaseSensitivePlatforms)] public void CaseSensitive() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); using (File.Create(testFile + "AAAA")) using (File.Create(testFile + "aAAa")) { Assert.False(File.Exists(testFile + "AaAa")); Assert.True(File.Exists(testFile + "AAAA")); Assert.True(File.Exists(testFile + "aAAa")); Assert.Equal(2, Directory.GetFiles(testDir.FullName).Length); } Assert.Throws<DirectoryNotFoundException>(() => File.Create(testFile.ToLowerInvariant())); } [Fact] [PlatformSpecific(CaseInsensitivePlatforms)] public void CaseInsensitive() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); File.Create(testFile + "AAAA").Dispose(); File.Create(testFile.ToLowerInvariant() + "aAAa").Dispose(); Assert.Equal(1, Directory.GetFiles(testDir.FullName).Length); } [Fact] [PlatformSpecific(XunitPlatformID.Windows)] public void WindowsWildCharacterPath() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Assert.Throws<ArgumentException>(() => Create(Path.Combine(testDir.FullName, "dls;d", "442349-0", "v443094(*)(+*$#$*", new string(Path.DirectorySeparatorChar, 3)))); Assert.Throws<ArgumentException>(() => Create(Path.Combine(testDir.FullName, "*"))); Assert.Throws<ArgumentException>(() => Create(Path.Combine(testDir.FullName, "Test*t"))); Assert.Throws<ArgumentException>(() => Create(Path.Combine(testDir.FullName, "*Tes*t"))); } [Fact] [PlatformSpecific(XunitPlatformID.Windows)] public void WindowsWhitespacePath() { Assert.Throws<ArgumentException>(() => Create(" ")); Assert.Throws<ArgumentException>(() => Create(" ")); Assert.Throws<ArgumentException>(() => Create("\n")); Assert.Throws<ArgumentException>(() => Create(">")); Assert.Throws<ArgumentException>(() => Create("<")); Assert.Throws<ArgumentException>(() => Create("\0")); Assert.Throws<ArgumentException>(() => Create("\t")); } [Fact] [PlatformSpecific(XunitPlatformID.AnyUnix)] public void UnixWhitespacePath() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Assert.Throws<ArgumentException>(() => Create("\0")); using (Create(Path.Combine(testDir.FullName, " "))) using (Create(Path.Combine(testDir.FullName, " "))) using (Create(Path.Combine(testDir.FullName, "\n"))) using (Create(Path.Combine(testDir.FullName, ">"))) using (Create(Path.Combine(testDir.FullName, "<"))) using (Create(Path.Combine(testDir.FullName, "\t"))) { Assert.True(File.Exists(Path.Combine(testDir.FullName, " "))); Assert.True(File.Exists(Path.Combine(testDir.FullName, " "))); Assert.True(File.Exists(Path.Combine(testDir.FullName, "\n"))); Assert.True(File.Exists(Path.Combine(testDir.FullName, ">"))); Assert.True(File.Exists(Path.Combine(testDir.FullName, "<"))); Assert.True(File.Exists(Path.Combine(testDir.FullName, "\t"))); } } #endregion } public class File_Create_str_i : File_Create_str { public override FileStream Create(string path) { return File.Create(path, 4096); // Default buffer size } public virtual FileStream Create(string path, int bufferSize) { return File.Create(path, bufferSize); } [Fact] public void NegativeBuffer() { Assert.Throws<ArgumentOutOfRangeException>(() => Create(GetTestFilePath(), -1)); Assert.Throws<ArgumentOutOfRangeException>(() => Create(GetTestFilePath(), -100)); } } public class File_Create_str_i_fo : File_Create_str_i { public override FileStream Create(string path) { return File.Create(path, 4096, FileOptions.Asynchronous); } public override FileStream Create(string path, int bufferSize) { return File.Create(path, bufferSize, FileOptions.Asynchronous); } } }
// // TextLayoutBackendHandler.cs // // Author: // Eric Maupin <ermau@xamarin.com> // Lytico (http://limada.sourceforge.net) // // Copyright (c) 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 Xwt.Backends; using Xwt.Drawing; using Font = Xwt.Drawing.Font; using System.Windows.Media; using System.Windows; using System.Collections.Generic; using System.Collections.ObjectModel; namespace Xwt.WPFBackend { public class WpfTextLayoutBackendHandler : TextLayoutBackendHandler { public override object Create () { return new TextLayoutBackend (); } public override void SetWidth (object backend, double value) { var t = (TextLayoutBackend)backend; t.SetWidth(value); } public override void SetHeight (object backend, double value) { var t = (TextLayoutBackend)backend; t.SetHeight(value); } public override void SetText (object backend, string text) { var t = (TextLayoutBackend)backend; t.SetText(text); } public override void SetFont (object backend, Font font) { var t = (TextLayoutBackend)backend; t.SetFont (font); } public override void SetTrimming (object backend, Xwt.Drawing.TextTrimming textTrimming) { var t = (TextLayoutBackend)backend; t.SetTrimming(textTrimming); } public override Size GetSize (object backend) { var t = (TextLayoutBackend)backend; return new Size (t.FormattedText.WidthIncludingTrailingWhitespace, t.FormattedText.Height); } public override Point GetCoordinateFromIndex (object backend, int index) { var geometry = ((TextLayoutBackend)backend).FormattedText.BuildHighlightGeometry(new System.Windows.Point(0, 0), index, 1); var point = new Point { X = geometry.Bounds.X, Y = geometry.Bounds.Y }; return point; } public override int GetIndexFromCoordinates (object backend, double x, double y) { return 0; } public override double GetBaseline (object backend) { var t = (TextLayoutBackend)backend; return t.FormattedText.Baseline; } public override void AddAttribute (object backend, TextAttribute attribute) { var t = (TextLayoutBackend)backend; t.AddAttribute(attribute); } public override void ClearAttributes (object backend) { var t = (TextLayoutBackend)backend; t.ClearAttributes(); } } class TextLayoutBackend { static Typeface defaultFont = new Typeface("Verdana"); System.Windows.Media.FormattedText formattedText; List<TextAttribute> attributes; SolidColorBrush brush = System.Windows.Media.Brushes.Black; double width; double height; string text = String.Empty; Xwt.Drawing.TextTrimming? textTrimming; bool needsRebuild; IList<BackgroundTextAttribute> backgroundTextAttributes = new List<BackgroundTextAttribute>(); public System.Windows.Media.FormattedText FormattedText { get { if (formattedText == null || needsRebuild) Rebuild (); return formattedText; } } public void SetWidth(double value) { if (width != value) { width = value; if (formattedText != null) { if (value >= 0) FormattedText.MaxTextWidth = value; else needsRebuild = true; } } } public void SetHeight(double value) { if (height != value) { height = value; if (formattedText != null) { if (value >= 0) FormattedText.MaxTextHeight = value; else needsRebuild = true; } } } public void SetText(string text) { if (this.text != text) { this.text = text ?? String.Empty; needsRebuild = true; } } public void SetFont(Font font) { if (!font.Equals(this.Font)) { this.Font = font; if (formattedText != null) ApplyFont(); } } void ApplyFont () { var f = (FontData)Toolkit.GetBackend(Font); FormattedText.SetFontFamily(f.Family); FormattedText.SetFontSize(f.GetDeviceIndependentPixelSize()); FormattedText.SetFontStretch(f.Stretch); FormattedText.SetFontStyle(f.Style); FormattedText.SetFontWeight(f.Weight); } public void SetTrimming(Xwt.Drawing.TextTrimming textTrimming) { if (this.textTrimming != textTrimming) { this.textTrimming = textTrimming; if (formattedText != null) ApplyTrimming(); } } void ApplyTrimming () { switch (textTrimming) { case Xwt.Drawing.TextTrimming.WordElipsis: FormattedText.Trimming = System.Windows.TextTrimming.WordEllipsis; break; default: FormattedText.Trimming = System.Windows.TextTrimming.None; break; } } public void SetDefaultForeground(SolidColorBrush fg) { if (fg.Color != brush.Color) { brush = fg; needsRebuild = true; } } public void AddAttribute(TextAttribute attribute) { if (attributes == null) attributes = new List<TextAttribute>(); attributes.Add(attribute); if (formattedText != null) ApplyAttribute(attribute); } public void ClearAttributes () { attributes = null; needsRebuild = true; } void ApplyAttribute(TextAttribute attribute) { if (attribute is FontStyleTextAttribute) { var xa = (FontStyleTextAttribute)attribute; FormattedText.SetFontStyle(xa.Style.ToWpfFontStyle(), xa.StartIndex, xa.Count); } else if (attribute is FontWeightTextAttribute) { var xa = (FontWeightTextAttribute)attribute; FormattedText.SetFontWeight(xa.Weight.ToWpfFontWeight(), xa.StartIndex, xa.Count); } else if (attribute is ColorTextAttribute) { var xa = (ColorTextAttribute)attribute; if (xa.StartIndex < FormattedText.Text.Length) { FormattedText.SetForegroundBrush(new SolidColorBrush(xa.Color.ToWpfColor()), xa.StartIndex, Math.Min(xa.Count, FormattedText.Text.Length - xa.StartIndex)); } } else if (attribute is StrikethroughTextAttribute) { var xa = (StrikethroughTextAttribute)attribute; var dec = new TextDecoration(TextDecorationLocation.Strikethrough, null, 0, TextDecorationUnit.FontRecommended, TextDecorationUnit.FontRecommended); TextDecorationCollection col = new TextDecorationCollection(); col.Add(dec); FormattedText.SetTextDecorations(col, xa.StartIndex, xa.Count); } else if (attribute is UnderlineTextAttribute) { var xa = (UnderlineTextAttribute)attribute; var dec = new TextDecoration(TextDecorationLocation.Underline, null, 0, TextDecorationUnit.FontRecommended, TextDecorationUnit.FontRecommended); TextDecorationCollection col = new TextDecorationCollection(); col.Add(dec); FormattedText.SetTextDecorations(col, xa.StartIndex, xa.Count); } else if (attribute is BackgroundTextAttribute) { // https://stackoverflow.com/questions/37381723/how-to-set-formattedtext-background-color-in-c-sharp // No, you cannot. // As is the case for anything you draw into a DrawingContext, // the properties of the object control only the object itself, // i.e. what's actually drawn for that object, not what's // behind it or around it. // Drawing a rectangle behind the text is the most obvious workaround, // and would be entirely appropriate when using the object in a DrawingContext. backgroundTextAttributes.Add((BackgroundTextAttribute)attribute); } } public void Rebuild () { backgroundTextAttributes.Clear(); needsRebuild = false; var dir = System.Windows.FlowDirection.LeftToRight; formattedText = new System.Windows.Media.FormattedText(text, System.Globalization.CultureInfo.CurrentCulture, dir, defaultFont, 36, brush); if (width > 0) formattedText.MaxTextWidth = width; if (height > 0) formattedText.MaxTextHeight = height; if (Font != null) ApplyFont(); if (textTrimming != null) ApplyTrimming(); if (attributes != null) foreach (var at in attributes) ApplyAttribute(at); } public Font Font { get; private set; } public ReadOnlyCollection<BackgroundTextAttribute> BackgroundTextAttributes { get { return new ReadOnlyCollection<BackgroundTextAttribute>(backgroundTextAttributes); } } } }
/* * Copyright 2012-2015 Aerospike, Inc. * * Portions may be licensed to Aerospike, Inc. under one or more contributor * license agreements. * * 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; namespace Aerospike.Client { public abstract class Command { // Flags commented out are not supported by this client. public static readonly int INFO1_READ = (1 << 0); // Contains a read operation. public static readonly int INFO1_GET_ALL = (1 << 1); // Get all bins. public static readonly int INFO1_BATCH = (1 << 3); // Batch read or exists. public static readonly int INFO1_NOBINDATA = (1 << 5); // Do not read the bins. public static readonly int INFO1_CONSISTENCY_ALL = (1 << 6); // Involve all replicas in read operation. public static readonly int INFO2_WRITE = (1 << 0); // Create or update record public static readonly int INFO2_DELETE = (1 << 1); // Fling a record into the belly of Moloch. public static readonly int INFO2_GENERATION = (1 << 2); // Update if expected generation == old. public static readonly int INFO2_GENERATION_GT = (1 << 3); // Update if new generation >= old, good for restore. public static readonly int INFO2_GENERATION_DUP = (1 << 4); // Create a duplicate on a generation collision. public static readonly int INFO2_CREATE_ONLY = (1 << 5); // Create only. Fail if record already exists. public static readonly int INFO3_LAST = (1 << 0); // This is the last of a multi-part message. public static readonly int INFO3_COMMIT_MASTER = (1 << 1); // Commit to master only before declaring success. public static readonly int INFO3_UPDATE_ONLY = (1 << 3); // Update only. Merge bins. public static readonly int INFO3_CREATE_OR_REPLACE = (1 << 4); // Create or completely replace record. public static readonly int INFO3_REPLACE_ONLY = (1 << 5); // Completely replace existing record only. public const int MSG_TOTAL_HEADER_SIZE = 30; public const int FIELD_HEADER_SIZE = 5; public const int OPERATION_HEADER_SIZE = 8; public const int MSG_REMAINING_HEADER_SIZE = 22; public const int DIGEST_SIZE = 20; public const ulong CL_MSG_VERSION = 2L; public const ulong AS_MSG_TYPE = 3L; protected internal byte[] dataBuffer; protected internal int dataOffset; public void SetWrite(WritePolicy policy, Operation.Type operation, Key key, Bin[] bins) { Begin(); int fieldCount = EstimateKeySize(policy, key); foreach (Bin bin in bins) { EstimateOperationSize(bin); } SizeBuffer(); WriteHeader(policy, 0, Command.INFO2_WRITE, fieldCount, bins.Length); WriteKey(policy, key); foreach (Bin bin in bins) { WriteOperation(bin, operation); } End(); } public void SetDelete(WritePolicy policy, Key key) { Begin(); int fieldCount = EstimateKeySize(policy, key); SizeBuffer(); WriteHeader(policy, 0, Command.INFO2_WRITE | Command.INFO2_DELETE, fieldCount, 0); WriteKey(policy, key); End(); } public void SetTouch(WritePolicy policy, Key key) { Begin(); int fieldCount = EstimateKeySize(policy, key); EstimateOperationSize(); SizeBuffer(); WriteHeader(policy, 0, Command.INFO2_WRITE, fieldCount, 1); WriteKey(policy, key); WriteOperation(Operation.Type.TOUCH); End(); } public void SetExists(Policy policy, Key key) { Begin(); int fieldCount = EstimateKeySize(policy, key); SizeBuffer(); WriteHeader(policy, Command.INFO1_READ | Command.INFO1_NOBINDATA, 0, fieldCount, 0); WriteKey(policy, key); End(); } public void SetRead(Policy policy, Key key) { Begin(); int fieldCount = EstimateKeySize(policy, key); SizeBuffer(); WriteHeader(policy, Command.INFO1_READ | Command.INFO1_GET_ALL, 0, fieldCount, 0); WriteKey(policy, key); End(); } public void SetRead(Policy policy, Key key, string[] binNames) { if (binNames != null) { Begin(); int fieldCount = EstimateKeySize(policy, key); foreach (string binName in binNames) { EstimateOperationSize(binName); } SizeBuffer(); WriteHeader(policy, Command.INFO1_READ, 0, fieldCount, binNames.Length); WriteKey(policy, key); foreach (string binName in binNames) { WriteOperation(binName, Operation.Type.READ); } End(); } else { SetRead(policy, key); } } public void SetReadHeader(Policy policy, Key key) { Begin(); int fieldCount = EstimateKeySize(policy, key); EstimateOperationSize((string)null); SizeBuffer(); WriteHeader(policy, Command.INFO1_READ | Command.INFO1_NOBINDATA, 0, fieldCount, 0); WriteKey(policy, key); End(); } public void SetOperate(WritePolicy policy, Key key, Operation[] operations) { Begin(); int fieldCount = EstimateKeySize(policy, key); int readAttr = 0; int writeAttr = 0; bool readBin = false; bool readHeader = false; foreach (Operation operation in operations) { switch (operation.type) { case Operation.Type.READ: readAttr |= Command.INFO1_READ; // Read all bins if no bin is specified. if (operation.binName == null) { readAttr |= Command.INFO1_GET_ALL; } readBin = true; break; case Operation.Type.READ_HEADER: readAttr |= Command.INFO1_READ; readHeader = true; break; default: writeAttr = Command.INFO2_WRITE; break; } EstimateOperationSize(operation); } SizeBuffer(); if (readHeader && !readBin) { readAttr |= Command.INFO1_NOBINDATA; } WriteHeader(policy, readAttr, writeAttr, fieldCount, operations.Length); WriteKey(policy, key); foreach (Operation operation in operations) { WriteOperation(operation); } End(); } public void SetUdf(WritePolicy policy, Key key, string packageName, string functionName, Value[] args) { Begin(); int fieldCount = EstimateKeySize(policy, key); byte[] argBytes = Packer.Pack(args); fieldCount += EstimateUdfSize(packageName, functionName, argBytes); SizeBuffer(); WriteHeader(policy, 0, Command.INFO2_WRITE, fieldCount, 0); WriteKey(policy, key); WriteField(packageName, FieldType.UDF_PACKAGE_NAME); WriteField(functionName, FieldType.UDF_FUNCTION); WriteField(argBytes, FieldType.UDF_ARGLIST); End(); } public void SetBatchRead(BatchPolicy policy, List<BatchRead> records, BatchNode batch) { // Estimate full row size int[] offsets = batch.offsets; int max = batch.offsetsSize; BatchRead prev = null; Begin(); dataOffset += FIELD_HEADER_SIZE + 5; for (int i = 0; i < max; i++) { BatchRead record = records[offsets[i]]; Key key = record.key; string[] binNames = record.binNames; dataOffset += key.digest.Length + 4; // Avoid relatively expensive full equality checks for performance reasons. // Use reference equality only in hope that common namespaces/bin names are set from // fixed variables. It's fine if equality not determined correctly because it just // results in more space used. The batch will still be correct. if (prev != null && prev.key.ns == key.ns && prev.binNames == binNames && prev.readAllBins == record.readAllBins) { // Can set repeat previous namespace/bin names to save space. dataOffset++; } else { // Estimate full header, namespace and bin names. dataOffset += ByteUtil.EstimateSizeUtf8(key.ns) + FIELD_HEADER_SIZE + 6; if (binNames != null) { foreach (string binName in binNames) { EstimateOperationSize(binName); } } prev = record; } } SizeBuffer(); WriteHeader(policy, Command.INFO1_READ | Command.INFO1_BATCH, 0, 1, 0); int fieldSizeOffset = dataOffset; WriteFieldHeader(0, FieldType.BATCH_INDEX); // Need to update size at end ByteUtil.IntToBytes((uint)max, dataBuffer, dataOffset); dataOffset += 4; dataBuffer[dataOffset++] = (policy.allowInline) ? (byte)1 : (byte)0; prev = null; for (int i = 0; i < max; i++) { int index = offsets[i]; ByteUtil.IntToBytes((uint)index, dataBuffer, dataOffset); dataOffset += 4; BatchRead record = records[index]; Key key = record.key; string[] binNames = record.binNames; byte[] digest = key.digest; Array.Copy(digest, 0, dataBuffer, dataOffset, digest.Length); dataOffset += digest.Length; // Avoid relatively expensive full equality checks for performance reasons. // Use reference equality only in hope that common namespaces/bin names are set from // fixed variables. It's fine if equality not determined correctly because it just // results in more space used. The batch will still be correct. if (prev != null && prev.key.ns == key.ns && prev.binNames == binNames && prev.readAllBins == record.readAllBins) { // Can set repeat previous namespace/bin names to save space. dataBuffer[dataOffset++] = 1; // repeat } else { // Write full header, namespace and bin names. dataBuffer[dataOffset++] = 0; // do not repeat if (binNames != null && binNames.Length != 0) { dataBuffer[dataOffset++] = (byte)Command.INFO1_READ; dataBuffer[dataOffset++] = 0; // pad dataBuffer[dataOffset++] = 0; // pad ByteUtil.ShortToBytes((ushort)binNames.Length, dataBuffer, dataOffset); dataOffset += 2; WriteField(key.ns, FieldType.NAMESPACE); foreach (string binName in binNames) { WriteOperation(binName, Operation.Type.READ); } } else { dataBuffer[dataOffset++] = (byte)(Command.INFO1_READ | (record.readAllBins ? Command.INFO1_GET_ALL : Command.INFO1_NOBINDATA)); dataBuffer[dataOffset++] = 0; // pad dataBuffer[dataOffset++] = 0; // pad ByteUtil.ShortToBytes(0, dataBuffer, dataOffset); dataOffset += 2; WriteField(key.ns, FieldType.NAMESPACE); } prev = record; } } // Write real field size. ByteUtil.IntToBytes((uint)(dataOffset - MSG_TOTAL_HEADER_SIZE - 4), dataBuffer, fieldSizeOffset); End(); } public void SetBatchRead(BatchPolicy policy, Key[] keys, BatchNode batch, string[] binNames, int readAttr) { // Estimate full row size int[] offsets = batch.offsets; int max = batch.offsetsSize; int rowSize = 30 + FIELD_HEADER_SIZE + 31; // Row's header(30) + max namespace(31). int operationCount = 0; if (binNames != null) { foreach (string binName in binNames) { EstimateOperationSize(binName); } rowSize += dataOffset; operationCount = binNames.Length; } // Estimate buffer size. Begin(); dataOffset += FIELD_HEADER_SIZE + 5; string prevNamespace = null; for (int i = 0; i < max; i++) { Key key = keys[offsets[i]]; // Try reference equality in hope that namespace for all keys is set from a fixed variable. if (key.ns == prevNamespace || (prevNamespace != null && prevNamespace.Equals(key.ns))) { // Can set repeat previous namespace/bin names to save space. dataOffset += 25; } else { // Must write full header and namespace/bin names. dataOffset += rowSize; prevNamespace = key.ns; } } SizeBuffer(); WriteHeader(policy, readAttr | Command.INFO1_BATCH, 0, 1, 0); int fieldSizeOffset = dataOffset; WriteFieldHeader(0, FieldType.BATCH_INDEX); // Need to update size at end ByteUtil.IntToBytes((uint)max, dataBuffer, dataOffset); dataOffset += 4; dataBuffer[dataOffset++] = (policy.allowInline) ? (byte)1 : (byte)0; prevNamespace = null; for (int i = 0; i < max; i++) { int index = offsets[i]; ByteUtil.IntToBytes((uint)index, dataBuffer, dataOffset); dataOffset += 4; Key key = keys[index]; byte[] digest = key.digest; Array.Copy(digest, 0, dataBuffer, dataOffset, digest.Length); dataOffset += digest.Length; // Try reference equality in hope that namespace for all keys is set from a fixed variable. if (key.ns == prevNamespace || (prevNamespace != null && prevNamespace.Equals(key.ns))) { // Can set repeat previous namespace/bin names to save space. dataBuffer[dataOffset++] = 1; // repeat } else { // Write full header, namespace and bin names. dataBuffer[dataOffset++] = 0; // do not repeat dataBuffer[dataOffset++] = (byte)readAttr; dataBuffer[dataOffset++] = 0; // pad dataBuffer[dataOffset++] = 0; // pad ByteUtil.ShortToBytes((ushort)operationCount, dataBuffer, dataOffset); dataOffset += 2; WriteField(key.ns, FieldType.NAMESPACE); if (binNames != null) { foreach (string binName in binNames) { WriteOperation(binName, Operation.Type.READ); } } prevNamespace = key.ns; } } // Write real field size. ByteUtil.IntToBytes((uint)(dataOffset - MSG_TOTAL_HEADER_SIZE - 4), dataBuffer, fieldSizeOffset); End(); } public void SetBatchReadDirect(Policy policy, Key[] keys, BatchNode.BatchNamespace batch, string[] binNames, int readAttr) { // Estimate buffer size Begin(); int byteSize = batch.offsetsSize * SyncCommand.DIGEST_SIZE; dataOffset += ByteUtil.EstimateSizeUtf8(batch.ns) + FIELD_HEADER_SIZE + byteSize + FIELD_HEADER_SIZE; if (binNames != null) { foreach (string binName in binNames) { EstimateOperationSize(binName); } } SizeBuffer(); int operationCount = (binNames == null)? 0 : binNames.Length; WriteHeader(policy, readAttr, 0, 2, operationCount); WriteField(batch.ns, FieldType.NAMESPACE); WriteFieldHeader(byteSize, FieldType.DIGEST_RIPE_ARRAY); int[] offsets = batch.offsets; int max = batch.offsetsSize; for (int i = 0; i < max; i++) { Key key = keys[offsets[i]]; byte[] digest = key.digest; Array.Copy(digest, 0, dataBuffer, dataOffset, digest.Length); dataOffset += digest.Length; } if (binNames != null) { foreach (string binName in binNames) { WriteOperation(binName, Operation.Type.READ); } } End(); } public void SetScan(ScanPolicy policy, string ns, string setName, string[] binNames, long taskId) { Begin(); int fieldCount = 0; if (ns != null) { dataOffset += ByteUtil.EstimateSizeUtf8(ns) + FIELD_HEADER_SIZE; fieldCount++; } if (setName != null) { dataOffset += ByteUtil.EstimateSizeUtf8(setName) + FIELD_HEADER_SIZE; fieldCount++; } // Estimate scan options size. dataOffset += 2 + FIELD_HEADER_SIZE; fieldCount++; // Estimate taskId size. dataOffset += 8 + FIELD_HEADER_SIZE; fieldCount++; if (binNames != null) { foreach (String binName in binNames) { EstimateOperationSize(binName); } } SizeBuffer(); byte readAttr = (byte)Command.INFO1_READ; if (!policy.includeBinData) { readAttr |= (byte)Command.INFO1_NOBINDATA; } int operationCount = (binNames == null) ? 0 : binNames.Length; WriteHeader(policy, readAttr, 0, fieldCount, operationCount); if (ns != null) { WriteField(ns, FieldType.NAMESPACE); } if (setName != null) { WriteField(setName, FieldType.TABLE); } WriteFieldHeader(2, FieldType.SCAN_OPTIONS); byte priority = (byte)policy.priority; priority <<= 4; if (policy.failOnClusterChange) { priority |= 0x08; } dataBuffer[dataOffset++] = priority; dataBuffer[dataOffset++] = (byte)policy.scanPercent; // Write taskId field WriteFieldHeader(8, FieldType.TRAN_ID); ByteUtil.LongToBytes((ulong)taskId, dataBuffer, dataOffset); dataOffset += 8; if (binNames != null) { foreach (String binName in binNames) { WriteOperation(binName, Operation.Type.READ); } } End(); } protected internal void SetQuery(Policy policy, Statement statement, bool write) { byte[] functionArgBuffer = null; int fieldCount = 0; int filterSize = 0; int binNameSize = 0; Begin(); if (statement.ns != null) { dataOffset += ByteUtil.EstimateSizeUtf8(statement.ns) + FIELD_HEADER_SIZE; fieldCount++; } if (statement.indexName != null) { dataOffset += ByteUtil.EstimateSizeUtf8(statement.indexName) + FIELD_HEADER_SIZE; fieldCount++; } if (statement.setName != null) { dataOffset += ByteUtil.EstimateSizeUtf8(statement.setName) + FIELD_HEADER_SIZE; fieldCount++; } // Allocate space for TaskId field. dataOffset += 8 + FIELD_HEADER_SIZE; fieldCount++; if (statement.filters != null) { if (statement.filters.Length >= 1) { IndexCollectionType type = statement.filters[0].CollectionType; if (type != IndexCollectionType.DEFAULT) { dataOffset += FIELD_HEADER_SIZE + 1; fieldCount++; } } dataOffset += FIELD_HEADER_SIZE; filterSize++; // num filters foreach (Filter filter in statement.filters) { filterSize += filter.EstimateSize(); } dataOffset += filterSize; fieldCount++; // Query bin names are specified as a field (Scan bin names are specified later as operations) if (statement.binNames != null) { dataOffset += FIELD_HEADER_SIZE; binNameSize++; // num bin names foreach (string binName in statement.binNames) { binNameSize += ByteUtil.EstimateSizeUtf8(binName) + 1; } dataOffset += binNameSize; fieldCount++; } } else { // Calling query with no filters is more efficiently handled by a primary index scan. // Estimate scan options size. dataOffset += 2 + FIELD_HEADER_SIZE; fieldCount++; } if (statement.functionName != null) { dataOffset += FIELD_HEADER_SIZE + 1; // udf type dataOffset += ByteUtil.EstimateSizeUtf8(statement.packageName) + FIELD_HEADER_SIZE; dataOffset += ByteUtil.EstimateSizeUtf8(statement.functionName) + FIELD_HEADER_SIZE; if (statement.functionArgs.Length > 0) { functionArgBuffer = Packer.Pack(statement.functionArgs); } else { functionArgBuffer = new byte[0]; } dataOffset += FIELD_HEADER_SIZE + functionArgBuffer.Length; fieldCount += 4; } if (statement.filters == null) { if (statement.binNames != null) { foreach (string binName in statement.binNames) { EstimateOperationSize(binName); } } } SizeBuffer(); int operationCount = (statement.filters == null && statement.binNames != null) ? statement.binNames.Length : 0; if (write) { WriteHeader((WritePolicy)policy, Command.INFO1_READ, Command.INFO2_WRITE, fieldCount, operationCount); } else { WriteHeader(policy, Command.INFO1_READ, 0, fieldCount, operationCount); } if (statement.ns != null) { WriteField(statement.ns, FieldType.NAMESPACE); } if (statement.indexName != null) { WriteField(statement.indexName, FieldType.INDEX_NAME); } if (statement.setName != null) { WriteField(statement.setName, FieldType.TABLE); } // Write taskId field WriteFieldHeader(8, FieldType.TRAN_ID); ByteUtil.LongToBytes((ulong)statement.taskId, dataBuffer, dataOffset); dataOffset += 8; if (statement.filters != null) { if (statement.filters.Length >= 1) { IndexCollectionType type = statement.filters[0].CollectionType; if (type != IndexCollectionType.DEFAULT) { WriteFieldHeader(1, FieldType.INDEX_TYPE); dataBuffer[dataOffset++] = (byte)type; } } WriteFieldHeader(filterSize, FieldType.INDEX_RANGE); dataBuffer[dataOffset++] = (byte)statement.filters.Length; foreach (Filter filter in statement.filters) { dataOffset = filter.Write(dataBuffer, dataOffset); } // Query bin names are specified as a field (Scan bin names are specified later as operations) if (statement.binNames != null) { WriteFieldHeader(binNameSize, FieldType.QUERY_BINLIST); dataBuffer[dataOffset++] = (byte)statement.binNames.Length; foreach (string binName in statement.binNames) { int len = ByteUtil.StringToUtf8(binName, dataBuffer, dataOffset + 1); dataBuffer[dataOffset] = (byte)len; dataOffset += len + 1; } } } else { // Calling query with no filters is more efficiently handled by a primary index scan. WriteFieldHeader(2, FieldType.SCAN_OPTIONS); byte priority = (byte)policy.priority; priority <<= 4; dataBuffer[dataOffset++] = priority; dataBuffer[dataOffset++] = (byte)100; } if (statement.functionName != null) { WriteFieldHeader(1, FieldType.UDF_OP); dataBuffer[dataOffset++] = (statement.returnData) ? (byte)1 : (byte)2; WriteField(statement.packageName, FieldType.UDF_PACKAGE_NAME); WriteField(statement.functionName, FieldType.UDF_FUNCTION); WriteField(functionArgBuffer, FieldType.UDF_ARGLIST); } // Scan bin names are specified after all fields. if (statement.filters == null) { if (statement.binNames != null) { foreach (string binName in statement.binNames) { WriteOperation(binName, Operation.Type.READ); } } } End(); } private int EstimateKeySize(Policy policy, Key key) { int fieldCount = 0; if (key.ns != null) { dataOffset += ByteUtil.EstimateSizeUtf8(key.ns) + FIELD_HEADER_SIZE; fieldCount++; } if (key.setName != null) { dataOffset += ByteUtil.EstimateSizeUtf8(key.setName) + FIELD_HEADER_SIZE; fieldCount++; } dataOffset += key.digest.Length + FIELD_HEADER_SIZE; fieldCount++; if (policy.sendKey) { dataOffset += key.userKey.EstimateSize() + FIELD_HEADER_SIZE + 1; fieldCount++; } return fieldCount; } private int EstimateUdfSize(string packageName, string functionName, byte[] bytes) { dataOffset += ByteUtil.EstimateSizeUtf8(packageName) + FIELD_HEADER_SIZE; dataOffset += ByteUtil.EstimateSizeUtf8(functionName) + FIELD_HEADER_SIZE; dataOffset += bytes.Length + FIELD_HEADER_SIZE; return 3; } private void EstimateOperationSize(Bin bin) { dataOffset += ByteUtil.EstimateSizeUtf8(bin.name) + OPERATION_HEADER_SIZE; dataOffset += bin.value.EstimateSize(); } private void EstimateOperationSize(Operation operation) { dataOffset += ByteUtil.EstimateSizeUtf8(operation.binName) + OPERATION_HEADER_SIZE; dataOffset += operation.binValue.EstimateSize(); } protected void EstimateOperationSize(string binName) { dataOffset += ByteUtil.EstimateSizeUtf8(binName) + OPERATION_HEADER_SIZE; } private void EstimateOperationSize() { dataOffset += OPERATION_HEADER_SIZE; } /// <summary> /// Header write for write operations. /// </summary> protected internal void WriteHeader(WritePolicy policy, int readAttr, int writeAttr, int fieldCount, int operationCount) { // Set flags. int generation = 0; int infoAttr = 0; switch (policy.recordExistsAction) { case RecordExistsAction.UPDATE: break; case RecordExistsAction.UPDATE_ONLY: infoAttr |= Command.INFO3_UPDATE_ONLY; break; case RecordExistsAction.REPLACE: infoAttr |= Command.INFO3_CREATE_OR_REPLACE; break; case RecordExistsAction.REPLACE_ONLY: infoAttr |= Command.INFO3_REPLACE_ONLY; break; case RecordExistsAction.CREATE_ONLY: writeAttr |= Command.INFO2_CREATE_ONLY; break; } switch (policy.generationPolicy) { case GenerationPolicy.NONE: break; case GenerationPolicy.EXPECT_GEN_EQUAL: generation = policy.generation; writeAttr |= Command.INFO2_GENERATION; break; case GenerationPolicy.EXPECT_GEN_GT: generation = policy.generation; writeAttr |= Command.INFO2_GENERATION_GT; break; } if (policy.commitLevel == CommitLevel.COMMIT_MASTER) { infoAttr |= Command.INFO3_COMMIT_MASTER; } if (policy.consistencyLevel == ConsistencyLevel.CONSISTENCY_ALL) { readAttr |= Command.INFO1_CONSISTENCY_ALL; } // Write all header data except total size which must be written last. dataBuffer[8] = MSG_REMAINING_HEADER_SIZE; // Message header length. dataBuffer[9] = (byte)readAttr; dataBuffer[10] = (byte)writeAttr; dataBuffer[11] = (byte)infoAttr; dataBuffer[12] = 0; // unused dataBuffer[13] = 0; // clear the result code ByteUtil.IntToBytes((uint)generation, dataBuffer, 14); ByteUtil.IntToBytes((uint)policy.expiration, dataBuffer, 18); // Initialize timeout. It will be written later. dataBuffer[22] = 0; dataBuffer[23] = 0; dataBuffer[24] = 0; dataBuffer[25] = 0; ByteUtil.ShortToBytes((ushort)fieldCount, dataBuffer, 26); ByteUtil.ShortToBytes((ushort)operationCount, dataBuffer, 28); dataOffset = MSG_TOTAL_HEADER_SIZE; } /// <summary> /// Generic header write. /// </summary> protected internal void WriteHeader(Policy policy, int readAttr, int writeAttr, int fieldCount, int operationCount) { if (policy.consistencyLevel == ConsistencyLevel.CONSISTENCY_ALL) { readAttr |= Command.INFO1_CONSISTENCY_ALL; } // Write all header data except total size which must be written last. dataBuffer[8] = MSG_REMAINING_HEADER_SIZE; // Message header length. dataBuffer[9] = (byte)readAttr; dataBuffer[10] = (byte)writeAttr; for (int i = 11; i < 26; i++) { dataBuffer[i] = 0; } ByteUtil.ShortToBytes((ushort)fieldCount, dataBuffer, 26); ByteUtil.ShortToBytes((ushort)operationCount, dataBuffer, 28); dataOffset = MSG_TOTAL_HEADER_SIZE; } private void WriteKey(Policy policy, Key key) { // Write key into buffer. if (key.ns != null) { WriteField(key.ns, FieldType.NAMESPACE); } if (key.setName != null) { WriteField(key.setName, FieldType.TABLE); } WriteField(key.digest, FieldType.DIGEST_RIPE); if (policy.sendKey) { WriteField(key.userKey, FieldType.KEY); } } private void WriteOperation(Bin bin, Operation.Type operationType) { int nameLength = ByteUtil.StringToUtf8(bin.name, dataBuffer, dataOffset + OPERATION_HEADER_SIZE); int valueLength = bin.value.Write(dataBuffer, dataOffset + OPERATION_HEADER_SIZE + nameLength); ByteUtil.IntToBytes((uint)(nameLength + valueLength + 4), dataBuffer, dataOffset); dataOffset += 4; dataBuffer[dataOffset++] = Operation.GetProtocolType(operationType); dataBuffer[dataOffset++] = (byte) bin.value.Type; dataBuffer[dataOffset++] = (byte) 0; dataBuffer[dataOffset++] = (byte) nameLength; dataOffset += nameLength + valueLength; } private void WriteOperation(Operation operation) { int nameLength = ByteUtil.StringToUtf8(operation.binName, dataBuffer, dataOffset + OPERATION_HEADER_SIZE); int valueLength = operation.binValue.Write(dataBuffer, dataOffset + OPERATION_HEADER_SIZE + nameLength); ByteUtil.IntToBytes((uint)(nameLength + valueLength + 4), dataBuffer, dataOffset); dataOffset += 4; dataBuffer[dataOffset++] = Operation.GetProtocolType(operation.type); dataBuffer[dataOffset++] = (byte) operation.binValue.Type; dataBuffer[dataOffset++] = (byte) 0; dataBuffer[dataOffset++] = (byte) nameLength; dataOffset += nameLength + valueLength; } protected void WriteOperation(string name, Operation.Type operationType) { int nameLength = ByteUtil.StringToUtf8(name, dataBuffer, dataOffset + OPERATION_HEADER_SIZE); ByteUtil.IntToBytes((uint)(nameLength + 4), dataBuffer, dataOffset); dataOffset += 4; dataBuffer[dataOffset++] = Operation.GetProtocolType(operationType); dataBuffer[dataOffset++] = (byte) 0; dataBuffer[dataOffset++] = (byte) 0; dataBuffer[dataOffset++] = (byte) nameLength; dataOffset += nameLength; } private void WriteOperation(Operation.Type operationType) { ByteUtil.IntToBytes(4, dataBuffer, dataOffset); dataOffset += 4; dataBuffer[dataOffset++] = Operation.GetProtocolType(operationType); dataBuffer[dataOffset++] = 0; dataBuffer[dataOffset++] = 0; dataBuffer[dataOffset++] = 0; } public void WriteField(Value value, int type) { int offset = dataOffset + FIELD_HEADER_SIZE; dataBuffer[offset++] = (byte)value.Type; int len = value.Write(dataBuffer, offset) + 1; WriteFieldHeader(len, type); dataOffset += len; } public void WriteField(string str, int type) { int len = ByteUtil.StringToUtf8(str, dataBuffer, dataOffset + FIELD_HEADER_SIZE); WriteFieldHeader(len, type); dataOffset += len; } public void WriteField(byte[] bytes, int type) { Array.Copy(bytes, 0, dataBuffer, dataOffset + FIELD_HEADER_SIZE, bytes.Length); WriteFieldHeader(bytes.Length, type); dataOffset += bytes.Length; } public void WriteFieldHeader(int size, int type) { ByteUtil.IntToBytes((uint)size+1, dataBuffer, dataOffset); dataOffset += 4; dataBuffer[dataOffset++] = (byte)type; } protected internal void Begin() { dataOffset = MSG_TOTAL_HEADER_SIZE; } protected internal void End() { // Write total size of message which is the current offset. ulong size = ((ulong)dataOffset - 8) | (CL_MSG_VERSION << 56) | (AS_MSG_TYPE << 48); ByteUtil.LongToBytes(size, dataBuffer, 0); } protected internal abstract Policy GetPolicy(); protected internal abstract void WriteBuffer(); protected internal abstract void SizeBuffer(); } }
/******************************************************************************* * Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; namespace Amazon.EC2.Model { /// <summary> /// Bundle Task /// </summary> [XmlRootAttribute(IsNullable = false)] public class BundleTask { private string instanceIdField; private string bundleIdField; private string bundleStateField; private string startTimeField; private string updateTimeField; private Storage storageField; private string progressField; private BundleTaskError bundleTaskErrorField; /// <summary> /// The ID of the instance associated with this bundle task. /// </summary> [XmlElementAttribute(ElementName = "InstanceId")] public string InstanceId { get { return this.instanceIdField; } set { this.instanceIdField = value; } } /// <summary> /// Sets the ID of the instance associated with this bundle task. /// </summary> /// <param name="instanceId">Instance associated with this bundle task.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public BundleTask WithInstanceId(string instanceId) { this.instanceIdField = instanceId; return this; } /// <summary> /// Checks if InstanceId property is set /// </summary> /// <returns>true if InstanceId property is set</returns> public bool IsSetInstanceId() { return this.instanceIdField != null; } /// <summary> /// The ID for this bundle task. /// </summary> [XmlElementAttribute(ElementName = "BundleId")] public string BundleId { get { return this.bundleIdField; } set { this.bundleIdField = value; } } /// <summary> /// Sets the ID for this bundle task. /// </summary> /// <param name="bundleId">Identifier for this task.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public BundleTask WithBundleId(string bundleId) { this.bundleIdField = bundleId; return this; } /// <summary> /// Checks if BundleId property is set /// </summary> /// <returns>true if BundleId property is set</returns> public bool IsSetBundleId() { return this.bundleIdField != null; } /// <summary> /// The state of the task. /// /// Valid Values: pending | waiting-for-shutdown | bundling | storing | cancelling | complete | failed /// </summary> [XmlElementAttribute(ElementName = "BundleState")] public string BundleState { get { return this.bundleStateField; } set { this.bundleStateField = value; } } /// <summary> /// Sets the state of the task. /// </summary> /// <param name="bundleState">The state of the task.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public BundleTask WithBundleState(string bundleState) { this.bundleStateField = bundleState; return this; } /// <summary> /// Checks if BundleState property is set /// </summary> /// <returns>true if BundleState property is set</returns> public bool IsSetBundleState() { return this.bundleStateField != null; } /// <summary> /// The time this task started. /// </summary> [XmlElementAttribute(ElementName = "StartTime")] public string StartTime { get { return this.startTimeField; } set { this.startTimeField = value; } } /// <summary> /// Sets the time this task started. /// </summary> /// <param name="startTime">The time this task started.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public BundleTask WithStartTime(string startTime) { this.startTimeField = startTime; return this; } /// <summary> /// Checks if StartTime property is set /// </summary> /// <returns>true if StartTime property is set</returns> public bool IsSetStartTime() { return this.startTimeField != null; } /// <summary> /// The time of the most recent update for the task. /// </summary> [XmlElementAttribute(ElementName = "UpdateTime")] public string UpdateTime { get { return this.updateTimeField; } set { this.updateTimeField = value; } } /// <summary> /// Sets the time of the most recent update for the task. /// </summary> /// <param name="updateTime">The time of the most recent update for the /// task.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public BundleTask WithUpdateTime(string updateTime) { this.updateTimeField = updateTime; return this; } /// <summary> /// Checks if UpdateTime property is set /// </summary> /// <returns>true if UpdateTime property is set</returns> public bool IsSetUpdateTime() { return this.updateTimeField != null; } /// <summary> /// The Amazon S3 storage locations. /// </summary> [XmlElementAttribute(ElementName = "Storage")] public Storage Storage { get { return this.storageField; } set { this.storageField = value; } } /// <summary> /// Sets the Amazon S3 storage locations. /// </summary> /// <param name="storage">Amazon S3 storage locations.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public BundleTask WithStorage(Storage storage) { this.storageField = storage; return this; } /// <summary> /// Checks if Storage property is set /// </summary> /// <returns>true if Storage property is set</returns> public bool IsSetStorage() { return this.storageField != null; } /// <summary> /// The level of task completion, as a percent (for example, 20%). /// </summary> [XmlElementAttribute(ElementName = "Progress")] public string Progress { get { return this.progressField; } set { this.progressField = value; } } /// <summary> /// Sets the level of task completion, as a percent (for example, 20%). /// </summary> /// <param name="progress">The level of task completion, in percent (e.g., 20%).</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public BundleTask WithProgress(string progress) { this.progressField = progress; return this; } /// <summary> /// Checks if Progress property is set /// </summary> /// <returns>true if Progress property is set</returns> public bool IsSetProgress() { return this.progressField != null; } /// <summary> /// If the task fails, a description of the error. /// </summary> [XmlElementAttribute(ElementName = "BundleTaskError")] public BundleTaskError BundleTaskError { get { return this.bundleTaskErrorField; } set { this.bundleTaskErrorField = value; } } /// <summary> /// Sets the description of an error if the task fails /// </summary> /// <param name="bundleTaskError">If the task fails, a description of the error.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public BundleTask WithBundleTaskError(BundleTaskError bundleTaskError) { this.bundleTaskErrorField = bundleTaskError; return this; } /// <summary> /// Checks if BundleTaskError property is set /// </summary> /// <returns>true if BundleTaskError property is set</returns> public bool IsSetBundleTaskError() { return this.bundleTaskErrorField != null; } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Collections.ObjectModel; using System.Management.Automation; using System.Net; using System.IO; using System.Text; using System.Collections; using System.Globalization; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; #if !CORECLR using mshtml; #endif using Microsoft.Win32; namespace Microsoft.PowerShell.Commands { /// <summary> /// Base class for Invoke-RestMethod and Invoke-WebRequest commands. /// </summary> public abstract partial class WebRequestPSCmdlet : PSCmdlet { #region Virtual Properties #region URI /// <summary> /// gets or sets the parameter UseBasicParsing /// </summary> [Parameter] public virtual SwitchParameter UseBasicParsing { get; set; } /// <summary> /// gets or sets the Uri property /// </summary> [Parameter(Position = 0, Mandatory = true)] [ValidateNotNullOrEmpty] public virtual Uri Uri { get; set; } #endregion #region Session /// <summary> /// gets or sets the Session property /// </summary> [Parameter] public virtual WebRequestSession WebSession { get; set; } /// <summary> /// gets or sets the SessionVariable property /// </summary> [Parameter] [Alias("SV")] public virtual string SessionVariable { get; set; } #endregion #region Authorization and Credentials /// <summary> /// gets or sets the Credential property /// </summary> [Parameter] [Credential] public virtual PSCredential Credential { get; set; } /// <summary> /// gets or sets the UseDefaultCredentials property /// </summary> [Parameter] public virtual SwitchParameter UseDefaultCredentials { get; set; } /// <summary> /// gets or sets the CertificateThumbprint property /// </summary> [Parameter] [ValidateNotNullOrEmpty] public virtual string CertificateThumbprint { get; set; } /// <summary> /// gets or sets the Certificate property /// </summary> [Parameter] [ValidateNotNull] public virtual X509Certificate Certificate { get; set; } #endregion #region Headers /// <summary> /// gets or sets the UserAgent property /// </summary> [Parameter] public virtual string UserAgent { get; set; } /// <summary> /// gets or sets the DisableKeepAlive property /// </summary> [Parameter] public virtual SwitchParameter DisableKeepAlive { get; set; } /// <summary> /// gets or sets the TimeOut property /// </summary> [Parameter] [ValidateRange(0, Int32.MaxValue)] public virtual int TimeoutSec { get; set; } /// <summary> /// gets or sets the Headers property /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [Parameter] public virtual IDictionary Headers { get; set; } #endregion #region Redirect /// <summary> /// gets or sets the RedirectMax property /// </summary> [Parameter] [ValidateRange(0, Int32.MaxValue)] public virtual int MaximumRedirection { get { return _maximumRedirection; } set { _maximumRedirection = value; } } private int _maximumRedirection = -1; #endregion #region Method /// <summary> /// gets or sets the Method property /// </summary> [Parameter] public virtual WebRequestMethod Method { get { return _method; } set { _method = value; } } private WebRequestMethod _method = WebRequestMethod.Default; #endregion #region Proxy /// <summary> /// gets or sets the Proxy property /// </summary> [Parameter] public virtual Uri Proxy { get; set; } /// <summary> /// gets or sets the ProxyCredential property /// </summary> [Parameter] [Credential] public virtual PSCredential ProxyCredential { get; set; } /// <summary> /// gets or sets the ProxyUseDefaultCredentials property /// </summary> [Parameter] public virtual SwitchParameter ProxyUseDefaultCredentials { get; set; } #endregion #region Input /// <summary> /// gets or sets the Body property /// </summary> [Parameter(ValueFromPipeline = true)] public virtual object Body { get; set; } /// <summary> /// gets or sets the ContentType property /// </summary> [Parameter] public virtual string ContentType { get; set; } /// <summary> /// gets or sets the TransferEncoding property /// </summary> [Parameter] [ValidateSet("chunked", "compress", "deflate", "gzip", "identity", IgnoreCase = true)] public virtual string TransferEncoding { get; set; } /// <summary> /// gets or sets the InFile property /// </summary> [Parameter] public virtual string InFile { get; set; } /// <summary> /// keep the original file path after the resolved provider path is /// assigned to InFile /// </summary> private string _originalFilePath; #endregion #region Output /// <summary> /// gets or sets the OutFile property /// </summary> [Parameter] public virtual string OutFile { get; set; } /// <summary> /// gets or sets the PassThrough property /// </summary> [Parameter] public virtual SwitchParameter PassThru { get; set; } #endregion #endregion Virtual Properties #region Virtual Methods internal virtual void ValidateParameters() { // sessions if ((null != WebSession) && (null != SessionVariable)) { ErrorRecord error = GetValidationError(WebCmdletStrings.SessionConflict, "WebCmdletSessionConflictException"); ThrowTerminatingError(error); } // credentials if (UseDefaultCredentials && (null != Credential)) { ErrorRecord error = GetValidationError(WebCmdletStrings.CredentialConflict, "WebCmdletCredentialConflictException"); ThrowTerminatingError(error); } // Proxy server if (ProxyUseDefaultCredentials && (null != ProxyCredential)) { ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyCredentialConflict, "WebCmdletProxyCredentialConflictException"); ThrowTerminatingError(error); } else if ((null == Proxy) && ((null != ProxyCredential) || ProxyUseDefaultCredentials)) { ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyUriNotSupplied, "WebCmdletProxyUriNotSuppliedException"); ThrowTerminatingError(error); } // request body content if ((null != Body) && (null != InFile)) { ErrorRecord error = GetValidationError(WebCmdletStrings.BodyConflict, "WebCmdletBodyConflictException"); ThrowTerminatingError(error); } // validate InFile path if (InFile != null) { ProviderInfo provider = null; ErrorRecord errorRecord = null; try { Collection<string> providerPaths = GetResolvedProviderPathFromPSPath(InFile, out provider); if (!provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase)) { errorRecord = GetValidationError(WebCmdletStrings.NotFilesystemPath, "WebCmdletInFileNotFilesystemPathException", InFile); } else { if (providerPaths.Count > 1) { errorRecord = GetValidationError(WebCmdletStrings.MultiplePathsResolved, "WebCmdletInFileMultiplePathsResolvedException", InFile); } else if (providerPaths.Count == 0) { errorRecord = GetValidationError(WebCmdletStrings.NoPathResolved, "WebCmdletInFileNoPathResolvedException", InFile); } else { if (Directory.Exists(providerPaths[0])) { errorRecord = GetValidationError(WebCmdletStrings.DirecotryPathSpecified, "WebCmdletInFileNotFilePathException", InFile); } _originalFilePath = InFile; InFile = providerPaths[0]; } } } catch (ItemNotFoundException pathNotFound) { errorRecord = new ErrorRecord(pathNotFound.ErrorRecord, pathNotFound); } catch (ProviderNotFoundException providerNotFound) { errorRecord = new ErrorRecord(providerNotFound.ErrorRecord, providerNotFound); } catch (System.Management.Automation.DriveNotFoundException driveNotFound) { errorRecord = new ErrorRecord(driveNotFound.ErrorRecord, driveNotFound); } if (errorRecord != null) { ThrowTerminatingError(errorRecord); } } // output ?? if (PassThru && (OutFile == null)) { ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing, "WebCmdletOutFileMissingException"); ThrowTerminatingError(error); } } internal virtual void PrepareSession() { // make sure we have a valid WebRequestSession object to work with if (null == WebSession) { WebSession = new WebRequestSession(); } if (null != SessionVariable) { // save the session back to the PS environment if requested PSVariableIntrinsics vi = SessionState.PSVariable; vi.Set(SessionVariable, WebSession); } // // handle credentials // if (null != Credential) { // get the relevant NetworkCredential NetworkCredential netCred = Credential.GetNetworkCredential(); WebSession.Credentials = netCred; // supplying a credential overrides the UseDefaultCredentials setting WebSession.UseDefaultCredentials = false; } else if (UseDefaultCredentials) { WebSession.UseDefaultCredentials = true; } if (null != CertificateThumbprint) { X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates; X509Certificate2Collection tbCollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByThumbprint, CertificateThumbprint, false); if (tbCollection.Count == 0) { CryptographicException ex = new CryptographicException(WebCmdletStrings.ThumbprintNotFound); throw ex; } foreach (X509Certificate2 tbCert in tbCollection) { X509Certificate certificate = (X509Certificate)tbCert; WebSession.AddCertificate(certificate); } } if (null != Certificate) { WebSession.AddCertificate(Certificate); } // // handle the user agent // if (null != UserAgent) { // store the UserAgent string WebSession.UserAgent = UserAgent; } if (null != Proxy) { WebProxy webProxy = new WebProxy(Proxy); webProxy.BypassProxyOnLocal = false; if (null != ProxyCredential) { webProxy.Credentials = ProxyCredential.GetNetworkCredential(); } else if (ProxyUseDefaultCredentials) { // If both ProxyCredential and ProxyUseDefaultCredentials are passed, // UseDefaultCredentials will overwrite the supplied credentials. webProxy.UseDefaultCredentials = true; } WebSession.Proxy = webProxy; } if (-1 < MaximumRedirection) { WebSession.MaximumRedirection = MaximumRedirection; } // store the other supplied headers if (null != Headers) { foreach (string key in Headers.Keys) { // add the header value (or overwrite it if already present) WebSession.Headers[key] = Headers[key].ToString(); } } } #endregion Virtual Methods #region Helper Properties internal string QualifiedOutFile { get { return (QualifyFilePath(OutFile)); } } internal bool ShouldSaveToOutFile { get { return (!string.IsNullOrEmpty(OutFile)); } } internal bool ShouldWriteToPipeline { get { return (!ShouldSaveToOutFile || PassThru); } } #endregion Helper Properties #region Helper Methods /// <summary> /// Verifies that Internet Explorer is available, and that its first-run /// configuration is complete. /// </summary> /// <param name="checkComObject">True if we should try to access IE's COM object. Not /// needed if an HtmlDocument will be created shortly.</param> protected bool VerifyInternetExplorerAvailable(bool checkComObject) { // TODO: Remove this code once the dependency on mshtml has been resolved. #if CORECLR return false; #else bool isInternetExplorerConfigurationComplete = false; // Check for IE for both PS Full and PS Core on windows. // The registry key DisableFirstRunCustomize can exits at one of the following path. // IE uses the same descending order (as mentioned) to check for the presence of this key. // If the value of DisableFirstRunCustomize key is set to greater than zero then Run first // is disabled. string[] disableFirstRunCustomizePaths = new string[] { @"HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Internet Explorer\Main", @"HKEY_CURRENT_USER\Software\Policies\Microsoft\Internet Explorer\Main", @"HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main", @"HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Explorer\Main" }; foreach (string currentRegPath in disableFirstRunCustomizePaths) { object val = Registry.GetValue(currentRegPath, "DisableFirstRunCustomize", string.Empty); if (val != null && !string.Empty.Equals(val) && Convert.ToInt32(val, CultureInfo.InvariantCulture) > 0) { isInternetExplorerConfigurationComplete = true; break; } } if (!isInternetExplorerConfigurationComplete) { // Verify that if IE is installed, it has been through the RunOnce check. // Otherwise, the call will hang waiting for users to go through First Run // personalization. using (RegistryKey key = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Internet Explorer\\Main")) { if (key != null) { foreach (string setting in key.GetValueNames()) { if (setting.IndexOf("RunOnce", StringComparison.OrdinalIgnoreCase) > -1) { isInternetExplorerConfigurationComplete = true; break; } } } } } if (isInternetExplorerConfigurationComplete && checkComObject) { try { IHTMLDocument2 ieCheck = (IHTMLDocument2)new HTMLDocument(); System.Runtime.InteropServices.Marshal.ReleaseComObject(ieCheck); } catch (System.Runtime.InteropServices.COMException) { isInternetExplorerConfigurationComplete = false; } } // Throw exception in PS Full only if (!isInternetExplorerConfigurationComplete) throw new NotSupportedException(WebCmdletStrings.IEDomNotSupported); return isInternetExplorerConfigurationComplete; #endif } private Uri PrepareUri(Uri uri) { uri = CheckProtocol(uri); // before creating the web request, // preprocess Body if content is a dictionary and method is GET (set as query) IDictionary bodyAsDictionary; LanguagePrimitives.TryConvertTo<IDictionary>(Body, out bodyAsDictionary); if ((null != bodyAsDictionary) && (Method == WebRequestMethod.Default || Method == WebRequestMethod.Get)) { UriBuilder uriBuilder = new UriBuilder(uri); if (uriBuilder.Query != null && uriBuilder.Query.Length > 1) { uriBuilder.Query = uriBuilder.Query.Substring(1) + "&" + FormatDictionary(bodyAsDictionary); } else { uriBuilder.Query = FormatDictionary(bodyAsDictionary); } uri = uriBuilder.Uri; // set body to null to prevent later FillRequestStream Body = null; } return uri; } private Uri CheckProtocol(Uri uri) { if (null == uri) { throw new ArgumentNullException("uri"); } if (!uri.IsAbsoluteUri) { uri = new Uri("http://" + uri.OriginalString); } return (uri); } private string QualifyFilePath(string path) { string resolvedFilePath = PathUtils.ResolveFilePath(path, this, false); return resolvedFilePath; } private string FormatDictionary(IDictionary content) { if (content == null) throw new ArgumentNullException("content"); StringBuilder bodyBuilder = new StringBuilder(); foreach (string key in content.Keys) { if (0 < bodyBuilder.Length) { bodyBuilder.Append("&"); } object value = content[key]; // URLEncode the key and value string encodedKey = WebUtility.UrlEncode(key); string encodedValue = String.Empty; if (null != value) { encodedValue = WebUtility.UrlEncode(value.ToString()); } bodyBuilder.AppendFormat("{0}={1}", encodedKey, encodedValue); } return bodyBuilder.ToString(); } private ErrorRecord GetValidationError(string msg, string errorId) { var ex = new ValidationMetadataException(msg); var error = new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this); return (error); } private ErrorRecord GetValidationError(string msg, string errorId, params object[] args) { msg = string.Format(CultureInfo.InvariantCulture, msg, args); var ex = new ValidationMetadataException(msg); var error = new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this); return (error); } #endregion Helper Methods } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Compute.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedRegionBackendServicesClientTest { [xunit::FactAttribute] public void GetRequestObject() { moq::Mock<RegionBackendServices.RegionBackendServicesClient> mockGrpcClient = new moq::Mock<RegionBackendServices.RegionBackendServicesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegionBackendServiceRequest request = new GetRegionBackendServiceRequest { Region = "regionedb20d96", Project = "projectaa6ff846", BackendService = "backend_serviceed490d45", }; BackendService expectedResponse = new BackendService { Id = 11672635353343658936UL, Iap = new BackendServiceIAP(), ConsistentHash = new ConsistentHashLoadBalancerSettings(), Kind = "kindf7aa39d9", Name = "name1c9368b0", Port = -78310000, CustomRequestHeaders = { "custom_request_headers3532c035", }, CreationTimestamp = "creation_timestamp235e59a1", EdgeSecurityPolicy = "edge_security_policy85c5b8f4", PortName = "port_namebaaa4cd4", MaxStreamDuration = new Duration(), TimeoutSec = -1529270667, Protocol = "protocola08b7881", FailoverPolicy = new BackendServiceFailoverPolicy(), LocalityLbPolicy = "locality_lb_policyc8722098", Region = "regionedb20d96", ConnectionTrackingPolicy = new BackendServiceConnectionTrackingPolicy(), SecurityPolicy = "security_policy76596315", CdnPolicy = new BackendServiceCdnPolicy(), Network = "networkd22ce091", Fingerprint = "fingerprint009e6052", EnableCDN = false, LogConfig = new BackendServiceLogConfig(), OutlierDetection = new OutlierDetection(), LoadBalancingScheme = "load_balancing_scheme21346104", AffinityCookieTtlSec = -328985636, CustomResponseHeaders = { "custom_response_headersda5d431e", }, CircuitBreakers = new CircuitBreakers(), Description = "description2cf9da67", HealthChecks = { "health_checksedb1f3f8", }, Subsetting = new Subsetting(), SelfLink = "self_link7e87f12d", ConnectionDraining = new ConnectionDraining(), SessionAffinity = "session_affinitye702dadf", SecuritySettings = new SecuritySettings(), Backends = { new Backend(), }, }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RegionBackendServicesClient client = new RegionBackendServicesClientImpl(mockGrpcClient.Object, null); BackendService response = client.Get(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRequestObjectAsync() { moq::Mock<RegionBackendServices.RegionBackendServicesClient> mockGrpcClient = new moq::Mock<RegionBackendServices.RegionBackendServicesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegionBackendServiceRequest request = new GetRegionBackendServiceRequest { Region = "regionedb20d96", Project = "projectaa6ff846", BackendService = "backend_serviceed490d45", }; BackendService expectedResponse = new BackendService { Id = 11672635353343658936UL, Iap = new BackendServiceIAP(), ConsistentHash = new ConsistentHashLoadBalancerSettings(), Kind = "kindf7aa39d9", Name = "name1c9368b0", Port = -78310000, CustomRequestHeaders = { "custom_request_headers3532c035", }, CreationTimestamp = "creation_timestamp235e59a1", EdgeSecurityPolicy = "edge_security_policy85c5b8f4", PortName = "port_namebaaa4cd4", MaxStreamDuration = new Duration(), TimeoutSec = -1529270667, Protocol = "protocola08b7881", FailoverPolicy = new BackendServiceFailoverPolicy(), LocalityLbPolicy = "locality_lb_policyc8722098", Region = "regionedb20d96", ConnectionTrackingPolicy = new BackendServiceConnectionTrackingPolicy(), SecurityPolicy = "security_policy76596315", CdnPolicy = new BackendServiceCdnPolicy(), Network = "networkd22ce091", Fingerprint = "fingerprint009e6052", EnableCDN = false, LogConfig = new BackendServiceLogConfig(), OutlierDetection = new OutlierDetection(), LoadBalancingScheme = "load_balancing_scheme21346104", AffinityCookieTtlSec = -328985636, CustomResponseHeaders = { "custom_response_headersda5d431e", }, CircuitBreakers = new CircuitBreakers(), Description = "description2cf9da67", HealthChecks = { "health_checksedb1f3f8", }, Subsetting = new Subsetting(), SelfLink = "self_link7e87f12d", ConnectionDraining = new ConnectionDraining(), SessionAffinity = "session_affinitye702dadf", SecuritySettings = new SecuritySettings(), Backends = { new Backend(), }, }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BackendService>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RegionBackendServicesClient client = new RegionBackendServicesClientImpl(mockGrpcClient.Object, null); BackendService responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); BackendService responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Get() { moq::Mock<RegionBackendServices.RegionBackendServicesClient> mockGrpcClient = new moq::Mock<RegionBackendServices.RegionBackendServicesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegionBackendServiceRequest request = new GetRegionBackendServiceRequest { Region = "regionedb20d96", Project = "projectaa6ff846", BackendService = "backend_serviceed490d45", }; BackendService expectedResponse = new BackendService { Id = 11672635353343658936UL, Iap = new BackendServiceIAP(), ConsistentHash = new ConsistentHashLoadBalancerSettings(), Kind = "kindf7aa39d9", Name = "name1c9368b0", Port = -78310000, CustomRequestHeaders = { "custom_request_headers3532c035", }, CreationTimestamp = "creation_timestamp235e59a1", EdgeSecurityPolicy = "edge_security_policy85c5b8f4", PortName = "port_namebaaa4cd4", MaxStreamDuration = new Duration(), TimeoutSec = -1529270667, Protocol = "protocola08b7881", FailoverPolicy = new BackendServiceFailoverPolicy(), LocalityLbPolicy = "locality_lb_policyc8722098", Region = "regionedb20d96", ConnectionTrackingPolicy = new BackendServiceConnectionTrackingPolicy(), SecurityPolicy = "security_policy76596315", CdnPolicy = new BackendServiceCdnPolicy(), Network = "networkd22ce091", Fingerprint = "fingerprint009e6052", EnableCDN = false, LogConfig = new BackendServiceLogConfig(), OutlierDetection = new OutlierDetection(), LoadBalancingScheme = "load_balancing_scheme21346104", AffinityCookieTtlSec = -328985636, CustomResponseHeaders = { "custom_response_headersda5d431e", }, CircuitBreakers = new CircuitBreakers(), Description = "description2cf9da67", HealthChecks = { "health_checksedb1f3f8", }, Subsetting = new Subsetting(), SelfLink = "self_link7e87f12d", ConnectionDraining = new ConnectionDraining(), SessionAffinity = "session_affinitye702dadf", SecuritySettings = new SecuritySettings(), Backends = { new Backend(), }, }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RegionBackendServicesClient client = new RegionBackendServicesClientImpl(mockGrpcClient.Object, null); BackendService response = client.Get(request.Project, request.Region, request.BackendService); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAsync() { moq::Mock<RegionBackendServices.RegionBackendServicesClient> mockGrpcClient = new moq::Mock<RegionBackendServices.RegionBackendServicesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegionBackendServiceRequest request = new GetRegionBackendServiceRequest { Region = "regionedb20d96", Project = "projectaa6ff846", BackendService = "backend_serviceed490d45", }; BackendService expectedResponse = new BackendService { Id = 11672635353343658936UL, Iap = new BackendServiceIAP(), ConsistentHash = new ConsistentHashLoadBalancerSettings(), Kind = "kindf7aa39d9", Name = "name1c9368b0", Port = -78310000, CustomRequestHeaders = { "custom_request_headers3532c035", }, CreationTimestamp = "creation_timestamp235e59a1", EdgeSecurityPolicy = "edge_security_policy85c5b8f4", PortName = "port_namebaaa4cd4", MaxStreamDuration = new Duration(), TimeoutSec = -1529270667, Protocol = "protocola08b7881", FailoverPolicy = new BackendServiceFailoverPolicy(), LocalityLbPolicy = "locality_lb_policyc8722098", Region = "regionedb20d96", ConnectionTrackingPolicy = new BackendServiceConnectionTrackingPolicy(), SecurityPolicy = "security_policy76596315", CdnPolicy = new BackendServiceCdnPolicy(), Network = "networkd22ce091", Fingerprint = "fingerprint009e6052", EnableCDN = false, LogConfig = new BackendServiceLogConfig(), OutlierDetection = new OutlierDetection(), LoadBalancingScheme = "load_balancing_scheme21346104", AffinityCookieTtlSec = -328985636, CustomResponseHeaders = { "custom_response_headersda5d431e", }, CircuitBreakers = new CircuitBreakers(), Description = "description2cf9da67", HealthChecks = { "health_checksedb1f3f8", }, Subsetting = new Subsetting(), SelfLink = "self_link7e87f12d", ConnectionDraining = new ConnectionDraining(), SessionAffinity = "session_affinitye702dadf", SecuritySettings = new SecuritySettings(), Backends = { new Backend(), }, }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BackendService>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RegionBackendServicesClient client = new RegionBackendServicesClientImpl(mockGrpcClient.Object, null); BackendService responseCallSettings = await client.GetAsync(request.Project, request.Region, request.BackendService, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); BackendService responseCancellationToken = await client.GetAsync(request.Project, request.Region, request.BackendService, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetHealthRequestObject() { moq::Mock<RegionBackendServices.RegionBackendServicesClient> mockGrpcClient = new moq::Mock<RegionBackendServices.RegionBackendServicesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetHealthRegionBackendServiceRequest request = new GetHealthRegionBackendServiceRequest { ResourceGroupReferenceResource = new ResourceGroupReference(), Region = "regionedb20d96", Project = "projectaa6ff846", BackendService = "backend_serviceed490d45", }; BackendServiceGroupHealth expectedResponse = new BackendServiceGroupHealth { Kind = "kindf7aa39d9", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, HealthStatus = { new HealthStatus(), }, }; mockGrpcClient.Setup(x => x.GetHealth(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RegionBackendServicesClient client = new RegionBackendServicesClientImpl(mockGrpcClient.Object, null); BackendServiceGroupHealth response = client.GetHealth(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetHealthRequestObjectAsync() { moq::Mock<RegionBackendServices.RegionBackendServicesClient> mockGrpcClient = new moq::Mock<RegionBackendServices.RegionBackendServicesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetHealthRegionBackendServiceRequest request = new GetHealthRegionBackendServiceRequest { ResourceGroupReferenceResource = new ResourceGroupReference(), Region = "regionedb20d96", Project = "projectaa6ff846", BackendService = "backend_serviceed490d45", }; BackendServiceGroupHealth expectedResponse = new BackendServiceGroupHealth { Kind = "kindf7aa39d9", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, HealthStatus = { new HealthStatus(), }, }; mockGrpcClient.Setup(x => x.GetHealthAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BackendServiceGroupHealth>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RegionBackendServicesClient client = new RegionBackendServicesClientImpl(mockGrpcClient.Object, null); BackendServiceGroupHealth responseCallSettings = await client.GetHealthAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); BackendServiceGroupHealth responseCancellationToken = await client.GetHealthAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetHealth() { moq::Mock<RegionBackendServices.RegionBackendServicesClient> mockGrpcClient = new moq::Mock<RegionBackendServices.RegionBackendServicesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetHealthRegionBackendServiceRequest request = new GetHealthRegionBackendServiceRequest { ResourceGroupReferenceResource = new ResourceGroupReference(), Region = "regionedb20d96", Project = "projectaa6ff846", BackendService = "backend_serviceed490d45", }; BackendServiceGroupHealth expectedResponse = new BackendServiceGroupHealth { Kind = "kindf7aa39d9", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, HealthStatus = { new HealthStatus(), }, }; mockGrpcClient.Setup(x => x.GetHealth(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RegionBackendServicesClient client = new RegionBackendServicesClientImpl(mockGrpcClient.Object, null); BackendServiceGroupHealth response = client.GetHealth(request.Project, request.Region, request.BackendService, request.ResourceGroupReferenceResource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetHealthAsync() { moq::Mock<RegionBackendServices.RegionBackendServicesClient> mockGrpcClient = new moq::Mock<RegionBackendServices.RegionBackendServicesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetHealthRegionBackendServiceRequest request = new GetHealthRegionBackendServiceRequest { ResourceGroupReferenceResource = new ResourceGroupReference(), Region = "regionedb20d96", Project = "projectaa6ff846", BackendService = "backend_serviceed490d45", }; BackendServiceGroupHealth expectedResponse = new BackendServiceGroupHealth { Kind = "kindf7aa39d9", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, HealthStatus = { new HealthStatus(), }, }; mockGrpcClient.Setup(x => x.GetHealthAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BackendServiceGroupHealth>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RegionBackendServicesClient client = new RegionBackendServicesClientImpl(mockGrpcClient.Object, null); BackendServiceGroupHealth responseCallSettings = await client.GetHealthAsync(request.Project, request.Region, request.BackendService, request.ResourceGroupReferenceResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); BackendServiceGroupHealth responseCancellationToken = await client.GetHealthAsync(request.Project, request.Region, request.BackendService, request.ResourceGroupReferenceResource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using System.Collections.Generic; using System.Data; using System.Web; using System.Linq; using System.Web.Mvc; using System.Web.Routing; using System.Web.Security; using System.Web.UI; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.IO; using Umbraco.Core.Cache; using Umbraco.Core.Logging; using Umbraco.Core.Services; using umbraco.BusinessLogic; using umbraco.DataLayer; using Umbraco.Core; using Umbraco.Core.Security; namespace umbraco.BasePages { /// <summary> /// umbraco.BasePages.BasePage is the default page type for the umbraco backend. /// The basepage keeps track of the current user and the page context. But does not /// Restrict access to the page itself. /// The keep the page secure, the umbracoEnsuredPage class should be used instead /// </summary> [Obsolete("This class has been superceded by Umbraco.Web.UI.Pages.BasePage")] public class BasePage : System.Web.UI.Page { private User _user; private bool _userisValidated = false; private ClientTools _clientTools; /// <summary> /// The path to the umbraco root folder /// </summary> protected string UmbracoPath = SystemDirectories.Umbraco; /// <summary> /// The current user ID /// </summary> protected int uid = 0; /// <summary> /// The page timeout in seconds. /// </summary> protected long timeout = 0; /// <summary> /// Unused, please do not use /// </summary> [Obsolete("Obsolete, For querying the database use the new UmbracoDatabase object ApplicationContext.Current.DatabaseContext.Database", false)] protected static ISqlHelper SqlHelper { get { return BusinessLogic.Application.SqlHelper; } } /// <summary> /// Returns the current ApplicationContext /// </summary> public ApplicationContext ApplicationContext { get { return ApplicationContext.Current; } } /// <summary> /// Returns a ServiceContext /// </summary> public ServiceContext Services { get { return ApplicationContext.Services; } } /// <summary> /// Returns a DatabaseContext /// </summary> public DatabaseContext DatabaseContext { get { return ApplicationContext.DatabaseContext; } } /// <summary> /// Returns the current BasePage for the current request. /// This assumes that the current page is a BasePage, otherwise, returns null; /// </summary> [Obsolete("Should use the Umbraco.Web.UmbracoContext.Current singleton instead to access common methods and properties")] public static BasePage Current { get { var page = HttpContext.Current.CurrentHandler as BasePage; if (page != null) return page; //the current handler is not BasePage but people might be expecting this to be the case if they // are using this singleton accesor... which is legacy code now and shouldn't be used. When people // start using Umbraco.Web.UI.Pages.BasePage then this will not be the case! So, we'll just return a // new instance of BasePage as a hack to make it work. if (HttpContext.Current.Items["umbraco.BasePages.BasePage"] == null) { HttpContext.Current.Items["umbraco.BasePages.BasePage"] = new BasePage(); } return (BasePage)HttpContext.Current.Items["umbraco.BasePages.BasePage"]; } } private UrlHelper _url; /// <summary> /// Returns a UrlHelper /// </summary> /// <remarks> /// This URL helper is created without any route data and an empty request context /// </remarks> public UrlHelper Url { get { return _url ?? (_url = new UrlHelper(new RequestContext(new HttpContextWrapper(Context), new RouteData()))); } } /// <summary> /// Returns a refernce of an instance of ClientTools for access to the pages client API /// </summary> public ClientTools ClientTools { get { if (_clientTools == null) _clientTools = new ClientTools(this); return _clientTools; } } [Obsolete("Use ClientTools instead")] public void RefreshPage(int Seconds) { ClientTools.RefreshAdmin(Seconds); } //NOTE: This is basically replicated in WebSecurity because this class exists in a poorly placed assembly. - also why it is obsolete. private void ValidateUser() { var ticket = Context.GetUmbracoAuthTicket(); if (ticket != null) { if (ticket.Expired == false) { _user = BusinessLogic.User.GetUser(GetUserId("")); // Check for console access if (_user.Disabled || (_user.NoConsole && GlobalSettings.RequestIsInUmbracoApplication(Context))) { throw new ArgumentException("You have no priviledges to the umbraco console. Please contact your administrator"); } _userisValidated = true; UpdateLogin(); } else { throw new ArgumentException("User has timed out!!"); } } else { throw new InvalidOperationException("The user has no umbraco contextid - try logging in"); } } /// <summary> /// Gets the user id. /// </summary> /// <param name="umbracoUserContextID">This is not used</param> /// <returns></returns> [Obsolete("This method is no longer used, use the GetUserId() method without parameters instead")] public static int GetUserId(string umbracoUserContextID) { return GetUserId(); } /// <summary> /// Gets the currnet user's id. /// </summary> /// <returns></returns> public static int GetUserId() { var identity = HttpContext.Current.GetCurrentIdentity( //DO NOT AUTO-AUTH UNLESS THE CURRENT HANDLER IS WEBFORMS! // Without this check, anything that is using this legacy API, like ui.Text will // automatically log the back office user in even if it is a front-end request (if there is // a back office user logged in. This can cause problems becaues the identity is changing mid // request. For example: http://issues.umbraco.org/issue/U4-4010 HttpContext.Current.CurrentHandler is Page); if (identity == null) return -1; return Convert.ToInt32(identity.Id); } // Added by NH to use with webservices authentications /// <summary> /// Validates the user context ID. /// </summary> /// <param name="currentUmbracoUserContextID">This doesn't do anything</param> /// <returns></returns> [Obsolete("This method is no longer used, use the ValidateCurrentUser() method instead")] public static bool ValidateUserContextID(string currentUmbracoUserContextID) { return ValidateCurrentUser(); } /// <summary> /// Validates the currently logged in user and ensures they are not timed out /// </summary> /// <returns></returns> public static bool ValidateCurrentUser() { var identity = HttpContext.Current.GetCurrentIdentity( //DO NOT AUTO-AUTH UNLESS THE CURRENT HANDLER IS WEBFORMS! // Without this check, anything that is using this legacy API, like ui.Text will // automatically log the back office user in even if it is a front-end request (if there is // a back office user logged in. This can cause problems becaues the identity is changing mid // request. For example: http://issues.umbraco.org/issue/U4-4010 HttpContext.Current.CurrentHandler is Page); if (identity != null) { return true; } return false; } //[Obsolete("Use Umbraco.Web.Security.WebSecurity.GetTimeout instead")] public static long GetTimeout(bool bypassCache) { var ticket = HttpContext.Current.GetUmbracoAuthTicket(); if (ticket.Expired) return 0; var ticks = ticket.Expiration.Ticks - DateTime.Now.Ticks; return ticks; } // Changed to public by NH to help with webservice authentication /// <summary> /// Gets or sets the umbraco user context ID. /// </summary> /// <value>The umbraco user context ID.</value> [Obsolete("Returns the current user's unique umbraco sesion id - this cannot be set and isn't intended to be used in your code")] public static string umbracoUserContextID { get { var identity = HttpContext.Current.GetCurrentIdentity( //DO NOT AUTO-AUTH UNLESS THE CURRENT HANDLER IS WEBFORMS! // Without this check, anything that is using this legacy API, like ui.Text will // automatically log the back office user in even if it is a front-end request (if there is // a back office user logged in. This can cause problems becaues the identity is changing mid // request. For example: http://issues.umbraco.org/issue/U4-4010 HttpContext.Current.CurrentHandler is Page); return identity == null ? "" : identity.SessionId; } set { } } /// <summary> /// Clears the login. /// </summary> public void ClearLogin() { Context.UmbracoLogout(); } private void UpdateLogin() { Context.RenewUmbracoAuthTicket(); } public static void RenewLoginTimeout() { HttpContext.Current.RenewUmbracoAuthTicket(); } /// <summary> /// Logs a user in. /// </summary> /// <param name="u">The user</param> public static void doLogin(User u) { HttpContext.Current.CreateUmbracoAuthTicket(new UserData(Guid.NewGuid().ToString("N")) { Id = u.Id, AllowedApplications = u.GetApplications().Select(x => x.alias).ToArray(), RealName = u.Name, //currently we only have one user type! Roles = new[] { u.UserType.Alias }, StartContentNode = u.StartNodeId, StartMediaNode = u.StartMediaId, Username = u.LoginName, Culture = ui.Culture(u) }); LogHelper.Info<BasePage>("User {0} (Id: {1}) logged in", () => u.Name, () => u.Id); } /// <summary> /// Gets the user. /// </summary> /// <returns></returns> [Obsolete("Use UmbracoUser property instead.")] public User getUser() { return UmbracoUser; } /// <summary> /// Gets the user. /// </summary> /// <value></value> public User UmbracoUser { get { if (!_userisValidated) ValidateUser(); return _user; } } /// <summary> /// Ensures the page context. /// </summary> public void ensureContext() { ValidateUser(); } [Obsolete("Use ClientTools instead")] public void speechBubble(speechBubbleIcon i, string header, string body) { ClientTools.ShowSpeechBubble(i, header, body); } //[Obsolete("Use ClientTools instead")] //public void reloadParentNode() //{ // ClientTools.ReloadParentNode(true); //} /// <summary> /// a collection of available speechbubble icons /// </summary> [Obsolete("This has been superceded by Umbraco.Web.UI.SpeechBubbleIcon but that requires the use of the Umbraco.Web.UI.Pages.BasePage or Umbraco.Web.UI.Pages.EnsuredPage objects")] public enum speechBubbleIcon { /// <summary> /// Save icon /// </summary> save, /// <summary> /// Info icon /// </summary> info, /// <summary> /// Error icon /// </summary> error, /// <summary> /// Success icon /// </summary> success, /// <summary> /// Warning icon /// </summary> warning } protected override void OnInit(EventArgs e) { base.OnInit(e); //This must be set on each page to mitigate CSRF attacks which ensures that this unique token // is added to the viewstate of each request if (umbracoUserContextID.IsNullOrWhiteSpace() == false) { ViewStateUserKey = umbracoUserContextID; } } /// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load"></see> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs"></see> object that contains the event data.</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!Request.IsSecureConnection && GlobalSettings.UseSSL) { string serverName = HttpUtility.UrlEncode(Request.ServerVariables["SERVER_NAME"]); Response.Redirect(string.Format("https://{0}{1}", serverName, Request.FilePath)); } } /// <summary> /// Override client target. /// </summary> [Obsolete("This is no longer supported")] public bool OverrideClientTarget = false; } }
/******************************************************************************* * Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET * API Version: 2006-03-01 * */ using System.Xml.Serialization; namespace Amazon.S3.Model { /// <summary> /// The parameters to list the object keys in a bucket. /// </summary> [XmlTypeAttribute(Namespace = "http://s3.amazonaws.com/doc/2006-03-01/")] [XmlRootAttribute(Namespace = "http://s3.amazonaws.com/doc/2006-03-01/", IsNullable = false)] public class ListObjectsRequest : S3Request { #region Private Members private string bucketName; private string prefix; private string marker; private int maxKeys = -1; private string delimiter; #endregion #region BucketName /// <summary> /// The name of the bucket containing the objects whose keys are to be listed. /// </summary> [XmlElementAttribute(ElementName = "BucketName")] public string BucketName { get { return this.bucketName; } set { this.bucketName = value; } } /// <summary> /// Sets the name of the bucket containing the objects whose keys are to be listed. /// </summary> /// <param name="bucketName">The bucket name</param> /// <returns>this instance</returns> [System.Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ListObjectsRequest WithBucketName(string bucketName) { this.bucketName = bucketName; return this; } /// <summary> /// Checks if BucketName property is set /// </summary> /// <returns>true if BucketName property is set</returns> internal bool IsSetBucketName() { return !System.String.IsNullOrEmpty(this.bucketName); } #endregion #region Prefix /// <summary> /// Limits the response to keys which begin with the indicated prefix. You can /// use prefixes to separate a bucket into different sets of keys in a way similar /// to how a file system uses folders. /// </summary> [XmlElementAttribute(ElementName = "Prefix")] public string Prefix { get { return this.prefix; } set { this.prefix=value; } } /// <summary> /// Limits the response to keys which begin with the indicated prefix. You can /// use prefixes to separate a bucket into different sets of keys in a way similar /// to how a file system uses folders. /// </summary> /// <param name="prefix">The prefix value</param> /// <returns>this instance</returns> [System.Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ListObjectsRequest WithPrefix(string prefix) { this.prefix = prefix; return this; } /// <summary> /// Checks if Prefix property is set /// </summary> /// <returns>true if Prefix property is set</returns> internal bool IsSetPrefix() { return !System.String.IsNullOrEmpty(this.prefix); } #endregion #region Marker /// <summary> /// Indicates where in the bucket to begin listing. The list will only /// include keys that occur lexicographically after marker. This is /// convenient for pagination: to get the next page of results use the /// last key of the current page as the marker. /// </summary> [XmlElementAttribute(ElementName = "Marker")] public string Marker { get { return this.marker; } set { this.marker = value; } } /// <summary> /// Indicates where in the bucket to begin listing. The list will only /// include keys that occur lexicographically after marker. This is /// convenient for pagination: to get the next page of results use the /// last key of the current page as the marker. /// </summary> /// <param name="marker">The marker value</param> /// <returns>this instance</returns> [System.Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ListObjectsRequest WithMarker(string marker) { this.marker = marker; return this; } /// <summary> /// Checks if Marker property is set /// </summary> /// <returns>true if Marker property is set</returns> internal bool IsSetMarker() { return !System.String.IsNullOrEmpty(this.marker); } #endregion #region MaxKeys /// <summary> /// The maximum number of keys you'd like to see in the response body. The /// server might return fewer than this many keys, but will not return more. /// </summary> [XmlElementAttribute(ElementName = "MaxKeys")] public int MaxKeys { get { return this.maxKeys; } set { this.maxKeys = value; } } /// <summary> /// The maximum number of keys you'd like to see in the response body. The /// server might return fewer than this many keys, but will not return more. /// </summary> /// <param name="maxKeys">The maximum keys value</param> /// <returns>this instance</returns> [System.Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ListObjectsRequest WithMaxKeys(int maxKeys) { this.maxKeys = maxKeys; return this; } /// <summary> /// Checks if MaxKeys property is set /// </summary> /// <returns>true if MaxKeys property is set</returns> internal bool IsSetMaxKeys() { return this.maxKeys >= 0; } #endregion #region Delimiter /// <summary> /// Causes keys that contain the same string between the prefix and the /// first occurrence of the delimiter to be rolled up into a single result /// element in the CommonPrefixes collection. These rolled-up keys are not /// returned elsewhere in the response. /// </summary> [XmlElementAttribute(ElementName = "Delimiter")] public string Delimiter { get { return this.delimiter; } set { this.delimiter = value; } } /// <summary> /// Causes keys that contain the same string between the prefix and the /// first occurrence of the delimiter to be rolled up into a single result /// element in the CommonPrefixes collection. These rolled-up keys are not /// returned elsewhere in the response. /// </summary> /// <param name="delimiter">The delimiter value</param> /// <returns>this instance</returns> [System.Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ListObjectsRequest WithDelimiter(string delimiter) { this.delimiter = delimiter; return this; } /// <summary> /// Checks if Delimiter property is set /// </summary> /// <returns>true if Delimiter property is set</returns> internal bool IsSetDelimiter() { return !System.String.IsNullOrEmpty(this.delimiter); } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Automation { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for CertificateOperations. /// </summary> public static partial class CertificateOperationsExtensions { /// <summary> /// Delete the certificate. /// <see href="http://aka.ms/azureautomationsdk/certificateoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='certificateName'> /// The name of certificate. /// </param> public static void Delete(this ICertificateOperations operations, string resourceGroupName, string automationAccountName, string certificateName) { operations.DeleteAsync(resourceGroupName, automationAccountName, certificateName).GetAwaiter().GetResult(); } /// <summary> /// Delete the certificate. /// <see href="http://aka.ms/azureautomationsdk/certificateoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='certificateName'> /// The name of certificate. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this ICertificateOperations operations, string resourceGroupName, string automationAccountName, string certificateName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, automationAccountName, certificateName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Retrieve the certificate identified by certificate name. /// <see href="http://aka.ms/azureautomationsdk/certificateoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='certificateName'> /// The name of certificate. /// </param> public static Certificate Get(this ICertificateOperations operations, string resourceGroupName, string automationAccountName, string certificateName) { return operations.GetAsync(resourceGroupName, automationAccountName, certificateName).GetAwaiter().GetResult(); } /// <summary> /// Retrieve the certificate identified by certificate name. /// <see href="http://aka.ms/azureautomationsdk/certificateoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='certificateName'> /// The name of certificate. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Certificate> GetAsync(this ICertificateOperations operations, string resourceGroupName, string automationAccountName, string certificateName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, automationAccountName, certificateName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Create a certificate. /// <see href="http://aka.ms/azureautomationsdk/certificateoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='certificateName'> /// The parameters supplied to the create or update certificate operation. /// </param> /// <param name='parameters'> /// The parameters supplied to the create or update certificate operation. /// </param> public static Certificate CreateOrUpdate(this ICertificateOperations operations, string resourceGroupName, string automationAccountName, string certificateName, CertificateCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, automationAccountName, certificateName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Create a certificate. /// <see href="http://aka.ms/azureautomationsdk/certificateoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='certificateName'> /// The parameters supplied to the create or update certificate operation. /// </param> /// <param name='parameters'> /// The parameters supplied to the create or update certificate operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Certificate> CreateOrUpdateAsync(this ICertificateOperations operations, string resourceGroupName, string automationAccountName, string certificateName, CertificateCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, automationAccountName, certificateName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Update a certificate. /// <see href="http://aka.ms/azureautomationsdk/certificateoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='certificateName'> /// The parameters supplied to the update certificate operation. /// </param> /// <param name='parameters'> /// The parameters supplied to the update certificate operation. /// </param> public static Certificate Update(this ICertificateOperations operations, string resourceGroupName, string automationAccountName, string certificateName, CertificateUpdateParameters parameters) { return operations.UpdateAsync(resourceGroupName, automationAccountName, certificateName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Update a certificate. /// <see href="http://aka.ms/azureautomationsdk/certificateoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='certificateName'> /// The parameters supplied to the update certificate operation. /// </param> /// <param name='parameters'> /// The parameters supplied to the update certificate operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Certificate> UpdateAsync(this ICertificateOperations operations, string resourceGroupName, string automationAccountName, string certificateName, CertificateUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, automationAccountName, certificateName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Retrieve a list of certificates. /// <see href="http://aka.ms/azureautomationsdk/certificateoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> public static IPage<Certificate> ListByAutomationAccount(this ICertificateOperations operations, string resourceGroupName, string automationAccountName) { return operations.ListByAutomationAccountAsync(resourceGroupName, automationAccountName).GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of certificates. /// <see href="http://aka.ms/azureautomationsdk/certificateoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Certificate>> ListByAutomationAccountAsync(this ICertificateOperations operations, string resourceGroupName, string automationAccountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByAutomationAccountWithHttpMessagesAsync(resourceGroupName, automationAccountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Retrieve a list of certificates. /// <see href="http://aka.ms/azureautomationsdk/certificateoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<Certificate> ListByAutomationAccountNext(this ICertificateOperations operations, string nextPageLink) { return operations.ListByAutomationAccountNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of certificates. /// <see href="http://aka.ms/azureautomationsdk/certificateoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Certificate>> ListByAutomationAccountNextAsync(this ICertificateOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByAutomationAccountNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using BenchmarkDotNet.Loggers; using BenchmarkDotNet.Portability; using BenchmarkDotNet.Running; using BenchmarkDotNet.Toolchains.CsProj; using BenchmarkDotNet.Toolchains.DotNetCli; namespace BenchmarkDotNet.Toolchains.CoreRt { /// <summary> /// generates new csproj file for self-contained .NET Core RT app /// based on https://github.com/dotnet/corert/blob/7f902d4d8b1c3280e60f5e06c71951a60da173fb/Documentation/how-to-build-and-run-ilcompiler-in-console-shell-prompt.md#compiling-source-to-native-code-using-the-ilcompiler-you-built /// and https://github.com/dotnet/corert/tree/7f902d4d8b1c3280e60f5e06c71951a60da173fb/samples/HelloWorld#add-corert-to-your-project /// </summary> public class Generator : CsProjGenerator { internal const string CoreRtNuGetFeed = "coreRtNuGetFeed"; internal Generator(string coreRtVersion, bool useCppCodeGenerator, string runtimeFrameworkVersion, string targetFrameworkMoniker, string cliPath, string runtimeIdentifier, IReadOnlyDictionary<string, string> feeds, bool useNuGetClearTag, bool useTempFolderForRestore, string packagesRestorePath, bool rootAllApplicationAssemblies, bool ilcGenerateCompleteTypeMetadata, bool ilcGenerateStackTraceData) : base(targetFrameworkMoniker, cliPath, GetPackagesDirectoryPath(useTempFolderForRestore, packagesRestorePath), runtimeFrameworkVersion) { this.coreRtVersion = coreRtVersion; this.useCppCodeGenerator = useCppCodeGenerator; this.targetFrameworkMoniker = targetFrameworkMoniker; this.runtimeIdentifier = runtimeIdentifier; this.feeds = feeds; this.useNuGetClearTag = useNuGetClearTag; this.useTempFolderForRestore = useTempFolderForRestore; this.rootAllApplicationAssemblies = rootAllApplicationAssemblies; this.ilcGenerateCompleteTypeMetadata = ilcGenerateCompleteTypeMetadata; this.ilcGenerateStackTraceData = ilcGenerateStackTraceData; } private readonly string coreRtVersion; private readonly bool useCppCodeGenerator; private readonly string targetFrameworkMoniker; private readonly string runtimeIdentifier; private readonly IReadOnlyDictionary<string, string> feeds; private readonly bool useNuGetClearTag; private readonly bool useTempFolderForRestore; private readonly bool rootAllApplicationAssemblies; private readonly bool ilcGenerateCompleteTypeMetadata; private readonly bool ilcGenerateStackTraceData; private bool IsNuGetCoreRt => feeds.ContainsKey(CoreRtNuGetFeed) && !string.IsNullOrWhiteSpace(coreRtVersion); protected override string GetExecutableExtension() => RuntimeInformation.ExecutableExtension; protected override string GetBuildArtifactsDirectoryPath(BuildPartition buildPartition, string programName) => useTempFolderForRestore ? Path.Combine(Path.GetTempPath(), programName) // store everything in temp to avoid collisions with IDE : base.GetBuildArtifactsDirectoryPath(buildPartition, programName); protected override string GetBinariesDirectoryPath(string buildArtifactsDirectoryPath, string configuration) => Path.Combine(buildArtifactsDirectoryPath, "bin", configuration, TargetFrameworkMoniker, runtimeIdentifier, "native"); protected override void GenerateBuildScript(BuildPartition buildPartition, ArtifactsPaths artifactsPaths) { string extraArguments = useCppCodeGenerator ? $"-r {runtimeIdentifier} /p:NativeCodeGen=cpp" : $"-r {runtimeIdentifier}"; var content = new StringBuilder(300) .AppendLine($"call {CliPath ?? "dotnet"} {DotNetCliCommand.GetRestoreCommand(artifactsPaths, buildPartition)} {extraArguments}") .AppendLine($"call {CliPath ?? "dotnet"} {DotNetCliCommand.GetBuildCommand(buildPartition)} {extraArguments}") .AppendLine($"call {CliPath ?? "dotnet"} {DotNetCliCommand.GetPublishCommand(buildPartition)} {extraArguments}") .ToString(); File.WriteAllText(artifactsPaths.BuildScriptFilePath, content); } // we always want to have a new directory for NuGet packages restore // to avoid this https://github.com/dotnet/coreclr/blob/master/Documentation/workflow/UsingDotNetCli.md#update-coreclr-using-runtime-nuget-package // some of the packages are going to contain source code, so they can not be in the subfolder of current solution // otherwise they would be compiled too (new .csproj include all .cs files from subfolders by default private static string GetPackagesDirectoryPath(bool useTempFolderForRestore, string packagesRestorePath) => packagesRestorePath ?? (useTempFolderForRestore ? Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()) : null); protected override string[] GetArtifactsToCleanup(ArtifactsPaths artifactsPaths) => useTempFolderForRestore ? base.GetArtifactsToCleanup(artifactsPaths).Concat(new[] { artifactsPaths.PackagesDirectoryName }).ToArray() : base.GetArtifactsToCleanup(artifactsPaths); protected override void GenerateNuGetConfig(ArtifactsPaths artifactsPaths) { if (!feeds.Any()) return; string content = $@"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> <packageSources> {(useNuGetClearTag ? "<clear/>" : string.Empty)} {string.Join(Environment.NewLine + " ", feeds.Select(feed => $"<add key=\"{feed.Key}\" value=\"{feed.Value}\" />"))} </packageSources> </configuration>"; File.WriteAllText(artifactsPaths.NuGetConfigPath, content); } protected override void GenerateProject(BuildPartition buildPartition, ArtifactsPaths artifactsPaths, ILogger logger) { File.WriteAllText(artifactsPaths.ProjectFilePath, IsNuGetCoreRt ? GenerateProjectForNuGetBuild(buildPartition, artifactsPaths, logger) : GenerateProjectForLocalBuild(buildPartition, artifactsPaths, logger)); GenerateReflectionFile(artifactsPaths); } private string GenerateProjectForNuGetBuild(BuildPartition buildPartition, ArtifactsPaths artifactsPaths, ILogger logger) => $@" <Project Sdk=""Microsoft.NET.Sdk""> <PropertyGroup> <ImportDirectoryBuildProps>false</ImportDirectoryBuildProps> <ImportDirectoryBuildTargets>false</ImportDirectoryBuildTargets> <OutputType>Exe</OutputType> <TargetFramework>{TargetFrameworkMoniker}</TargetFramework> <RuntimeIdentifier>{runtimeIdentifier}</RuntimeIdentifier> <RuntimeFrameworkVersion>{RuntimeFrameworkVersion}</RuntimeFrameworkVersion> <AssemblyName>{artifactsPaths.ProgramName}</AssemblyName> <AssemblyTitle>{artifactsPaths.ProgramName}</AssemblyTitle> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <TreatWarningsAsErrors>False</TreatWarningsAsErrors> <DebugType>pdbonly</DebugType> <DebugSymbols>true</DebugSymbols> <UseSharedCompilation>false</UseSharedCompilation> <RootAllApplicationAssemblies>{rootAllApplicationAssemblies}</RootAllApplicationAssemblies> <IlcGenerateCompleteTypeMetadata>{ilcGenerateCompleteTypeMetadata}</IlcGenerateCompleteTypeMetadata> <IlcGenerateStackTraceData>{ilcGenerateStackTraceData}</IlcGenerateStackTraceData> </PropertyGroup> {GetRuntimeSettings(buildPartition.RepresentativeBenchmarkCase.Job.Environment.Gc, buildPartition.Resolver)} <ItemGroup> <Compile Include=""{Path.GetFileName(artifactsPaths.ProgramCodePath)}"" Exclude=""bin\**;obj\**;**\*.xproj;packages\**"" /> </ItemGroup> <ItemGroup> <PackageReference Include=""Microsoft.DotNet.ILCompiler"" Version=""{coreRtVersion}"" /> <ProjectReference Include=""{GetProjectFilePath(buildPartition.RepresentativeBenchmarkCase.Descriptor.Type, logger).FullName}"" /> </ItemGroup> <ItemGroup> <RdXmlFile Include=""rd.xml"" /> </ItemGroup> </Project>"; private string GenerateProjectForLocalBuild(BuildPartition buildPartition, ArtifactsPaths artifactsPaths, ILogger logger) => $@" <Project> <Import Project=""$(MSBuildSDKsPath)\Microsoft.NET.Sdk\Sdk\Sdk.props"" /> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>{TargetFrameworkMoniker}</TargetFramework> <RuntimeIdentifier>{runtimeIdentifier}</RuntimeIdentifier> <RuntimeFrameworkVersion>{RuntimeFrameworkVersion}</RuntimeFrameworkVersion> <AssemblyName>{artifactsPaths.ProgramName}</AssemblyName> <AssemblyTitle>{artifactsPaths.ProgramName}</AssemblyTitle> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <TreatWarningsAsErrors>False</TreatWarningsAsErrors> <DebugType>pdbonly</DebugType> <DebugSymbols>true</DebugSymbols> <UseSharedCompilation>false</UseSharedCompilation> <RootAllApplicationAssemblies>{rootAllApplicationAssemblies}</RootAllApplicationAssemblies> <IlcGenerateCompleteTypeMetadata>{ilcGenerateCompleteTypeMetadata}</IlcGenerateCompleteTypeMetadata> <IlcGenerateStackTraceData>{ilcGenerateStackTraceData}</IlcGenerateStackTraceData> </PropertyGroup> <Import Project=""$(MSBuildSDKsPath)\Microsoft.NET.Sdk\Sdk\Sdk.targets"" /> <Import Project=""$(IlcPath)\build\Microsoft.NETCore.Native.targets"" /> {GetRuntimeSettings(buildPartition.RepresentativeBenchmarkCase.Job.Environment.Gc, buildPartition.Resolver)} <ItemGroup> <Compile Include=""{Path.GetFileName(artifactsPaths.ProgramCodePath)}"" Exclude=""bin\**;obj\**;**\*.xproj;packages\**"" /> </ItemGroup> <ItemGroup> <ProjectReference Include=""{GetProjectFilePath(buildPartition.RepresentativeBenchmarkCase.Descriptor.Type, logger).FullName}"" /> </ItemGroup> <ItemGroup> <RdXmlFile Include=""rd.xml"" /> </ItemGroup> </Project>"; /// <summary> /// mandatory to make it possible to call GC.GetAllocatedBytesForCurrentThread() using reflection (not part of .NET Standard) /// </summary> private void GenerateReflectionFile(ArtifactsPaths artifactsPaths) { const string content = @" <Directives> <Application> <Assembly Name=""System.Runtime""> <Type Name=""System.GC"" Dynamic=""Required All"" /> </Assembly> </Application> </Directives> "; File.WriteAllText(Path.Combine(Path.GetDirectoryName(artifactsPaths.ProjectFilePath), "rd.xml"), content); } } }
//#define ASTARDEBUG using UnityEngine; using System.Collections.Generic; using Pathfinding.Util; namespace Pathfinding { [AddComponentMenu ("Pathfinding/Modifiers/Funnel")] [System.Serializable] /** Simplifies paths on navmesh graphs using the funnel algorithm. * The funnel algorithm is an algorithm which can, given a path corridor with nodes in the path where the nodes have an area, like triangles, it can find the shortest path inside it. * This makes paths on navmeshes look much cleaner and smoother. * \image html images/funnelModifier_on.png * \ingroup modifiers */ public class FunnelModifier : MonoModifier { #if UNITY_EDITOR [UnityEditor.MenuItem ("CONTEXT/Seeker/Add Funnel Modifier")] public static void AddComp (UnityEditor.MenuCommand command) { (command.context as Component).gameObject.AddComponent (typeof(FunnelModifier)); } #endif public override ModifierData input { get { return ModifierData.StrictVectorPath; } } public override ModifierData output { get { return ModifierData.VectorPath; } } public override void Apply (Path p, ModifierData source) { List<GraphNode> path = p.path; List<Vector3> vectorPath = p.vectorPath; if (path == null || path.Count == 0 || vectorPath == null || vectorPath.Count != path.Count) { return; } List<Vector3> funnelPath = ListPool<Vector3>.Claim (); //Claim temporary lists and try to find lists with a high capacity List<Vector3> left = ListPool<Vector3>.Claim (path.Count+1); List<Vector3> right = ListPool<Vector3>.Claim (path.Count+1); AstarProfiler.StartProfile ("Construct Funnel"); left.Add (vectorPath[0]); right.Add (vectorPath[0]); for (int i=0;i<path.Count-1;i++) { bool a = path[i].GetPortal (path[i+1], left, right, false); bool b = false;//path[i+1].GetPortal (path[i], right, left, true); if (!a && !b) { left.Add ((Vector3)path[i].position); right.Add ((Vector3)path[i].position); left.Add ((Vector3)path[i+1].position); right.Add ((Vector3)path[i+1].position); } } left.Add (vectorPath[vectorPath.Count-1]); right.Add (vectorPath[vectorPath.Count-1]); if (!RunFunnel (left,right,funnelPath)) { //If funnel algorithm failed, degrade to simple line funnelPath.Add (vectorPath[0]); funnelPath.Add (vectorPath[vectorPath.Count-1]); } ListPool<Vector3>.Release (p.vectorPath); p.vectorPath = funnelPath; ListPool<Vector3>.Release (left); ListPool<Vector3>.Release (right); } /** Calculate a funnel path from the \a left and \a right portal lists. * The result will be appended to \a funnelPath */ public bool RunFunnel (List<Vector3> left, List<Vector3> right, List<Vector3> funnelPath) { if (left == null) throw new System.ArgumentNullException("left"); if (right == null) throw new System.ArgumentNullException("right"); if (funnelPath == null) throw new System.ArgumentNullException("funnelPath"); if (left.Count != right.Count) throw new System.ArgumentException("left and right lists must have equal length"); if (left.Count <= 3) { return false; } //Remove identical vertices while (left[1] == left[2] && right[1] == right[2]) { //System.Console.WriteLine ("Removing identical left and right"); left.RemoveAt (1); right.RemoveAt (1); if (left.Count <= 3) { return false; } } Vector3 swPoint = left[2]; if (swPoint == left[1]) { swPoint = right[2]; } //Test while (Polygon.IsColinear (left[0],left[1],right[1]) || Polygon.Left (left[1],right[1],swPoint) == Polygon.Left (left[1],right[1],left[0])) { left.RemoveAt (1); right.RemoveAt (1); if (left.Count <= 3) { return false; } swPoint = left[2]; if (swPoint == left[1]) { swPoint = right[2]; } } //Switch left and right to really be on the "left" and "right" sides if (!Polygon.IsClockwise (left[0],left[1],right[1]) && !Polygon.IsColinear (left[0],left[1],right[1])) { //System.Console.WriteLine ("Wrong Side 2"); List<Vector3> tmp = left; left = right; right = tmp; } funnelPath.Add (left[0]); Vector3 portalApex = left[0]; Vector3 portalLeft = left[1]; Vector3 portalRight = right[1]; int apexIndex = 0; int rightIndex = 1; int leftIndex = 1; for (int i=2;i<left.Count;i++) { if (funnelPath.Count > 2000) { Debug.LogWarning ("Avoiding infinite loop. Remove this check if you have this long paths."); break; } Vector3 pLeft = left[i]; Vector3 pRight = right[i]; /*Debug.DrawLine (portalApex,portalLeft,Color.red); Debug.DrawLine (portalApex,portalRight,Color.yellow); Debug.DrawLine (portalApex,left,Color.cyan); Debug.DrawLine (portalApex,right,Color.cyan);*/ if (Polygon.TriangleArea2 (portalApex,portalRight,pRight) >= 0) { if (portalApex == portalRight || Polygon.TriangleArea2 (portalApex,portalLeft,pRight) <= 0) { portalRight = pRight; rightIndex = i; } else { funnelPath.Add (portalLeft); portalApex = portalLeft; apexIndex = leftIndex; portalLeft = portalApex; portalRight = portalApex; leftIndex = apexIndex; rightIndex = apexIndex; i = apexIndex; continue; } } if (Polygon.TriangleArea2 (portalApex,portalLeft,pLeft) <= 0) { if (portalApex == portalLeft || Polygon.TriangleArea2 (portalApex,portalRight,pLeft) >= 0) { portalLeft = pLeft; leftIndex = i; } else { funnelPath.Add (portalRight); portalApex = portalRight; apexIndex = rightIndex; portalLeft = portalApex; portalRight = portalApex; leftIndex = apexIndex; rightIndex = apexIndex; i = apexIndex; continue; } } } funnelPath.Add (left[left.Count-1]); return true; } } /** Graphs implementing this interface have support for the Funnel modifier */ public interface IFunnelGraph { void BuildFunnelCorridor (List<GraphNode> path, int sIndex, int eIndex, List<Vector3> left, List<Vector3> right); /** Add the portal between node \a n1 and \a n2 to the funnel corridor. The left and right edges does not necesarily need to be the left and right edges (right can be left), they will be swapped if that is detected. But that works only as long as the edges do not switch between left and right in the middle of the path. */ void AddPortal (GraphNode n1, GraphNode n2, List<Vector3> left, List<Vector3> right); } }
#region File Description //----------------------------------------------------------------------------- // Game.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System; #endregion namespace DistortionSample { /// <summary> /// This sample demonstrates a variety of image-distorting /// post-processing techniques. /// </summary> public class DistortionSampleGame : Microsoft.Xna.Framework.Game { #region Fields GraphicsDeviceManager graphics; const float initialViewAngle = MathHelper.Pi / 2f; float viewAngle = initialViewAngle; const float CameraRotationSpeed = 0.1f; const float ViewDistance = 750.0f; DistortionComponent distortionComponent; Distorter[] distorters; int currentDistorter; SpriteBatch spriteBatch; SpriteFont spriteFont; Vector2 overlayTextLocation; Texture2D background; KeyboardState lastKeyboardState = new KeyboardState(); GamePadState lastGamePadState = new GamePadState(); KeyboardState currentKeyboardState = new KeyboardState(); GamePadState currentGamePadState = new GamePadState(); #endregion #region Initialization public DistortionSampleGame() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; distortionComponent = new DistortionComponent(this); Components.Add(distortionComponent); } protected override void Initialize() { distorters = new Distorter[3]; currentDistorter = 0; base.Initialize(); } /// <summary> /// Load your graphics content. /// </summary> protected override void LoadContent() { spriteBatch = new SpriteBatch(graphics.GraphicsDevice); spriteFont = Content.Load<SpriteFont>("hudFont"); background = Content.Load<Texture2D>("Sunset"); distorters[0] = new Distorter(); distorters[0].ModelName = "Dude"; distorters[0].World = Matrix.CreateTranslation(0, -40, 0) * Matrix.CreateScale(8); distorters[0].Model = Content.Load<Model>("Dude"); distorters[0].Technique = DistortionComponent.DistortionTechnique.PullIn; distorters[0].DistortionScale = 0.0003f; distorters[0].DistortionBlur = true; distorters[1] = new Distorter(); distorters[1].ModelName = "Cylinder"; distorters[1].World = Matrix.CreateScale(200); distorters[1].Model = Content.Load<Model>("Cylinder"); distorters[1].Technique = DistortionComponent.DistortionTechnique.HeatHaze; distorters[1].DistortionScale = 0.025f; distorters[1].DistortionBlur = true; distorters[2] = new Distorter(); distorters[2].ModelName = "Window"; distorters[2].World = Matrix.CreateScale(500); distorters[2].Model = Content.Load<Model>("Window"); distorters[2].Technique = DistortionComponent.DistortionTechnique.DisplacementMapped; distorters[2].DistortionScale = 0.025f; distorters[2].DistortionBlur = false; overlayTextLocation = new Vector2( (float)graphics.GraphicsDevice.Viewport.X + (float)graphics.GraphicsDevice.Viewport.Width * 0.1f, (float)graphics.GraphicsDevice.Viewport.Y + (float)graphics.GraphicsDevice.Viewport.Height * 0.1f ); } #endregion #region Update and Draw /// <summary> /// Allows the game to run logic. /// </summary> protected override void Update(GameTime gameTime) { HandleInput(); // update the distortion component distortionComponent.Distorter = distorters[currentDistorter]; base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> protected override void Draw(GameTime gameTime) { distortionComponent.BeginDraw(); GraphicsDevice.Clear(Color.Black); // Draw the background image. spriteBatch.Begin(0, BlendState.Opaque); spriteBatch.Draw(background, GraphicsDevice.Viewport.Bounds, Color.White); spriteBatch.End(); // Draw other components (which includes the distortion). base.Draw(gameTime); // Display some text over the top. Note how we draw this after distortion // because we don't want the text to be affected by the postprocessing. DrawOverlayText(); } /// <summary> /// Displays an overlay showing what the controls are, /// and which settings are currently selected. /// </summary> void DrawOverlayText() { string text = distorters[currentDistorter].ToString() + "\n\n" + "A: Cycle Distorter\n" + "X: " + (distorters[currentDistorter].DistortionBlur ? "Disable" : "Enable") + " Distorter Blur\n" + "B: " + (distortionComponent.ShowDistortionMap ? "Hide" : "Show") + " Distortion Map\n"; spriteBatch.Begin(); // Draw the string twice to create a drop shadow, first colored black // and offset one pixel to the bottom right, then again in white at the // intended position. this makes text easier to read over the background. spriteBatch.DrawString(spriteFont, text, overlayTextLocation + Vector2.One, Color.Black); spriteBatch.DrawString(spriteFont, text, overlayTextLocation, Color.White); spriteBatch.End(); } #endregion #region Handle Input /// <summary> /// Handles input for quitting or changing the sample settings. /// </summary> private void HandleInput() { lastKeyboardState = currentKeyboardState; lastGamePadState = currentGamePadState; currentKeyboardState = Keyboard.GetState(); currentGamePadState = GamePad.GetState(PlayerIndex.One); // Check for exit. if (currentKeyboardState.IsKeyDown(Keys.Escape) || currentGamePadState.Buttons.Back == ButtonState.Pressed) { Exit(); } // Cycle mode if ((currentGamePadState.Buttons.A == ButtonState.Pressed && lastGamePadState.Buttons.A != ButtonState.Pressed) || (currentKeyboardState.IsKeyDown(Keys.Space) && lastKeyboardState.IsKeyUp(Keys.Space)) || (currentKeyboardState.IsKeyDown(Keys.A) && lastKeyboardState.IsKeyUp(Keys.A))) { currentDistorter = (currentDistorter + 1) % distorters.Length; viewAngle = initialViewAngle; } // Toggle showing the distortion map on or off? if ((currentGamePadState.Buttons.B == ButtonState.Pressed && lastGamePadState.Buttons.B != ButtonState.Pressed) || (currentKeyboardState.IsKeyDown(Keys.Tab) && lastKeyboardState.IsKeyUp(Keys.Tab)) || (currentKeyboardState.IsKeyDown(Keys.B) && lastKeyboardState.IsKeyUp(Keys.B))) { distortionComponent.ShowDistortionMap = !distortionComponent.ShowDistortionMap; } // Toggle showing the distortion map on or off? if ((currentGamePadState.Buttons.X == ButtonState.Pressed && lastGamePadState.Buttons.X != ButtonState.Pressed) || (currentKeyboardState.IsKeyDown(Keys.LeftControl) && lastKeyboardState.IsKeyUp(Keys.LeftControl)) || (currentKeyboardState.IsKeyDown(Keys.X) && lastKeyboardState.IsKeyUp(Keys.X))) { distorters[currentDistorter].DistortionBlur = !distorters[currentDistorter].DistortionBlur; } // rotate the camera, using the left thumbstick and arrow keys float viewAngleChange = currentGamePadState.ThumbSticks.Left.X; if (currentKeyboardState.IsKeyDown(Keys.Left)) { viewAngleChange = -1; } else if (currentKeyboardState.IsKeyDown(Keys.Right)) { viewAngleChange = 1; } viewAngle += viewAngleChange * CameraRotationSpeed; distortionComponent.View = Matrix.CreateLookAt(ViewDistance * new Vector3((float)Math.Cos(viewAngle), 0, (float)Math.Sin(viewAngle)), Vector3.Zero, Vector3.Up); } #endregion } #region Entry Point /// <summary> /// The main entry point for the application. /// </summary> static class Program { static void Main() { using (DistortionSampleGame game = new DistortionSampleGame()) { game.Run(); } } } #endregion }
#region license // Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Text.RegularExpressions; using System.Globalization; using System.IO; using System.Collections.Generic; namespace Boo.Lang.Compiler.Ast.Visitors { /// <summary> /// </summary> public class BooPrinterVisitor : TextEmitter { [Flags] public enum PrintOptions { None, PrintLocals = 1, WSA = 2, } public PrintOptions Options = PrintOptions.None; public BooPrinterVisitor(TextWriter writer) : base(writer) { } public BooPrinterVisitor(TextWriter writer, PrintOptions options) : this(writer) { this.Options = options; } public bool IsOptionSet(PrintOptions option) { return (option & Options) == option; } public void Print(CompileUnit ast) { OnCompileUnit(ast); } #region overridables public virtual void WriteKeyword(string text) { Write(text); } public virtual void WriteOperator(string text) { Write(text); } #endregion #region IAstVisitor Members override public void OnModule(Module m) { Visit(m.Namespace); if (m.Imports.Count > 0) { Visit(m.Imports); WriteLine(); } foreach (var member in m.Members) { Visit(member); WriteLine(); } if (m.Globals != null) Visit(m.Globals.Statements); foreach (var attribute in m.Attributes) WriteModuleAttribute(attribute); foreach (var attribute in m.AssemblyAttributes) WriteAssemblyAttribute(attribute); } private void WriteModuleAttribute(Attribute attribute) { WriteAttribute(attribute, "module: "); WriteLine(); } private void WriteAssemblyAttribute(Attribute attribute) { WriteAttribute(attribute, "assembly: "); WriteLine(); } override public void OnNamespaceDeclaration(NamespaceDeclaration node) { WriteKeyword("namespace"); WriteLine(" {0}", node.Name); WriteLine(); } static bool IsExtendedRE(string s) { return s.IndexOfAny(new char[] { ' ', '\t' }) > -1; } static bool CanBeRepresentedAsQualifiedName(string s) { foreach (char ch in s) if (!char.IsLetterOrDigit(ch) && ch != '_' && ch != '.') return false; return true; } override public void OnImport(Import p) { WriteKeyword("import"); Write(" {0}", p.Namespace); if (null != p.AssemblyReference) { WriteKeyword(" from "); var assemblyRef = p.AssemblyReference.Name; if (CanBeRepresentedAsQualifiedName(assemblyRef)) Write(assemblyRef); else WriteStringLiteral(assemblyRef); } if (p.Expression.NodeType == NodeType.MethodInvocationExpression) { MethodInvocationExpression mie = (MethodInvocationExpression)p.Expression; Write("("); WriteCommaSeparatedList(mie.Arguments); Write(")"); } if (null != p.Alias) { WriteKeyword(" as "); Write(p.Alias.Name); } WriteLine(); } public bool IsWhiteSpaceAgnostic { get { return IsOptionSet(PrintOptions.WSA); } } private void WritePass() { if (!IsWhiteSpaceAgnostic) { WriteIndented(); WriteKeyword("pass"); WriteLine(); } } private void WriteBlockStatements(Block b) { if (b.IsEmpty) { WritePass(); } else { Visit(b.Statements); } } public void WriteBlock(Block b) { BeginBlock(); WriteBlockStatements(b); EndBlock(); } private void BeginBlock() { Indent(); } private void EndBlock() { Dedent(); if (IsWhiteSpaceAgnostic) { WriteEnd(); } } private void WriteEnd() { WriteIndented(); WriteKeyword("end"); WriteLine(); } override public void OnAttribute(Attribute att) { WriteAttribute(att); } override public void OnClassDefinition(ClassDefinition c) { WriteTypeDefinition("class", c); } override public void OnStructDefinition(StructDefinition node) { WriteTypeDefinition("struct", node); } override public void OnInterfaceDefinition(InterfaceDefinition id) { WriteTypeDefinition("interface", id); } override public void OnEnumDefinition(EnumDefinition ed) { WriteTypeDefinition("enum", ed); } override public void OnEvent(Event node) { WriteAttributes(node.Attributes, true); WriteOptionalModifiers(node); WriteKeyword("event "); Write(node.Name); WriteTypeReference(node.Type); WriteLine(); } private static bool IsInterfaceMember(TypeMember node) { return node.ParentNode != null && node.ParentNode.NodeType == NodeType.InterfaceDefinition; } override public void OnField(Field f) { WriteAttributes(f.Attributes, true); WriteModifiers(f); Write(f.Name); WriteTypeReference(f.Type); if (null != f.Initializer) { WriteOperator(" = "); Visit(f.Initializer); } WriteLine(); } override public void OnExplicitMemberInfo(ExplicitMemberInfo node) { Visit(node.InterfaceType); Write("."); } override public void OnProperty(Property node) { bool interfaceMember = IsInterfaceMember(node); WriteAttributes(node.Attributes, true); WriteOptionalModifiers(node); WriteIndented(""); Visit(node.ExplicitInfo); Write(node.Name); if (node.Parameters.Count > 0) { WriteParameterList(node.Parameters, "[", "]"); } WriteTypeReference(node.Type); WriteLine(":"); BeginBlock(); WritePropertyAccessor(node.Getter, "get", interfaceMember); WritePropertyAccessor(node.Setter, "set", interfaceMember); EndBlock(); } private void WritePropertyAccessor(Method method, string name, bool interfaceMember) { if (null == method) return; WriteAttributes(method.Attributes, true); if (interfaceMember) { WriteIndented(); } else { WriteModifiers(method); } WriteKeyword(name); if (interfaceMember) { WriteLine(); } else { WriteLine(":"); WriteBlock(method.Body); } } override public void OnEnumMember(EnumMember node) { WriteAttributes(node.Attributes, true); WriteIndented(node.Name); if (null != node.Initializer) { WriteOperator(" = "); Visit(node.Initializer); } WriteLine(); } override public void OnConstructor(Constructor c) { OnMethod(c); } override public void OnDestructor(Destructor c) { OnMethod(c); } bool IsSimpleClosure(BlockExpression node) { switch (node.Body.Statements.Count) { case 0: return true; case 1: switch (node.Body.Statements[0].NodeType) { case NodeType.IfStatement: return false; case NodeType.WhileStatement: return false; case NodeType.ForStatement: return false; case NodeType.TryStatement: return false; } return true; } return false; } override public void OnBlockExpression(BlockExpression node) { if (IsSimpleClosure(node)) { DisableNewLine(); Write("{ "); if (node.Parameters.Count > 0) { WriteCommaSeparatedList(node.Parameters); Write(" | "); } if (node.Body.IsEmpty) Write("return"); else Visit(node.Body.Statements); Write(" }"); EnableNewLine(); } else { WriteKeyword("def "); WriteParameterList(node.Parameters); WriteTypeReference(node.ReturnType); WriteLine(":"); WriteBlock(node.Body); } } void WriteCallableDefinitionHeader(string keyword, CallableDefinition node) { WriteAttributes(node.Attributes, true); WriteOptionalModifiers(node); WriteKeyword(keyword); IExplicitMember em = node as IExplicitMember; if (null != em) { Visit(em.ExplicitInfo); } Write(node.Name); if (node.GenericParameters.Count > 0) { WriteGenericParameterList(node.GenericParameters); } WriteParameterList(node.Parameters); if (node.ReturnTypeAttributes.Count > 0) { Write(" "); WriteAttributes(node.ReturnTypeAttributes, false); } WriteTypeReference(node.ReturnType); } private void WriteOptionalModifiers(TypeMember node) { if (IsInterfaceMember(node)) { WriteIndented(); } else { WriteModifiers(node); } } override public void OnCallableDefinition(CallableDefinition node) { WriteCallableDefinitionHeader("callable ", node); } override public void OnMethod(Method m) { if (m.IsRuntime) WriteImplementationComment("runtime"); WriteCallableDefinitionHeader("def ", m); if (IsInterfaceMember(m)) { WriteLine(); } else { WriteLine(":"); WriteLocals(m); WriteBlock(m.Body); } } private void WriteImplementationComment(string comment) { WriteIndented("// {0}", comment); WriteLine(); } public override void OnLocal(Local node) { WriteIndented("// Local {0}, {1}, PrivateScope: {2}", node.Name, node.Entity, node.PrivateScope); WriteLine(); } void WriteLocals(Method m) { if (!IsOptionSet(PrintOptions.PrintLocals)) return; Visit(m.Locals); } void WriteTypeReference(TypeReference t) { if (null != t) { WriteKeyword(" as "); Visit(t); } } override public void OnParameterDeclaration(ParameterDeclaration p) { WriteAttributes(p.Attributes, false); if (p.IsByRef) WriteKeyword("ref "); if (IsCallableTypeReferenceParameter(p)) { if (p.IsParamArray) Write("*"); Visit(p.Type); } else { Write(p.Name); WriteTypeReference(p.Type); } } private static bool IsCallableTypeReferenceParameter(ParameterDeclaration p) { var parentNode = p.ParentNode; return parentNode != null && parentNode.NodeType == NodeType.CallableTypeReference; } override public void OnGenericParameterDeclaration(GenericParameterDeclaration gp) { Write(gp.Name); if (gp.BaseTypes.Count > 0 || gp.Constraints != GenericParameterConstraints.None) { Write("("); WriteCommaSeparatedList(gp.BaseTypes); if (gp.Constraints != GenericParameterConstraints.None) { if (gp.BaseTypes.Count != 0) { Write(", "); } WriteGenericParameterConstraints(gp.Constraints); } Write(")"); } } private void WriteGenericParameterConstraints(GenericParameterConstraints constraints) { List<string> constraintStrings = new List<string>(); if ((constraints & GenericParameterConstraints.ReferenceType) != GenericParameterConstraints.None) { constraintStrings.Add("class"); } if ((constraints & GenericParameterConstraints.ValueType) != GenericParameterConstraints.None) { constraintStrings.Add("struct"); } if ((constraints & GenericParameterConstraints.Constructable) != GenericParameterConstraints.None) { constraintStrings.Add("constructor"); } Write(string.Join(", ", constraintStrings.ToArray())); } private KeyValuePair<T, string> CreateTranslation<T>(T value, string translation) { return new KeyValuePair<T, string>(value, translation); } override public void OnTypeofExpression(TypeofExpression node) { Write("typeof("); Visit(node.Type); Write(")"); } override public void OnSimpleTypeReference(SimpleTypeReference t) { Write(t.Name); } override public void OnGenericTypeReference(GenericTypeReference node) { OnSimpleTypeReference(node); WriteGenericArguments(node.GenericArguments); } override public void OnGenericTypeDefinitionReference(GenericTypeDefinitionReference node) { OnSimpleTypeReference(node); Write("[of *"); for (int i = 1; i < node.GenericPlaceholders; i++) { Write(", *"); } Write("]"); } override public void OnGenericReferenceExpression(GenericReferenceExpression node) { Visit(node.Target); WriteGenericArguments(node.GenericArguments); } void WriteGenericArguments(TypeReferenceCollection arguments) { Write("[of "); WriteCommaSeparatedList(arguments); Write("]"); } override public void OnArrayTypeReference(ArrayTypeReference t) { Write("("); Visit(t.ElementType); if (null != t.Rank && t.Rank.Value > 1) { Write(", "); t.Rank.Accept(this); } Write(")"); } override public void OnCallableTypeReference(CallableTypeReference node) { Write("callable("); WriteCommaSeparatedList(node.Parameters); Write(")"); WriteTypeReference(node.ReturnType); } override public void OnMemberReferenceExpression(MemberReferenceExpression e) { Visit(e.Target); Write("."); Write(e.Name); } override public void OnTryCastExpression(TryCastExpression e) { Write("("); Visit(e.Target); WriteTypeReference(e.Type); Write(")"); } override public void OnCastExpression(CastExpression node) { Write("("); Visit(node.Target); WriteKeyword(" cast "); Visit(node.Type); Write(")"); } override public void OnNullLiteralExpression(NullLiteralExpression node) { WriteKeyword("null"); } override public void OnSelfLiteralExpression(SelfLiteralExpression node) { WriteKeyword("self"); } override public void OnSuperLiteralExpression(SuperLiteralExpression node) { WriteKeyword("super"); } override public void OnTimeSpanLiteralExpression(TimeSpanLiteralExpression node) { WriteTimeSpanLiteral(node.Value, _writer); } override public void OnBoolLiteralExpression(BoolLiteralExpression node) { if (node.Value) { WriteKeyword("true"); } else { WriteKeyword("false"); } } override public void OnUnaryExpression(UnaryExpression node) { bool addParens = NeedParensAround(node) && !IsMethodInvocationArg(node) && node.Operator != UnaryOperatorType.SafeAccess; if (addParens) { Write("("); } bool postOperator = AstUtil.IsPostUnaryOperator(node.Operator); if (!postOperator) { WriteOperator(GetUnaryOperatorText(node.Operator)); } Visit(node.Operand); if (postOperator) { WriteOperator(GetUnaryOperatorText(node.Operator)); } if (addParens) { Write(")"); } } private bool IsMethodInvocationArg(UnaryExpression node) { MethodInvocationExpression parent = node.ParentNode as MethodInvocationExpression; return null != parent && node != parent.Target; } override public void OnConditionalExpression(ConditionalExpression e) { Write("("); Visit(e.TrueValue); WriteKeyword(" if "); Visit(e.Condition); WriteKeyword(" else "); Visit(e.FalseValue); Write(")"); } bool NeedParensAround(Expression e) { if (e.ParentNode == null) return false; switch (e.ParentNode.NodeType) { case NodeType.ExpressionStatement: case NodeType.MacroStatement: case NodeType.IfStatement: case NodeType.WhileStatement: case NodeType.UnlessStatement: return false; } return true; } override public void OnBinaryExpression(BinaryExpression e) { bool needsParens = NeedParensAround(e); if (needsParens) { Write("("); } Visit(e.Left); Write(" "); WriteOperator(GetBinaryOperatorText(e.Operator)); Write(" "); if (e.Operator == BinaryOperatorType.TypeTest) { // isa rhs is encoded in a typeof expression Visit(((TypeofExpression)e.Right).Type); } else { Visit(e.Right); } if (needsParens) { Write(")"); } } override public void OnRaiseStatement(RaiseStatement rs) { WriteIndented(); WriteKeyword("raise "); Visit(rs.Exception); Visit(rs.Modifier); WriteLine(); } override public void OnMethodInvocationExpression(MethodInvocationExpression e) { Visit(e.Target); Write("("); WriteCommaSeparatedList(e.Arguments); if (e.NamedArguments.Count > 0) { if (e.Arguments.Count > 0) { Write(", "); } WriteCommaSeparatedList(e.NamedArguments); } Write(")"); } override public void OnArrayLiteralExpression(ArrayLiteralExpression node) { WriteArray(node.Items, node.Type); } override public void OnListLiteralExpression(ListLiteralExpression node) { WriteDelimitedCommaSeparatedList("[", node.Items, "]"); } private void WriteDelimitedCommaSeparatedList(string opening, IEnumerable<Expression> list, string closing) { Write(opening); WriteCommaSeparatedList(list); Write(closing); } public override void OnCollectionInitializationExpression(CollectionInitializationExpression node) { Visit(node.Collection); Write(" "); if (node.Initializer is ListLiteralExpression) WriteDelimitedCommaSeparatedList("{ ", ((ListLiteralExpression) node.Initializer).Items, " }"); else Visit(node.Initializer); } override public void OnGeneratorExpression(GeneratorExpression node) { Write("("); Visit(node.Expression); WriteGeneratorExpressionBody(node); Write(")"); } void WriteGeneratorExpressionBody(GeneratorExpression node) { WriteKeyword(" for "); WriteCommaSeparatedList(node.Declarations); WriteKeyword(" in "); Visit(node.Iterator); Visit(node.Filter); } override public void OnExtendedGeneratorExpression(ExtendedGeneratorExpression node) { Write("("); Visit(node.Items[0].Expression); for (int i=0; i<node.Items.Count; ++i) { WriteGeneratorExpressionBody(node.Items[i]); } Write(")"); } override public void OnSlice(Slice node) { Visit(node.Begin); if (null != node.End || WasOmitted(node.Begin)) { Write(":"); } Visit(node.End); if (null != node.Step) { Write(":"); Visit(node.Step); } } override public void OnSlicingExpression(SlicingExpression node) { Visit(node.Target); Write("["); WriteCommaSeparatedList(node.Indices); Write("]"); } override public void OnHashLiteralExpression(HashLiteralExpression node) { Write("{"); if (node.Items.Count > 0) { Write(" "); WriteCommaSeparatedList(node.Items); Write(" "); } Write("}"); } override public void OnExpressionPair(ExpressionPair pair) { Visit(pair.First); Write(": "); Visit(pair.Second); } override public void OnRELiteralExpression(RELiteralExpression e) { if (IsExtendedRE(e.Value)) { Write("@"); } Write(e.Value); } override public void OnSpliceExpression(SpliceExpression e) { WriteSplicedExpression(e.Expression); } private void WriteSplicedExpression(Expression expression) { WriteOperator("$("); Visit(expression); WriteOperator(")"); } public override void OnStatementTypeMember(StatementTypeMember node) { WriteModifiers(node); Visit(node.Statement); } public override void OnSpliceTypeMember(SpliceTypeMember node) { WriteIndented(); Visit(node.TypeMember); WriteLine(); } public override void OnSpliceTypeDefinitionBody(SpliceTypeDefinitionBody node) { WriteIndented(); WriteSplicedExpression(node.Expression); WriteLine(); } override public void OnSpliceTypeReference(SpliceTypeReference node) { WriteSplicedExpression(node.Expression); } void WriteIndentedOperator(string op) { WriteIndented(); WriteOperator(op); } override public void OnQuasiquoteExpression(QuasiquoteExpression e) { WriteIndentedOperator("[|"); if (e.Node is Expression) { Write(" "); Visit(e.Node); Write(" "); WriteIndentedOperator("|]"); } else { WriteLine(); Indent(); Visit(e.Node); Dedent(); WriteIndentedOperator("|]"); WriteLine(); } } override public void OnStringLiteralExpression(StringLiteralExpression e) { if (e != null && e.Value != null) WriteStringLiteral(e.Value); else WriteKeyword("null"); } override public void OnCharLiteralExpression(CharLiteralExpression e) { WriteKeyword("char"); Write("("); WriteStringLiteral(e.Value); Write(")"); } override public void OnIntegerLiteralExpression(IntegerLiteralExpression e) { Write(e.Value.ToString()); if (e.IsLong) { Write("L"); } } override public void OnDoubleLiteralExpression(DoubleLiteralExpression e) { Write(e.Value.ToString("########0.0##########", CultureInfo.InvariantCulture)); if (e.IsSingle) { Write("F"); } } override public void OnReferenceExpression(ReferenceExpression node) { Write(node.Name); } override public void OnExpressionStatement(ExpressionStatement node) { WriteIndented(); Visit(node.Expression); Visit(node.Modifier); WriteLine(); } override public void OnExpressionInterpolationExpression(ExpressionInterpolationExpression node) { Write("\""); foreach (var arg in node.Expressions) { switch (arg.NodeType) { case NodeType.StringLiteralExpression: WriteStringLiteralContents(((StringLiteralExpression)arg).Value, _writer, false); break; case NodeType.ReferenceExpression: case NodeType.BinaryExpression: Write("$"); Visit(arg); break; default: Write("$("); Visit(arg); Write(")"); break; } } Write("\""); } override public void OnStatementModifier(StatementModifier sm) { Write(" "); WriteKeyword(sm.Type.ToString().ToLower()); Write(" "); Visit(sm.Condition); } override public void OnLabelStatement(LabelStatement node) { WriteIndented(":"); WriteLine(node.Name); } override public void OnGotoStatement(GotoStatement node) { WriteIndented(); WriteKeyword("goto "); Visit(node.Label); Visit(node.Modifier); WriteLine(); } override public void OnMacroStatement(MacroStatement node) { WriteIndented(node.Name); Write(" "); WriteCommaSeparatedList(node.Arguments); if (!node.Body.IsEmpty) { WriteLine(":"); WriteBlock(node.Body); } else { Visit(node.Modifier); WriteLine(); } } override public void OnForStatement(ForStatement fs) { WriteIndented(); WriteKeyword("for "); for (int i=0; i<fs.Declarations.Count; ++i) { if (i > 0) { Write(", "); } Visit(fs.Declarations[i]); } WriteKeyword(" in "); Visit(fs.Iterator); WriteLine(":"); WriteBlock(fs.Block); if(fs.OrBlock != null) { WriteIndented(); WriteKeyword("or:"); WriteLine(); WriteBlock(fs.OrBlock); } if(fs.ThenBlock != null) { WriteIndented(); WriteKeyword("then:"); WriteLine(); WriteBlock(fs.ThenBlock); } } override public void OnTryStatement(TryStatement node) { WriteIndented(); WriteKeyword("try:"); WriteLine(); Indent(); WriteBlockStatements(node.ProtectedBlock); Dedent(); Visit(node.ExceptionHandlers); if (null != node.FailureBlock) { WriteIndented(); WriteKeyword("failure:"); WriteLine(); Indent(); WriteBlockStatements(node.FailureBlock); Dedent(); } if (null != node.EnsureBlock) { WriteIndented(); WriteKeyword("ensure:"); WriteLine(); Indent(); WriteBlockStatements(node.EnsureBlock); Dedent(); } if(IsWhiteSpaceAgnostic) { WriteEnd(); } } override public void OnExceptionHandler(ExceptionHandler node) { WriteIndented(); WriteKeyword("except"); if ((node.Flags & ExceptionHandlerFlags.Untyped) == ExceptionHandlerFlags.None) { if((node.Flags & ExceptionHandlerFlags.Anonymous) == ExceptionHandlerFlags.None) { Write(" "); Visit(node.Declaration); } else { WriteTypeReference(node.Declaration.Type); } } else if((node.Flags & ExceptionHandlerFlags.Anonymous) == ExceptionHandlerFlags.None) { Write(" "); Write(node.Declaration.Name); } if((node.Flags & ExceptionHandlerFlags.Filter) == ExceptionHandlerFlags.Filter) { UnaryExpression unless = node.FilterCondition as UnaryExpression; if(unless != null && unless.Operator == UnaryOperatorType.LogicalNot) { WriteKeyword(" unless "); Visit(unless.Operand); } else { WriteKeyword(" if "); Visit(node.FilterCondition); } } WriteLine(":"); Indent(); WriteBlockStatements(node.Block); Dedent(); } override public void OnUnlessStatement(UnlessStatement node) { WriteConditionalBlock("unless", node.Condition, node.Block); } override public void OnBreakStatement(BreakStatement node) { WriteIndented(); WriteKeyword("break "); Visit(node.Modifier); WriteLine(); } override public void OnContinueStatement(ContinueStatement node) { WriteIndented(); WriteKeyword("continue "); Visit(node.Modifier); WriteLine(); } override public void OnYieldStatement(YieldStatement node) { WriteIndented(); WriteKeyword("yield "); Visit(node.Expression); Visit(node.Modifier); WriteLine(); } override public void OnWhileStatement(WhileStatement node) { WriteConditionalBlock("while", node.Condition, node.Block); if(node.OrBlock != null) { WriteIndented(); WriteKeyword("or:"); WriteLine(); WriteBlock(node.OrBlock); } if(node.ThenBlock != null) { WriteIndented(); WriteKeyword("then:"); WriteLine(); WriteBlock(node.ThenBlock); } } override public void OnIfStatement(IfStatement node) { WriteIfBlock("if ", node); Block elseBlock = WriteElifs(node); if (null != elseBlock) { WriteIndented(); WriteKeyword("else:"); WriteLine(); WriteBlock(elseBlock); } else { if (IsWhiteSpaceAgnostic) { WriteEnd(); } } } private Block WriteElifs(IfStatement node) { Block falseBlock = node.FalseBlock; while (IsElif(falseBlock)) { IfStatement stmt = (IfStatement) falseBlock.Statements[0]; WriteIfBlock("elif ", stmt); falseBlock = stmt.FalseBlock; } return falseBlock; } private void WriteIfBlock(string keyword, IfStatement ifs) { WriteIndented(); WriteKeyword(keyword); Visit(ifs.Condition); WriteLine(":"); Indent(); WriteBlockStatements(ifs.TrueBlock); Dedent(); } private static bool IsElif(Block block) { if (block == null) return false; if (block.Statements.Count != 1) return false; return block.Statements[0] is IfStatement; } override public void OnDeclarationStatement(DeclarationStatement d) { WriteIndented(); Visit(d.Declaration); if (null != d.Initializer) { WriteOperator(" = "); Visit(d.Initializer); } WriteLine(); } override public void OnDeclaration(Declaration d) { Write(d.Name); WriteTypeReference(d.Type); } override public void OnReturnStatement(ReturnStatement r) { WriteIndented(); WriteKeyword("return"); if (r.Expression != null || r.Modifier != null) Write(" "); Visit(r.Expression); Visit(r.Modifier); WriteLine(); } override public void OnUnpackStatement(UnpackStatement us) { WriteIndented(); for (int i=0; i<us.Declarations.Count; ++i) { if (i > 0) { Write(", "); } Visit(us.Declarations[i]); } WriteOperator(" = "); Visit(us.Expression); Visit(us.Modifier); WriteLine(); } override public void OnAwaitExpression(AwaitExpression value) { Write("await ( "); base.OnAwaitExpression(value); Write(")"); } #endregion public static string GetUnaryOperatorText(UnaryOperatorType op) { switch (op) { case UnaryOperatorType.Explode: { return "*"; } case UnaryOperatorType.PostIncrement: case UnaryOperatorType.Increment: return "++"; case UnaryOperatorType.PostDecrement: case UnaryOperatorType.Decrement: return "--"; case UnaryOperatorType.UnaryNegation: return "-"; case UnaryOperatorType.LogicalNot: return "not "; case UnaryOperatorType.OnesComplement: return "~"; case UnaryOperatorType.AddressOf: return "&"; case UnaryOperatorType.Indirection: return "*"; case UnaryOperatorType.SafeAccess: return "?"; } throw new ArgumentException("op"); } public static string GetBinaryOperatorText(BinaryOperatorType op) { switch (op) { case BinaryOperatorType.Assign: return "="; case BinaryOperatorType.Match: return "=~"; case BinaryOperatorType.NotMatch: return "!~"; case BinaryOperatorType.Equality: return "=="; case BinaryOperatorType.Inequality: return "!="; case BinaryOperatorType.Addition: return "+"; case BinaryOperatorType.Exponentiation: return "**"; case BinaryOperatorType.InPlaceAddition: return "+="; case BinaryOperatorType.InPlaceBitwiseAnd: return "&="; case BinaryOperatorType.InPlaceBitwiseOr: return "|="; case BinaryOperatorType.InPlaceSubtraction: return "-="; case BinaryOperatorType.InPlaceMultiply: return "*="; case BinaryOperatorType.InPlaceModulus: return "%="; case BinaryOperatorType.InPlaceExclusiveOr: return "^="; case BinaryOperatorType.InPlaceDivision: return "/="; case BinaryOperatorType.Subtraction: return "-"; case BinaryOperatorType.Multiply: return "*"; case BinaryOperatorType.Division: return "/"; case BinaryOperatorType.GreaterThan: return ">"; case BinaryOperatorType.GreaterThanOrEqual: return ">="; case BinaryOperatorType.LessThan: return "<"; case BinaryOperatorType.LessThanOrEqual: return "<="; case BinaryOperatorType.Modulus: return "%"; case BinaryOperatorType.Member: return "in"; case BinaryOperatorType.NotMember: return "not in"; case BinaryOperatorType.ReferenceEquality: return "is"; case BinaryOperatorType.ReferenceInequality: return "is not"; case BinaryOperatorType.TypeTest: return "isa"; case BinaryOperatorType.Or: return "or"; case BinaryOperatorType.And: return "and"; case BinaryOperatorType.BitwiseOr: return "|"; case BinaryOperatorType.BitwiseAnd: return "&"; case BinaryOperatorType.ExclusiveOr: return "^"; case BinaryOperatorType.ShiftLeft: return "<<"; case BinaryOperatorType.ShiftRight: return ">>"; case BinaryOperatorType.InPlaceShiftLeft: return "<<="; case BinaryOperatorType.InPlaceShiftRight: return ">>="; } throw new NotImplementedException(op.ToString()); } public virtual void WriteStringLiteral(string text) { WriteStringLiteral(text, _writer); } public static void WriteTimeSpanLiteral(TimeSpan value, TextWriter writer) { double days = value.TotalDays; if (days >= 1) { writer.Write(days.ToString(CultureInfo.InvariantCulture) + "d"); } else { double hours = value.TotalHours; if (hours >= 1) { writer.Write(hours.ToString(CultureInfo.InvariantCulture) + "h"); } else { double minutes = value.TotalMinutes; if (minutes >= 1) { writer.Write(minutes.ToString(CultureInfo.InvariantCulture) + "m"); } else { double seconds = value.TotalSeconds; if (seconds >= 1) { writer.Write(seconds.ToString(CultureInfo.InvariantCulture) + "s"); } else { writer.Write(value.TotalMilliseconds.ToString(CultureInfo.InvariantCulture) + "ms"); } } } } } public static void WriteStringLiteral(string text, TextWriter writer) { writer.Write("'"); WriteStringLiteralContents(text, writer); writer.Write("'"); } public static void WriteStringLiteralContents(string text, TextWriter writer) { WriteStringLiteralContents(text, writer, true); } public static void WriteStringLiteralContents(string text, TextWriter writer, bool single) { foreach (char ch in text) { switch (ch) { case '\r': { writer.Write("\\r"); break; } case '\n': { writer.Write("\\n"); break; } case '\t': { writer.Write("\\t"); break; } case '\\': { writer.Write("\\\\"); break; } case '\a': { writer.Write(@"\a"); break; } case '\b': { writer.Write(@"\b"); break; } case '\f': { writer.Write(@"\f"); break; } case '\0': { writer.Write(@"\0"); break; } case '\'': { if (single) { writer.Write("\\'"); } else { writer.Write(ch); } break; } case '"': { if (!single) { writer.Write("\\\""); } else { writer.Write(ch); } break; } default: { writer.Write(ch); break; } } } } void WriteConditionalBlock(string keyword, Expression condition, Block block) { WriteIndented(); WriteKeyword(keyword + " "); Visit(condition); WriteLine(":"); WriteBlock(block); } void WriteParameterList(ParameterDeclarationCollection items) { WriteParameterList(items, "(", ")"); } void WriteParameterList(ParameterDeclarationCollection items, string st, string ed) { Write(st); int i = 0; foreach (ParameterDeclaration item in items) { if (i > 0) { Write(", "); } if (item.IsParamArray) { Write("*"); } Visit(item); ++i; } Write(ed); } void WriteGenericParameterList(GenericParameterDeclarationCollection items) { Write("[of "); WriteCommaSeparatedList(items); Write("]"); } void WriteAttribute(Attribute attribute) { WriteAttribute(attribute, null); } void WriteAttribute(Attribute attribute, string prefix) { WriteIndented("["); if (null != prefix) { Write(prefix); } Write(attribute.Name); if (attribute.Arguments.Count > 0 || attribute.NamedArguments.Count > 0) { Write("("); WriteCommaSeparatedList(attribute.Arguments); if (attribute.NamedArguments.Count > 0) { if (attribute.Arguments.Count > 0) { Write(", "); } WriteCommaSeparatedList(attribute.NamedArguments); } Write(")"); } Write("]"); } void WriteAttributes(AttributeCollection attributes, bool addNewLines) { foreach (Boo.Lang.Compiler.Ast.Attribute attribute in attributes) { Visit(attribute); if (addNewLines) { WriteLine(); } else { Write(" "); } } } void WriteModifiers(TypeMember member) { WriteIndented(); if (member.IsPartial) WriteKeyword("partial "); if (member.IsPublic) WriteKeyword("public "); else if (member.IsProtected) WriteKeyword("protected "); else if (member.IsPrivate) WriteKeyword("private "); else if (member.IsInternal) WriteKeyword("internal "); if (member.IsStatic) WriteKeyword("static "); else if (member.IsOverride) WriteKeyword("override "); else if (member.IsModifierSet(TypeMemberModifiers.Virtual)) WriteKeyword("virtual "); else if (member.IsModifierSet(TypeMemberModifiers.Abstract)) WriteKeyword("abstract "); if (member.IsFinal) WriteKeyword("final "); if (member.IsNew) WriteKeyword("new "); if (member.HasTransientModifier) WriteKeyword("transient "); } virtual protected void WriteTypeDefinition(string keyword, TypeDefinition td) { WriteAttributes(td.Attributes, true); WriteModifiers(td); WriteIndented(); WriteKeyword(keyword); Write(" "); var splice = td.ParentNode as SpliceTypeMember; if (splice != null) WriteSplicedExpression(splice.NameExpression); else Write(td.Name); if (td.GenericParameters.Count != 0) { WriteGenericParameterList(td.GenericParameters); } if (td.BaseTypes.Count > 0) { Write("("); WriteCommaSeparatedList<TypeReference>(td.BaseTypes); Write(")"); } WriteLine(":"); BeginBlock(); if (td.Members.Count > 0) { foreach (TypeMember member in td.Members) { WriteLine(); Visit(member); } } else { WritePass(); } EndBlock(); } bool WasOmitted(Expression node) { return null != node && NodeType.OmittedExpression == node.NodeType; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.ComponentModel.Composition.Factories; using System.ComponentModel.Composition.Primitives; using System.IO; using System.Linq; using System.Threading; using System.UnitTesting; using Xunit; namespace System.ComponentModel.Composition.Hosting { public class AggregateCatalogTest { [Fact] public void Constructor1_ShouldNotThrow() { new AggregateCatalog(); } [Fact] public void Constructor1_ShouldSetCatalogsPropertyToEmpty() { var catalog = new AggregateCatalog(); Assert.Empty(catalog.Catalogs); } [Fact] [ActiveIssue(812029)] public void Constructor1_ShouldSetPartsPropertyToEmpty() { var catalog = new AggregateCatalog(); Assert.Empty(catalog.Parts); } [Fact] public void Constructor3_NullAsCatalogsArgument_ShouldSetCatalogsPropertyToEmpty() { var catalog = new AggregateCatalog((IEnumerable<ComposablePartCatalog>)null); Assert.Empty(catalog.Catalogs); } [Fact] public void Constructor3_EmptyIEnumerableAsCatalogsArgument_ShouldSetCatalogsPropertyToEmpty() { var catalog = new AggregateCatalog(Enumerable.Empty<ComposablePartCatalog>()); Assert.Empty(catalog.Catalogs); } [Fact] [ActiveIssue(812029)] public void Constructor3_NullAsCatalogsArgument_ShouldSetPartsPropertyToEmpty() { var catalog = new AggregateCatalog((IEnumerable<ComposablePartCatalog>)null); Assert.Empty(catalog.Parts); } [Fact] [ActiveIssue(812029)] public void Constructor3_EmptyIEnumerableAsCatalogsArgument_ShouldSetPartsPropertyToEmpty() { var catalog = new AggregateCatalog(Enumerable.Empty<ComposablePartCatalog>()); Assert.Empty(catalog.Parts); } [Fact] [ActiveIssue(25498)] public void Constructor3_ArrayWithNullAsCatalogsArgument_ShouldThrowArgument() { var catalogs = new ComposablePartCatalog[] { null }; AssertExtensions.Throws<ArgumentException>("catalogs", () => { new AggregateCatalog(catalogs); }); } [Fact] public void Catalogs_WhenCatalogDisposed_ShouldThrowObjectDisposed() { var catalog = CreateAggregateCatalog(); catalog.Dispose(); ExceptionAssert.ThrowsDisposed(catalog, () => { var catalogs = catalog.Catalogs; }); } [Fact] public void Parts_WhenCatalogDisposed_ShouldThrowObjectDisposed() { var catalog = CreateAggregateCatalog(); catalog.Dispose(); ExceptionAssert.ThrowsDisposed(catalog, () => { var parts = catalog.Parts; }); } [Fact] public void GetExports_WhenCatalogDisposed_ShouldThrowObjectDisposed() { var catalog = CreateAggregateCatalog(); catalog.Dispose(); var definition = ImportDefinitionFactory.Create(); ExceptionAssert.ThrowsDisposed(catalog, () => { catalog.GetExports(definition); }); } [Fact] [ActiveIssue(25498)] public void GetExports_NullAsConstraintArgument_ShouldThrowArgumentNull() { var catalog = CreateAggregateCatalog(); AssertExtensions.Throws<ArgumentNullException>("definition", () => { catalog.GetExports((ImportDefinition)null); }); } [Fact] public void Dispose_ShouldNotThrow() { using (var catalog = CreateAggregateCatalog()) { } } [Fact] public void Dispose_CanBeCalledMultipleTimes() { var catalog = CreateAggregateCatalog(); catalog.Dispose(); catalog.Dispose(); catalog.Dispose(); } [Fact] public void EnumeratePartsProperty_ShouldSucceed() { using (var catalog = new AggregateCatalog( new TypeCatalog(typeof(SharedPartStuff)), new TypeCatalog(typeof(SharedPartStuff)), new TypeCatalog(typeof(SharedPartStuff)), new TypeCatalog(typeof(SharedPartStuff)), new TypeCatalog(typeof(SharedPartStuff)), new TypeCatalog(typeof(SharedPartStuff)))) { Assert.True(catalog.Catalogs.Count() == 6); Assert.True(catalog.Parts.Count() == 6); } } [Fact] public void MutableCatalogNotifications() { int step = 0; int changedStep = 0; var catalog = new AggregateCatalog(); var typePartCatalog = new TypeCatalog(typeof(SharedPartStuff)); var typePartCatalog1 = new TypeCatalog(typeof(SharedPartStuff)); var typePartCatalog2 = new TypeCatalog(typeof(SharedPartStuff)); var typePartCatalog3 = new TypeCatalog(typeof(SharedPartStuff)); var typePartCatalog4 = new TypeCatalog(typeof(SharedPartStuff)); var typePartCatalog5 = new TypeCatalog(typeof(SharedPartStuff)); // Smoke test on inner collection catalog.Catalogs.Add(typePartCatalog); catalog.Catalogs.Remove(typePartCatalog); catalog.Catalogs.Clear(); Assert.True(catalog.Catalogs.Count == 0); // Add notifications catalog.Changed += delegate (object source, ComposablePartCatalogChangeEventArgs args) { // Local code ++step; ++step; changedStep = step; }; //Add something then verify counters catalog.Catalogs.Add(typePartCatalog); Assert.True(catalog.Catalogs.Count == 1); Assert.True(changedStep == 2); // Reset counters step = changedStep = 0; // Remove something then verify counters catalog.Catalogs.Remove(typePartCatalog); Assert.True(catalog.Catalogs.Count == 0); Assert.True(changedStep == 2); //Now Add it back catalog.Catalogs.Add(typePartCatalog); Assert.True(catalog.Catalogs.Count == 1); step = changedStep = 0; // Now clear the collection and verify counters catalog.Catalogs.Clear(); Assert.True(catalog.Catalogs.Count == 0); Assert.True(changedStep == 2); // Now remove a non existent item and verify counters step = changedStep = 0; bool removed = catalog.Catalogs.Remove(typePartCatalog); Assert.True(removed == false); Assert.True(changedStep == 0); // Add a bunch step = changedStep = 0; catalog.Catalogs.Add(typePartCatalog); Assert.True(catalog.Catalogs.Count == 1); Assert.True(changedStep == 2); catalog.Catalogs.Add(typePartCatalog1); Assert.True(catalog.Catalogs.Count == 2); Assert.True(changedStep == 4); catalog.Catalogs.Add(typePartCatalog2); catalog.Catalogs.Add(typePartCatalog3); catalog.Catalogs.Add(typePartCatalog4); catalog.Catalogs.Add(typePartCatalog5); Assert.True(catalog.Catalogs.Count == 6); Assert.True(changedStep == 12); removed = catalog.Catalogs.Remove(typePartCatalog3); Assert.True(catalog.Catalogs.Count == 5); Assert.True(removed == true); Assert.True(changedStep == 14); removed = catalog.Catalogs.Remove(typePartCatalog2); removed = catalog.Catalogs.Remove(typePartCatalog1); removed = catalog.Catalogs.Remove(typePartCatalog4); removed = catalog.Catalogs.Remove(typePartCatalog); removed = catalog.Catalogs.Remove(typePartCatalog5); Assert.True(catalog.Catalogs.Count == 0); Assert.True(removed == true); Assert.True(changedStep == 24); // Add and then clear a lot step = changedStep = 0; catalog.Catalogs.Add(typePartCatalog); catalog.Catalogs.Add(typePartCatalog1); catalog.Catalogs.Add(typePartCatalog2); catalog.Catalogs.Add(typePartCatalog3); catalog.Catalogs.Add(typePartCatalog4); catalog.Catalogs.Add(typePartCatalog5); Assert.True(catalog.Catalogs.Count == 6); Assert.True(changedStep == 12); catalog.Catalogs.Clear(); Assert.True(catalog.Catalogs.Count == 0); step = changedStep = 0; int step2 = 100; int changedStep2 = 0; catalog.Changed += delegate (object source, ComposablePartCatalogChangeEventArgs args) { // Local code --step2; --step2; changedStep2 = step2; }; catalog.Catalogs.Add(typePartCatalog); Assert.True(catalog.Catalogs.Count == 1); Assert.True(changedStep == 2); Assert.True(changedStep2 == 98); catalog.Catalogs.Add(typePartCatalog1); Assert.True(catalog.Catalogs.Count == 2); Assert.True(changedStep == 4); Assert.True(changedStep2 == 96); catalog.Catalogs.Remove(typePartCatalog); Assert.True(catalog.Catalogs.Count == 1); Assert.True(changedStep == 6); Assert.True(changedStep2 == 94); catalog.Catalogs.Clear(); Assert.True(catalog.Catalogs.Count == 0); Assert.True(changedStep == 8); Assert.True(changedStep2 == 92); } [Fact] public void DisposeAggregatingCatalog() { int changedNotification = 0; var typePartCatalog1 = new TypeCatalog(typeof(SharedPartStuff)); var typePartCatalog2 = new TypeCatalog(typeof(SharedPartStuff)); var typePartCatalog3 = new TypeCatalog(typeof(SharedPartStuff)); var assemblyPartCatalog1 = new AssemblyCatalog(typeof(SharedPartStuff).Assembly); var assemblyPartCatalog2 = new AssemblyCatalog(typeof(SharedPartStuff).Assembly); var assemblyPartCatalog3 = new AssemblyCatalog(typeof(SharedPartStuff).Assembly); var dirPartCatalog1 = new DirectoryCatalog(Path.GetTempPath()); var dirPartCatalog2 = new DirectoryCatalog(Path.GetTempPath()); var dirPartCatalog3 = new DirectoryCatalog(Path.GetTempPath()); using (var catalog = new AggregateCatalog()) { catalog.Catalogs.Add(typePartCatalog1); catalog.Catalogs.Add(typePartCatalog2); catalog.Catalogs.Add(typePartCatalog3); catalog.Catalogs.Add(assemblyPartCatalog1); catalog.Catalogs.Add(assemblyPartCatalog2); catalog.Catalogs.Add(assemblyPartCatalog3); catalog.Catalogs.Add(dirPartCatalog1); catalog.Catalogs.Add(dirPartCatalog2); catalog.Catalogs.Add(dirPartCatalog3); // Add notifications catalog.Changed += delegate (object source, ComposablePartCatalogChangeEventArgs args) { // Local code ++changedNotification; }; } Assert.True(changedNotification == 0); //Ensure that the other catalogs are ExceptionAssert.ThrowsDisposed(typePartCatalog1, () => { var iEnum = typePartCatalog1.Parts.GetEnumerator(); }); ExceptionAssert.ThrowsDisposed(typePartCatalog2, () => { var iEnum = typePartCatalog2.Parts.GetEnumerator(); }); ExceptionAssert.ThrowsDisposed(typePartCatalog3, () => { var iEnum = typePartCatalog3.Parts.GetEnumerator(); }); //Ensure that the other catalogs are ExceptionAssert.ThrowsDisposed(assemblyPartCatalog1, () => { var iEnum = assemblyPartCatalog1.Parts.GetEnumerator(); }); ExceptionAssert.ThrowsDisposed(assemblyPartCatalog2, () => { var iEnum = assemblyPartCatalog2.Parts.GetEnumerator(); }); ExceptionAssert.ThrowsDisposed(assemblyPartCatalog3, () => { var iEnum = assemblyPartCatalog3.Parts.GetEnumerator(); }); //Ensure that the other catalogs are ExceptionAssert.ThrowsDisposed(dirPartCatalog1, () => { var iEnum = dirPartCatalog1.Parts.GetEnumerator(); }); ExceptionAssert.ThrowsDisposed(dirPartCatalog2, () => { var iEnum = dirPartCatalog2.Parts.GetEnumerator(); }); ExceptionAssert.ThrowsDisposed(dirPartCatalog3, () => { var iEnum = dirPartCatalog3.Parts.GetEnumerator(); }); } [Fact] [ActiveIssue(514749)] public void MutableMultithreadedEnumerations() { var catalog = new AggregateCatalog(); ThreadStart func = delegate () { var typePart = new TypeCatalog(typeof(SharedPartStuff)); var typePart1 = new TypeCatalog(typeof(SharedPartStuff)); var typePart2 = new TypeCatalog(typeof(SharedPartStuff)); var typePart3 = new TypeCatalog(typeof(SharedPartStuff)); var typePart4 = new TypeCatalog(typeof(SharedPartStuff)); var typePart5 = new TypeCatalog(typeof(SharedPartStuff)); for (int i = 0; i < 100; i++) { catalog.Catalogs.Add(typePart); catalog.Catalogs.Add(typePart1); catalog.Catalogs.Add(typePart2); catalog.Catalogs.Add(typePart3); catalog.Catalogs.Add(typePart4); catalog.Catalogs.Add(typePart5); Assert.True(catalog.Catalogs.Count >= 6); for (int k = 0; k < 5; k++) { int j; // Ensure that iterating the returned queryable is okay even though there are many threads mutationg it // We are really just looking to ensure that ollection changed exceptions are not thrown j = 0; var iq = catalog.Parts.GetEnumerator(); while (iq.MoveNext()) { ++j; } Assert.True(j >= 6); // Ensure that iterating the returned enumerator is okay even though there are many threads mutationg it // We are really just looking to ensure that collection changed exceptions are not thrown j = 0; var ie = catalog.Catalogs.GetEnumerator(); while (ie.MoveNext()) { ++j; } Assert.True(j >= 6); } catalog.Catalogs.Remove(typePart); catalog.Catalogs.Remove(typePart1); catalog.Catalogs.Remove(typePart2); catalog.Catalogs.Remove(typePart3); catalog.Catalogs.Remove(typePart4); catalog.Catalogs.Remove(typePart5); } }; Thread[] threads = new Thread[100]; for (int i = 0; i < threads.Length; i++) { threads[i] = new Thread(func); } for (int i = 0; i < threads.Length; i++) { threads[i].Start(); } for (int i = 0; i < threads.Length; i++) { threads[i].Join(); } Assert.True(catalog.Catalogs.Count == 0); } private static void CreateMainAndOtherChildren( out AggregateCatalog[] mainChildren, out AggregateCatalog[] otherChildren, out TypeCatalog[] componentCatalogs) { componentCatalogs = new TypeCatalog[] { new TypeCatalog(typeof(SharedPartStuff)), new TypeCatalog(typeof(SharedPartStuff)), new TypeCatalog(typeof(SharedPartStuff)) }; // Create our child catalogs mainChildren = new AggregateCatalog[5]; for (int i = 0; i < mainChildren.Length; i++) { mainChildren[i] = new AggregateCatalog(componentCatalogs); } otherChildren = new AggregateCatalog[5]; for (int i = 0; i < otherChildren.Length; i++) { otherChildren[i] = new AggregateCatalog(componentCatalogs); } } [Fact] [ActiveIssue(812029)] public void AggregatingCatalogAddAndRemoveChildren() { int changedCount = 0; int typesChanged = 0; EventHandler<ComposablePartCatalogChangeEventArgs> onChanged = delegate (object sender, ComposablePartCatalogChangeEventArgs e) { ++changedCount; typesChanged += e.AddedDefinitions.Concat(e.RemovedDefinitions).Count(); }; // Create our child catalogs AggregateCatalog[] mainChildren; AggregateCatalog[] otherChildren; TypeCatalog[] componentCatalogs; CreateMainAndOtherChildren(out mainChildren, out otherChildren, out componentCatalogs); var parent = new AggregateCatalog(mainChildren); parent.Changed += onChanged; for (int i = 0; i < otherChildren.Length; i++) { parent.Catalogs.Add(otherChildren[i]); } Assert.Equal(otherChildren.Length, changedCount); Assert.Equal(otherChildren.Length * 3, typesChanged); changedCount = 0; typesChanged = 0; parent.Catalogs.Remove(otherChildren[0]); parent.Catalogs.Remove(otherChildren[1]); Assert.Equal(2, changedCount); Assert.Equal(2 * 3, typesChanged); changedCount = 0; typesChanged = 0; parent.Catalogs.Add(otherChildren[0]); parent.Catalogs.Add(otherChildren[1]); Assert.Equal(2, changedCount); Assert.Equal(2 * 3, typesChanged); changedCount = 0; typesChanged = 0; parent.Catalogs.Clear(); Assert.Equal(1, changedCount); Assert.Equal((mainChildren.Length + otherChildren.Length) * 3, typesChanged); changedCount = 0; typesChanged = 0; // These have already been removed and so I should be able remove components from them without recieving notifications otherChildren[0].Catalogs.Remove(componentCatalogs[0]); otherChildren[1].Catalogs.Remove(componentCatalogs[1]); Assert.Equal(0, changedCount); Assert.Equal(0, typesChanged); // These have already been Cleared and so I should be able remove components from them without recieving notifications otherChildren[3].Catalogs.Remove(componentCatalogs[0]); otherChildren[4].Catalogs.Remove(componentCatalogs[1]); Assert.Equal(0, changedCount); } [Fact] [ActiveIssue(812029)] public void AggregatingCatalogAddAndRemoveNestedChildren() { int changedCount = 0; int typesChanged = 0; EventHandler<ComposablePartCatalogChangeEventArgs> onChanged = delegate (object sender, ComposablePartCatalogChangeEventArgs e) { ++changedCount; typesChanged += e.AddedDefinitions.Concat(e.RemovedDefinitions).Count(); }; // Create our child catalogs AggregateCatalog[] mainChildren; AggregateCatalog[] otherChildren; TypeCatalog[] componentCatalogs; CreateMainAndOtherChildren(out mainChildren, out otherChildren, out componentCatalogs); var parent = new AggregateCatalog(mainChildren); parent.Changed += onChanged; for (int i = 0; i < otherChildren.Length; i++) { parent.Catalogs.Add(otherChildren[i]); } Assert.Equal(otherChildren.Length, changedCount); Assert.Equal(otherChildren.Length * 3, typesChanged); changedCount = 0; typesChanged = 0; otherChildren[0].Catalogs.Remove(componentCatalogs[0]); otherChildren[1].Catalogs.Remove(componentCatalogs[1]); Assert.Equal(2, changedCount); Assert.Equal(2, typesChanged); changedCount = 0; typesChanged = 0; otherChildren[0].Catalogs.Add(componentCatalogs[0]); otherChildren[1].Catalogs.Add(componentCatalogs[1]); Assert.Equal(2, changedCount); Assert.Equal(2, typesChanged); changedCount = 0; typesChanged = 0; otherChildren[1].Catalogs.Clear(); Assert.Equal(1, changedCount); Assert.Equal(componentCatalogs.Length, typesChanged); } [Fact] [ActiveIssue(812029)] public void AggregatingDisposedAndNotifications() { int changedCount = 0; int typesChanged = 0; EventHandler<ComposablePartCatalogChangeEventArgs> onChanged = delegate (object sender, ComposablePartCatalogChangeEventArgs e) { ++changedCount; typesChanged += e.AddedDefinitions.Concat(e.RemovedDefinitions).Count(); }; // Create our child catalogs AggregateCatalog[] mainChildren; AggregateCatalog[] otherChildren; TypeCatalog[] componentCatalogs; CreateMainAndOtherChildren(out mainChildren, out otherChildren, out componentCatalogs); var parent = new AggregateCatalog(mainChildren); parent.Changed += onChanged; for (int i = 0; i < otherChildren.Length; i++) { parent.Catalogs.Add(otherChildren[i]); } Assert.Equal(otherChildren.Length, changedCount); Assert.Equal(otherChildren.Length * 3, typesChanged); changedCount = 0; typesChanged = 0; parent.Dispose(); Assert.Equal(0, changedCount); Assert.Equal(0, typesChanged); //Ensure that the children are also disposed ExceptionAssert.ThrowsDisposed(otherChildren[0], () => { otherChildren[0].Catalogs.Remove(componentCatalogs[0]); }); //Ensure that the children are also disposed ExceptionAssert.ThrowsDisposed(otherChildren[4], () => { otherChildren[4].Catalogs.Remove(componentCatalogs[0]); }); Assert.Equal(0, changedCount); Assert.Equal(0, typesChanged); } [Fact] public void AggregatingCatalogParmsConstructorAggregateAggregateCatalogs() { var aggCatalog1 = new AggregateCatalog(); var aggCatalog2 = new AggregateCatalog(); var aggCatalog3 = new AggregateCatalog(); // Construct with one catalog parameter var catalog = new AggregateCatalog(aggCatalog1); Assert.True(catalog.Catalogs.Count == 1); // Construct with two catalog parameters catalog = new AggregateCatalog(aggCatalog1, aggCatalog2); Assert.True(catalog.Catalogs.Count == 2); // Construct with three catalog parameters catalog = new AggregateCatalog(aggCatalog1, aggCatalog2, aggCatalog3); Assert.True(catalog.Catalogs.Count == 3); } [Fact] public void AggregatingCatalogParmsConstructorAggregateAssemblyCatalogs() { var assemblyCatalog1 = new AssemblyCatalog(typeof(SharedPartStuff).Assembly); var assemblyCatalog2 = new AssemblyCatalog(typeof(SharedPartStuff).Assembly); var assemblyCatalog3 = new AssemblyCatalog(typeof(SharedPartStuff).Assembly); // Construct with one catalog parameter var catalog = new AggregateCatalog(assemblyCatalog1); Assert.True(catalog.Catalogs.Count == 1); // Construct with two catalog parameters catalog = new AggregateCatalog(assemblyCatalog1, assemblyCatalog2); Assert.True(catalog.Catalogs.Count == 2); // Construct with three catalog parameters catalog = new AggregateCatalog(assemblyCatalog1, assemblyCatalog2, assemblyCatalog3); Assert.True(catalog.Catalogs.Count == 3); } [Fact] public void AggregatingCatalogParmsConstructorMixedCatalogs() { var typePartCatalog1 = new TypeCatalog(typeof(SharedPartStuff)); var assemblyCatalog2 = new AssemblyCatalog(typeof(SharedPartStuff).Assembly); var typePartCatalog3 = new TypeCatalog(typeof(SharedPartStuff)); // Construct with three catalog parameters var catalog = new AggregateCatalog(typePartCatalog1, assemblyCatalog2, typePartCatalog3); Assert.True(catalog.Catalogs.Count == 3); } [Fact] public void AggregatingCatalogRaisesChangesForCatalogsPassedToConstructor() { var subCatalog = CreateAggregateCatalog(); var testCatalog = new AggregateCatalog(subCatalog); bool changedCalled = false; testCatalog.Changed += delegate { changedCalled = true; }; subCatalog.Catalogs.Add(new TypeCatalog(typeof(SharedPartStuff))); Assert.True(changedCalled); } private AggregateCatalog CreateAggregateCatalog() { return new AggregateCatalog(); } [Fact] [ActiveIssue(812029)] public void CatalogEvents_AggregateAddRemove() { var catalog = new AggregateCatalog(); AggregateTests(catalog, catalog); } [Fact] [ActiveIssue(812029)] public void CatalogEvents_DeepAggregateAddRemove() { var deepCatalog = new AggregateCatalog(); var midCatalog = new AggregateCatalog(new ComposablePartCatalog[] { deepCatalog }); var topCatalog = new AggregateCatalog(new ComposablePartCatalog[] { midCatalog }); AggregateTests(topCatalog, deepCatalog); } private void AggregateTests(AggregateCatalog watchedCatalog, AggregateCatalog modifiedCatalog) { var fooCatalog = new TypeCatalog(new Type[] { typeof(FooExporter) }); var barCatalog = new TypeCatalog(new Type[] { typeof(BarExporter) }); var bothCatalog = new TypeCatalog(new Type[] { typeof(FooExporter), typeof(BarExporter) }); var catalogListener = new CatalogListener(watchedCatalog, modifiedCatalog); catalogListener.VerifyAdd(fooCatalog, typeof(FooExporter)); catalogListener.VerifyAdd(barCatalog, typeof(BarExporter)); catalogListener.VerifyRemove(fooCatalog, typeof(FooExporter)); catalogListener.VerifyRemove(barCatalog, typeof(BarExporter)); catalogListener.VerifyAdd(bothCatalog, typeof(FooExporter), typeof(BarExporter)); catalogListener.VerifyClear(typeof(FooExporter), typeof(BarExporter)); catalogListener.VerifyAdd(bothCatalog, typeof(FooExporter), typeof(BarExporter)); catalogListener.VerifyRemove(bothCatalog, typeof(FooExporter), typeof(BarExporter)); } public interface IFoo { } public interface IBar { } [Export(typeof(IFoo))] public class FooExporter : IFoo { } [Export(typeof(IBar))] public class BarExporter : IBar { } public class CatalogListener { private AggregateCatalog _watchedCatalog; private AggregateCatalog _modifiedCatalog; private string[] _expectedAdds; private string[] _expectedRemoves; private int _changedEventCount; private int _changingEventCount; public CatalogListener(AggregateCatalog watchCatalog, AggregateCatalog modifiedCatalog) { watchCatalog.Changing += OnChanging; watchCatalog.Changed += OnChanged; this._watchedCatalog = watchCatalog; this._modifiedCatalog = modifiedCatalog; } public void VerifyAdd(ComposablePartCatalog catalogToAdd, params Type[] expectedTypesAdded) { this._expectedAdds = GetDisplayNames(expectedTypesAdded); this._modifiedCatalog.Catalogs.Add(catalogToAdd); Assert.True(this._changingEventCount == 1); Assert.True(this._changedEventCount == 1); ResetState(); } public void VerifyRemove(ComposablePartCatalog catalogToRemove, params Type[] expectedTypesRemoved) { this._expectedAdds = null; this._expectedRemoves = GetDisplayNames(expectedTypesRemoved); this._modifiedCatalog.Catalogs.Remove(catalogToRemove); Assert.True(this._changingEventCount == 1); Assert.True(this._changedEventCount == 1); ResetState(); } public void VerifyClear(params Type[] expectedTypesRemoved) { this._expectedAdds = null; this._expectedRemoves = GetDisplayNames(expectedTypesRemoved); this._modifiedCatalog.Catalogs.Clear(); Assert.True(this._changingEventCount == 1); Assert.True(this._changedEventCount == 1); ResetState(); } public void OnChanging(object sender, ComposablePartCatalogChangeEventArgs args) { Assert.True(this._expectedAdds != null || this._expectedRemoves != null); if (this._expectedAdds == null) { Assert.Empty(args.AddedDefinitions); } else { EqualityExtensions.CheckSequenceEquals(this._expectedAdds, GetDisplayNames(args.AddedDefinitions)); } if (this._expectedRemoves == null) { Assert.Empty(args.RemovedDefinitions); } else { EqualityExtensions.CheckSequenceEquals(this._expectedRemoves, GetDisplayNames(args.RemovedDefinitions)); } Assert.False(ContainsChanges(), "The catalog should NOT contain the changes yet"); this._changingEventCount++; } public void OnChanged(object sender, ComposablePartCatalogChangeEventArgs args) { Assert.True(this._expectedAdds != null || this._expectedRemoves != null); if (this._expectedAdds == null) { Assert.Empty(args.AddedDefinitions); } else { EqualityExtensions.CheckSequenceEquals(this._expectedAdds, GetDisplayNames(args.AddedDefinitions)); } if (this._expectedRemoves == null) { Assert.Empty(args.RemovedDefinitions); } else { EqualityExtensions.CheckSequenceEquals(this._expectedRemoves, GetDisplayNames(args.RemovedDefinitions)); } Assert.Null(args.AtomicComposition); Assert.True(ContainsChanges()); this._changedEventCount++; } private bool ContainsChanges() { var allParts = GetDisplayNames(this._watchedCatalog.Parts); if (this._expectedAdds != null) { foreach (var add in this._expectedAdds) { if (!allParts.Contains(add)) { return false; } } } if (this._expectedRemoves != null) { foreach (var remove in this._expectedRemoves) { if (allParts.Contains(remove)) { return false; } } } return true; } private void ResetState() { this._expectedAdds = null; this._expectedRemoves = null; this._changedEventCount = 0; this._changingEventCount = 0; } private static string[] GetDisplayNames(IEnumerable<ComposablePartDefinition> definitions) { return definitions.OfType<ICompositionElement>().Select(p => p.DisplayName).ToArray(); } private static string[] GetDisplayNames(IEnumerable<Type> types) { return GetDisplayNames(types.Select(t => AttributedModelServices.CreatePartDefinition(t, null))); } } [Export] [PartCreationPolicy(CreationPolicy.Shared)] public class SharedPartStuff { Guid id = Guid.NewGuid(); public override string ToString() { return id.ToString(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using OpenTK.Graphics.OpenGL; namespace SageCS.Core.Graphics { class Shader { public int ProgramID = -1; public int VShaderID = -1; public int FShaderID = -1; public int AttributeCount = 0; public int UniformCount = 0; public Dictionary<String, AttributeInfo> Attributes = new Dictionary<string, AttributeInfo>(); public Dictionary<String, UniformInfo> Uniforms = new Dictionary<string, UniformInfo>(); public Dictionary<String, uint> Buffers = new Dictionary<string, uint>(); public Shader(Stream vshader, Stream fshader) { ProgramID = GL.CreateProgram(); loadShader(new StreamReader(vshader).ReadToEnd(), ShaderType.VertexShader, out VShaderID); loadShader(new StreamReader(fshader).ReadToEnd(), ShaderType.FragmentShader, out FShaderID); Link(); GenBuffers(); } public Shader(String vshader, String fshader, bool fromFile = false) { ProgramID = GL.CreateProgram(); if (fromFile) { LoadShaderFromFile(vshader, ShaderType.VertexShader); LoadShaderFromFile(fshader, ShaderType.FragmentShader); } else { LoadShaderFromString(vshader, ShaderType.VertexShader); LoadShaderFromString(fshader, ShaderType.FragmentShader); } Link(); GenBuffers(); } public void Link() { GL.LinkProgram(ProgramID); Console.WriteLine(GL.GetProgramInfoLog(ProgramID)); GL.GetProgram(ProgramID, GetProgramParameterName.ActiveAttributes, out AttributeCount); GL.GetProgram(ProgramID, GetProgramParameterName.ActiveUniforms, out UniformCount); for (int i = 0; i < AttributeCount; i++) { AttributeInfo info = new AttributeInfo(); int length = 0; StringBuilder name = new StringBuilder(); GL.GetActiveAttrib(ProgramID, i, 256, out length, out info.size, out info.type, name); info.name = name.ToString(); info.address = GL.GetAttribLocation(ProgramID, info.name); Attributes.Add(name.ToString(), info); } for (int i = 0; i < UniformCount; i++) { UniformInfo info = new UniformInfo(); int length = 0; StringBuilder name = new StringBuilder(); GL.GetActiveUniform(ProgramID, i, 256, out length, out info.size, out info.type, name); info.name = name.ToString(); Uniforms.Add(name.ToString(), info); info.address = GL.GetUniformLocation(ProgramID, info.name); } } public void GenBuffers() { for (int i = 0; i < Attributes.Count; i++) { uint buffer = 0; GL.GenBuffers(1, out buffer); Buffers.Add(Attributes.Values.ElementAt(i).name, buffer); } for (int i = 0; i < Uniforms.Count; i++) { uint buffer = 0; GL.GenBuffers(1, out buffer); Buffers.Add(Uniforms.Values.ElementAt(i).name, buffer); } } public void DeleteBuffers() { foreach (KeyValuePair<string, uint> b in Buffers) { GL.DeleteBuffer(b.Value); } } public void EnableVertexAttribArrays() { for (int i = 0; i < Attributes.Count; i++) { GL.EnableVertexAttribArray(Attributes.Values.ElementAt(i).address); } } public void DisableVertexAttribArrays() { for (int i = 0; i < Attributes.Count; i++) { GL.DisableVertexAttribArray(Attributes.Values.ElementAt(i).address); } } public int GetAttribute(string name) { if (Attributes.ContainsKey(name)) { return Attributes[name].address; } else { return -1; } } public int GetUniform(string name) { if (Uniforms.ContainsKey(name)) { return Uniforms[name].address; } else { return -1; } } public uint GetBuffer(string name) { if (Buffers.ContainsKey(name)) { return Buffers[name]; } else { return 0; } } private void loadShader(String code, ShaderType type, out int address) { address = GL.CreateShader(type); GL.ShaderSource(address, code); GL.CompileShader(address); GL.AttachShader(ProgramID, address); if (!GL.GetShaderInfoLog(address).Equals("")) Console.WriteLine("Shader info log: " + GL.GetShaderInfoLog(address)); } //UNUSED public void LoadShaderFromString(String code, ShaderType type) { if (type == ShaderType.VertexShader) { loadShader(code, type, out VShaderID); } else if (type == ShaderType.FragmentShader) { loadShader(code, type, out FShaderID); } } //UNUSED public void LoadShaderFromFile(String filename, ShaderType type) { using (StreamReader sr = new StreamReader(filename)) { if (type == ShaderType.VertexShader) { loadShader(sr.ReadToEnd(), type, out VShaderID); } else if (type == ShaderType.FragmentShader) { loadShader(sr.ReadToEnd(), type, out FShaderID); } } } } public class AttributeInfo { public String name = ""; public int address = -1; public int size = 0; public ActiveAttribType type; } public class UniformInfo { public String name = ""; public int address = -1; public int size = 0; public ActiveUniformType type; } }
#region "Copyright" /* FOR FURTHER DETAILS ABOUT LICENSING, PLEASE VISIT "LICENSE.txt" INSIDE THE SAGEFRAME FOLDER */ #endregion #region "References" using System; using System.Reflection; #endregion namespace SageFrame.Web.Utils { /// <summary> /// Define application encoded null values /// </summary> public class Null { /// <summary> /// Returns -1. /// </summary> public static short NullShort { get { return -1; } } /// <summary> /// Return -1. /// </summary> public static int NullInteger { get { return -1; } } /// <summary> /// Return float MinValue. /// </summary> public static float NullSingle { get { return float.MinValue; } } /// <summary> /// Return double MinValue. /// </summary> public static double NullDouble { get { return double.MinValue; } } /// <summary> /// Return decimal MinValue. /// </summary> public static decimal NullDecimal { get { return decimal.MinValue; } } /// <summary> /// Return DateTime MinValue. /// </summary> public static System.DateTime NullDate { get { return System.DateTime.MinValue; } } /// <summary> /// Return empty string. /// </summary> public static string NullString { get { return ""; } } /// <summary> /// Return false. /// </summary> public static bool NullBoolean { get { return false; } } /// <summary> /// Return empty Guid. /// </summary> public static Guid NullGuid { get { return Guid.Empty; } } /// <summary> /// Sets a field to an application encoded null value (used in BLL layer). /// </summary> /// <param name="objValue">object</param> /// <param name="objField">object</param> /// <returns></returns> public static object SetNull(object objValue, object objField) { object functionReturnValue = null; if (System.Convert.IsDBNull(objValue)) { if (objField is short) { functionReturnValue = NullShort; } else if (objField is int) { functionReturnValue = NullInteger; } else if (objField is float) { functionReturnValue = NullSingle; } else if (objField is double) { functionReturnValue = NullDouble; } else if (objField is decimal) { functionReturnValue = NullDecimal; } else if (objField is System.DateTime) { functionReturnValue = NullDate; } else if (objField is string) { functionReturnValue = NullString; } else if (objField is bool) { functionReturnValue = NullBoolean; } else if (objField is Guid) { functionReturnValue = NullGuid; } else { // complex object functionReturnValue = null; } } else { // return value functionReturnValue = objValue; } return functionReturnValue; } /// <summary> /// Sets a field to an application encoded null value (used in BLL layer). /// </summary> /// <param name="objPropertyInfo">Object of class PropertyInfo.</param> /// <returns>object</returns> public static object SetNull(PropertyInfo objPropertyInfo) { object functionReturnValue = null; switch (objPropertyInfo.PropertyType.ToString()) { case "System.Int16": functionReturnValue = NullShort; break; case "System.Int32": case "System.Int64": functionReturnValue = NullInteger; break; case "System.Single": functionReturnValue = NullSingle; break; case "System.Double": functionReturnValue = NullDouble; break; case "System.Decimal": functionReturnValue = NullDecimal; break; case "System.DateTime": functionReturnValue = NullDate; break; case "System.String": case "System.Char": functionReturnValue = NullString; break; case "System.Boolean": functionReturnValue = NullBoolean; break; case "System.Guid": functionReturnValue = NullGuid; break; default: // Enumerations default to the first entry Type pType = objPropertyInfo.PropertyType; if (pType.BaseType.Equals(typeof(System.Enum))) { System.Array objEnumValues = System.Enum.GetValues(pType); Array.Sort(objEnumValues); functionReturnValue = System.Enum.ToObject(pType, objEnumValues.GetValue(0)); } else { // complex object functionReturnValue = null; } break; } return functionReturnValue; } /// <summary> /// Convert an application encoded null value to a database null value (used in DAL) /// </summary> /// <param name="objField">object</param> /// <param name="objDBNull">object</param> /// <returns>object</returns> public static object GetNull(object objField, object objDBNull) { object functionReturnValue = null; functionReturnValue = objField; if (objField == null) { functionReturnValue = objDBNull; } else if (objField is short) { if (Convert.ToInt16(objField) == NullShort) { functionReturnValue = objDBNull; } } else if (objField is int) { if (Convert.ToInt32(objField) == NullInteger) { functionReturnValue = objDBNull; } } else if (objField is float) { if (Convert.ToSingle(objField) == NullSingle) { functionReturnValue = objDBNull; } } else if (objField is double) { if (Convert.ToDouble(objField) == NullDouble) { functionReturnValue = objDBNull; } } else if (objField is decimal) { if (Convert.ToDecimal(objField) == NullDecimal) { functionReturnValue = objDBNull; } } else if (objField is System.DateTime) { // compare the Date part of the DateTime with the DatePart of the NullDate ( this avoids subtle time differences ) if (Convert.ToDateTime(objField).Date == NullDate.Date) { functionReturnValue = objDBNull; } } else if (objField is string) { if (objField == null) { functionReturnValue = objDBNull; } else { if (objField.ToString() ==string.Empty ) { functionReturnValue = objDBNull; } } } else if (objField is bool) { if (Convert.ToBoolean(objField) == NullBoolean) { functionReturnValue = objDBNull; } } else if (objField is Guid) { if (((System.Guid)objField).Equals(NullGuid)) { functionReturnValue = objDBNull; } } return functionReturnValue; } /// <summary> /// checks if a field contains an application encoded null value /// </summary> /// <param name="objField">object</param> /// <returns>True if objField is known type.</returns> public static bool IsNull(object objField) { bool functionReturnValue = false; if ((objField != null)) { if (objField is int) { functionReturnValue = objField.Equals(NullInteger); } else if (objField is float) { functionReturnValue = objField.Equals(NullSingle); } else if (objField is double) { functionReturnValue = objField.Equals(NullDouble); } else if (objField is decimal) { functionReturnValue = objField.Equals(NullDecimal); } else if (objField is System.DateTime) { DateTime objDate = (DateTime)objField; functionReturnValue = objDate.Date.Equals(NullDate.Date); } else if (objField is string) { functionReturnValue = objField.Equals(NullString); } else if (objField is bool) { functionReturnValue = objField.Equals(NullBoolean); } else if (objField is Guid) { functionReturnValue = objField.Equals(NullGuid); } else { // complex object functionReturnValue = false; } } else { functionReturnValue = true; } return functionReturnValue; } } }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using Cassandra.Collections; using Cassandra.Connections; using Cassandra.ExecutionProfiles; using Cassandra.Observers.Abstractions; using Cassandra.Serialization; using Cassandra.SessionManagement; using Cassandra.Tasks; namespace Cassandra.Requests { /// <inheritdoc /> internal class RequestHandler : IRequestHandler { private static readonly Logger Logger = new Logger(typeof(Session)); public const long StateInit = 0; public const long StateCompleted = 1; private readonly IRequest _request; private readonly IInternalSession _session; private readonly IRequestResultHandler _requestResultHandler; private long _state; private readonly IEnumerator<Host> _queryPlan; private readonly object _queryPlanLock = new object(); private readonly ICollection<IRequestExecution> _running = new CopyOnWriteList<IRequestExecution>(); private ISpeculativeExecutionPlan _executionPlan; private volatile HashedWheelTimer.ITimeout _nextExecutionTimeout; private readonly IRequestObserver _requestObserver; public IExtendedRetryPolicy RetryPolicy { get; } public ISerializer Serializer { get; } public IStatement Statement { get; } public IRequestOptions RequestOptions { get; } /// <summary> /// Creates a new instance using a request, the statement and the execution profile. /// </summary> public RequestHandler( IInternalSession session, ISerializer serializer, IRequest request, IStatement statement, IRequestOptions requestOptions) { _session = session ?? throw new ArgumentNullException(nameof(session)); _requestObserver = session.ObserverFactory.CreateRequestObserver(); _requestResultHandler = new TcsMetricsRequestResultHandler(_requestObserver); _request = request; Serializer = serializer ?? throw new ArgumentNullException(nameof(session)); Statement = statement; RequestOptions = requestOptions ?? throw new ArgumentNullException(nameof(requestOptions)); RetryPolicy = RequestOptions.RetryPolicy; if (statement?.RetryPolicy != null) { RetryPolicy = statement.RetryPolicy.Wrap(RetryPolicy); } _queryPlan = RequestHandler.GetQueryPlan(session, statement, RequestOptions.LoadBalancingPolicy).GetEnumerator(); } /// <summary> /// Creates a new instance using the statement to build the request. /// Statement can not be null. /// </summary> public RequestHandler(IInternalSession session, ISerializer serializer, IStatement statement, IRequestOptions requestOptions) : this(session, serializer, RequestHandler.GetRequest(statement, serializer, requestOptions), statement, requestOptions) { } /// <summary> /// Creates a new instance with no request, suitable for getting a connection. /// </summary> public RequestHandler(IInternalSession session, ISerializer serializer) : this(session, serializer, null, null, session.Cluster.Configuration.DefaultRequestOptions) { } /// <summary> /// Gets a query plan as determined by the load-balancing policy. /// In the special case when a Host is provided at Statement level, it will return a query plan with a single /// host. /// </summary> private static IEnumerable<Host> GetQueryPlan(ISession session, IStatement statement, ILoadBalancingPolicy lbp) { // Single host iteration var host = (statement as Statement)?.Host; return host == null ? lbp.NewQueryPlan(session.Keyspace, statement) : Enumerable.Repeat(host, 1); } /// <inheritdoc /> public IRequest BuildRequest() { return RequestHandler.GetRequest(Statement, Serializer, RequestOptions); } /// <summary> /// Gets the Request to send to a cassandra node based on the statement type /// </summary> internal static IRequest GetRequest(IStatement statement, ISerializer serializer, IRequestOptions requestOptions) { ICqlRequest request = null; if (statement.IsIdempotent == null) { statement.SetIdempotence(requestOptions.DefaultIdempotence); } if (statement is RegularStatement s1) { s1.Serializer = serializer; var options = QueryProtocolOptions.CreateFromQuery(serializer.ProtocolVersion, s1, requestOptions, null); options.ValueNames = s1.QueryValueNames; request = new QueryRequest(serializer, s1.QueryString, options, s1.IsTracing, s1.OutgoingPayload); } if (statement is BoundStatement s2) { // set skip metadata only when result metadata id is supported because of CASSANDRA-10786 var skipMetadata = serializer.ProtocolVersion.SupportsResultMetadataId() && s2.PreparedStatement.ResultMetadata.ContainsColumnDefinitions(); var options = QueryProtocolOptions.CreateFromQuery(serializer.ProtocolVersion, s2, requestOptions, skipMetadata); request = new ExecuteRequest( serializer, s2.PreparedStatement.Id, null, s2.PreparedStatement.ResultMetadata, options, s2.IsTracing, s2.OutgoingPayload); } if (statement is BatchStatement s) { s.Serializer = serializer; var consistency = requestOptions.ConsistencyLevel; if (s.ConsistencyLevel.HasValue) { consistency = s.ConsistencyLevel.Value; } request = new BatchRequest(serializer, s.OutgoingPayload, s, consistency, requestOptions); } if (request == null) { throw new NotSupportedException("Statement of type " + statement.GetType().FullName + " not supported"); } return request; } /// <inheritdoc /> public bool SetCompleted(Exception ex, RowSet result = null) { return SetCompleted(ex, result, null); } /// <inheritdoc /> public bool SetCompleted(RowSet result, Action action) { return SetCompleted(null, result, action); } /// <summary> /// Marks this instance as completed. /// If ex is not null, sets the exception. /// If action is not null, it invokes it using the default task scheduler. /// </summary> private bool SetCompleted(Exception ex, RowSet result, Action action) { var finishedNow = Interlocked.CompareExchange(ref _state, RequestHandler.StateCompleted, RequestHandler.StateInit) == RequestHandler.StateInit; if (!finishedNow) { return false; } //Cancel the current timer //When the next execution timer is being scheduled at the *same time* //the timer is not going to be cancelled, in that case, this instance is going to stay alive a little longer _nextExecutionTimeout?.Cancel(); foreach (var execution in _running) { execution.Cancel(); } if (ex != null) { _requestResultHandler.TrySetException(ex); return true; } if (action != null) { //Create a new Task using the default scheduler, invoke the action and set the result Task.Factory.StartNew(() => { try { action(); _requestResultHandler.TrySetResult(result); } catch (Exception actionEx) { _requestResultHandler.TrySetException(actionEx); } }); return true; } _requestResultHandler.TrySetResult(result); return true; } public void SetNoMoreHosts(NoHostAvailableException ex, IRequestExecution execution) { //An execution ended with a NoHostAvailableException (retrying or starting). //If there is a running execution, do not yield it to the user _running.Remove(execution); if (_running.Count > 0) { RequestHandler.Logger.Info("Could not obtain an available host for speculative execution"); return; } SetCompleted(ex); } public bool HasCompleted() { return Interlocked.Read(ref _state) == RequestHandler.StateCompleted; } private Host GetNextHost() { // Lock to handle multiple threads from multiple executions to get a new host lock (_queryPlanLock) { if (_queryPlan.MoveNext()) { return _queryPlan.Current; } } return null; } /// <inheritdoc /> public ValidHost GetNextValidHost(Dictionary<IPEndPoint, Exception> triedHosts) { Host host; while ((host = GetNextHost()) != null && !_session.IsDisposed) { triedHosts[host.Address] = null; if (!TryValidateHost(host, out var validHost)) { continue; } return validHost; } throw new NoHostAvailableException(triedHosts); } /// <summary> /// Checks if the host is a valid candidate for the purpose of obtaining a connection. /// This method obtains the <see cref="HostDistance"/> from the load balancing policy. /// </summary> /// <param name="host">Host to check.</param> /// <param name="validHost">Output parameter that will contain the <see cref="ValidHost"/> instance.</param> /// <returns><code>true</code> if the host is valid and <code>false</code> if not valid /// (see documentation of <see cref="ValidHost.New"/>)</returns> private bool TryValidateHost(Host host, out ValidHost validHost) { var distance = _session.InternalCluster.RetrieveAndSetDistance(host); validHost = ValidHost.New(host, distance); return validHost != null; } /// <inheritdoc /> public async Task<IConnection> GetNextConnectionAsync(Dictionary<IPEndPoint, Exception> triedHosts) { Host host; // While there is an available host while ((host = GetNextHost()) != null) { var c = await ValidateHostAndGetConnectionAsync(host, triedHosts).ConfigureAwait(false); if (c == null) { continue; } return c; } throw new NoHostAvailableException(triedHosts); } /// <inheritdoc /> public async Task<IConnection> ValidateHostAndGetConnectionAsync(Host host, Dictionary<IPEndPoint, Exception> triedHosts) { if (_session.IsDisposed) { throw new NoHostAvailableException(triedHosts); } triedHosts[host.Address] = null; if (!TryValidateHost(host, out var validHost)) { return null; } var c = await GetConnectionToValidHostAsync(validHost, triedHosts).ConfigureAwait(false); return c; } /// <inheritdoc /> public Task<IConnection> GetConnectionToValidHostAsync(ValidHost validHost, IDictionary<IPEndPoint, Exception> triedHosts) { return RequestHandler.GetConnectionFromHostAsync(validHost.Host, validHost.Distance, _session, triedHosts); } /// <summary> /// Gets a connection from a host or null if its not possible, filling the triedHosts map with the failures. /// </summary> /// <param name="host">Host to which a connection will be obtained.</param> /// <param name="distance">Output parameter that will contain the <see cref="HostDistance"/> associated with /// <paramref name="host"/>. It is retrieved from the current <see cref="ILoadBalancingPolicy"/>.</param> /// <param name="session">Session from where a connection will be obtained (or created).</param> /// <param name="triedHosts">Hosts for which there were attempts to connect and send the request.</param> /// <exception cref="InvalidQueryException">When the keyspace is not valid</exception> internal static async Task<IConnection> GetConnectionFromHostAsync( Host host, HostDistance distance, IInternalSession session, IDictionary<IPEndPoint, Exception> triedHosts) { var hostPool = session.GetOrCreateConnectionPool(host, distance); try { return await hostPool.GetConnectionFromHostAsync(triedHosts, () => session.Keyspace).ConfigureAwait(false); } catch (SocketException) { // A socket exception on the current connection does not mean that all the pool is closed: // Retry on the same host return await RequestHandler.GetConnectionFromHostAsync(host, distance, session, triedHosts).ConfigureAwait(false); } } public Task<RowSet> SendAsync() { if (_request == null) { _requestResultHandler.TrySetException(new DriverException("request can not be null")); return _requestResultHandler.Task; } StartNewExecution(); return _requestResultHandler.Task; } /// <summary> /// Starts a new execution and adds it to the executions collection /// </summary> private void StartNewExecution() { try { var execution = _session.Cluster.Configuration.RequestExecutionFactory.Create(this, _session, _request, _requestObserver); var lastHost = execution.Start(false); _running.Add(execution); ScheduleNext(lastHost); } catch (NoHostAvailableException ex) { if (_running.Count == 0) { //Its the sending of the first execution //There isn't any host available, yield it to the user SetCompleted(ex); } //Let's wait for the other executions } catch (Exception ex) { //There was an Exception before sending: a protocol error or the keyspace does not exists SetCompleted(ex); } } /// <summary> /// Schedules the next delayed execution /// </summary> private void ScheduleNext(Host currentHost) { if (Statement == null || Statement.IsIdempotent == false) { //its not idempotent, we should not schedule an speculative execution return; } if (_executionPlan == null) { _executionPlan = RequestOptions.SpeculativeExecutionPolicy.NewPlan(_session.Keyspace, Statement); } var delay = _executionPlan.NextExecution(currentHost); if (delay <= 0) { return; } //There is one live timer at a time. _nextExecutionTimeout = _session.Cluster.Configuration.Timer.NewTimeout(_ => { // Start the speculative execution outside the IO thread Task.Run(() => { if (HasCompleted()) { return; } RequestHandler.Logger.Info("Starting new speculative execution after {0} ms. Last used host: {1}", delay, currentHost.Address); _requestObserver.OnSpeculativeExecution(currentHost, delay); StartNewExecution(); }); }, null, delay); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Windows; using Microsoft.Practices.Prism.Properties; using Microsoft.Practices.ServiceLocation; namespace Microsoft.Practices.Prism.Regions { /// <summary> /// Provides navigation for regions. /// </summary> public class RegionNavigationService : IRegionNavigationService { private readonly IServiceLocator serviceLocator; private readonly IRegionNavigationContentLoader regionNavigationContentLoader; private IRegionNavigationJournal journal; private NavigationContext currentNavigationContext; /// <summary> /// Initializes a new instance of the <see cref="RegionNavigationService"/> class. /// </summary> /// <param name="serviceLocator">The service locator.</param> /// <param name="regionNavigationContentLoader">The navigation target handler.</param> /// <param name="journal">The journal.</param> public RegionNavigationService(IServiceLocator serviceLocator, IRegionNavigationContentLoader regionNavigationContentLoader, IRegionNavigationJournal journal) { if (serviceLocator == null) { throw new ArgumentNullException("serviceLocator"); } if (regionNavigationContentLoader == null) { throw new ArgumentNullException("regionNavigationContentLoader"); } if (journal == null) { throw new ArgumentNullException("journal"); } this.serviceLocator = serviceLocator; this.regionNavigationContentLoader = regionNavigationContentLoader; this.journal = journal; this.journal.NavigationTarget = this; } /// <summary> /// Gets or sets the region. /// </summary> /// <value>The region.</value> public IRegion Region { get; set; } /// <summary> /// Gets the journal. /// </summary> /// <value>The journal.</value> public IRegionNavigationJournal Journal { get { return this.journal; } } /// <summary> /// Raised when the region is about to be navigated to content. /// </summary> public event EventHandler<RegionNavigationEventArgs> Navigating; private void RaiseNavigating(NavigationContext navigationContext) { if (this.Navigating != null) { this.Navigating(this, new RegionNavigationEventArgs(navigationContext)); } } /// <summary> /// Raised when the region is navigated to content. /// </summary> public event EventHandler<RegionNavigationEventArgs> Navigated; private void RaiseNavigated(NavigationContext navigationContext) { if (this.Navigated != null) { this.Navigated(this, new RegionNavigationEventArgs(navigationContext)); } } /// <summary> /// Raised when a navigation request fails. /// </summary> public event EventHandler<RegionNavigationFailedEventArgs> NavigationFailed; private void RaiseNavigationFailed(NavigationContext navigationContext, Exception error) { if (this.NavigationFailed != null) { this.NavigationFailed(this, new RegionNavigationFailedEventArgs(navigationContext, error)); } } /// <summary> /// Initiates navigation to the specified target. /// </summary> /// <param name="target">The target.</param> /// <param name="navigationCallback">A callback to execute when the navigation request is completed.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exception is marshalled to callback")] public void RequestNavigate(Uri target, Action<NavigationResult> navigationCallback) { this.RequestNavigate(target, navigationCallback, null); } /// <summary> /// Initiates navigation to the specified target. /// </summary> /// <param name="target">The target.</param> /// <param name="navigationCallback">A callback to execute when the navigation request is completed.</param> /// <param name="navigationParameters">The navigation parameters specific to the navigation request.</param> public void RequestNavigate(Uri target, Action<NavigationResult> navigationCallback, NavigationParameters navigationParameters) { if (navigationCallback == null) throw new ArgumentNullException("navigationCallback"); try { this.DoNavigate(target, navigationCallback, navigationParameters); } catch (Exception e) { this.NotifyNavigationFailed(new NavigationContext(this, target), navigationCallback, e); } } private void DoNavigate(Uri source, Action<NavigationResult> navigationCallback, NavigationParameters navigationParameters) { if (source == null) { throw new ArgumentNullException("source"); } if (this.Region == null) { throw new InvalidOperationException(Resources.NavigationServiceHasNoRegion); } this.currentNavigationContext = new NavigationContext(this, source, navigationParameters); // starts querying the active views RequestCanNavigateFromOnCurrentlyActiveView( this.currentNavigationContext, navigationCallback, this.Region.ActiveViews.ToArray(), 0); } private void RequestCanNavigateFromOnCurrentlyActiveView( NavigationContext navigationContext, Action<NavigationResult> navigationCallback, object[] activeViews, int currentViewIndex) { if (currentViewIndex < activeViews.Length) { var vetoingView = activeViews[currentViewIndex] as IConfirmNavigationRequest; if (vetoingView != null) { // the current active view implements IConfirmNavigationRequest, request confirmation // providing a callback to resume the navigation request vetoingView.ConfirmNavigationRequest( navigationContext, canNavigate => { if (this.currentNavigationContext == navigationContext && canNavigate) { RequestCanNavigateFromOnCurrentlyActiveViewModel( navigationContext, navigationCallback, activeViews, currentViewIndex); } else { this.NotifyNavigationFailed(navigationContext, navigationCallback, null); } }); } else { RequestCanNavigateFromOnCurrentlyActiveViewModel( navigationContext, navigationCallback, activeViews, currentViewIndex); } } else { ExecuteNavigation(navigationContext, activeViews, navigationCallback); } } private void RequestCanNavigateFromOnCurrentlyActiveViewModel( NavigationContext navigationContext, Action<NavigationResult> navigationCallback, object[] activeViews, int currentViewIndex) { var frameworkElement = activeViews[currentViewIndex] as FrameworkElement; if (frameworkElement != null) { var vetoingViewModel = frameworkElement.DataContext as IConfirmNavigationRequest; if (vetoingViewModel != null) { // the data model for the current active view implements IConfirmNavigationRequest, request confirmation // providing a callback to resume the navigation request vetoingViewModel.ConfirmNavigationRequest( navigationContext, canNavigate => { if (this.currentNavigationContext == navigationContext && canNavigate) { RequestCanNavigateFromOnCurrentlyActiveView( navigationContext, navigationCallback, activeViews, currentViewIndex + 1); } else { this.NotifyNavigationFailed(navigationContext, navigationCallback, null); } }); return; } } RequestCanNavigateFromOnCurrentlyActiveView( navigationContext, navigationCallback, activeViews, currentViewIndex + 1); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exception is marshalled to callback")] private void ExecuteNavigation(NavigationContext navigationContext, object[] activeViews, Action<NavigationResult> navigationCallback) { try { NotifyActiveViewsNavigatingFrom(navigationContext, activeViews); object view = this.regionNavigationContentLoader.LoadContent(this.Region, navigationContext); // Raise the navigating event just before activing the view. this.RaiseNavigating(navigationContext); this.Region.Activate(view); // Update the navigation journal before notifying others of navigaton IRegionNavigationJournalEntry journalEntry = this.serviceLocator.GetInstance<IRegionNavigationJournalEntry>(); journalEntry.Uri = navigationContext.Uri; journalEntry.Parameters = navigationContext.Parameters; this.journal.RecordNavigation(journalEntry); // The view can be informed of navigation InvokeOnNavigationAwareElement(view, (n) => n.OnNavigatedTo(navigationContext)); navigationCallback(new NavigationResult(navigationContext, true)); // Raise the navigated event when navigation is completed. this.RaiseNavigated(navigationContext); } catch (Exception e) { this.NotifyNavigationFailed(navigationContext, navigationCallback, e); } } private void NotifyNavigationFailed(NavigationContext navigationContext, Action<NavigationResult> navigationCallback, Exception e) { var navigationResult = e != null ? new NavigationResult(navigationContext, e) : new NavigationResult(navigationContext, false); navigationCallback(navigationResult); this.RaiseNavigationFailed(navigationContext, e); } private static void NotifyActiveViewsNavigatingFrom(NavigationContext navigationContext, object[] activeViews) { InvokeOnNavigationAwareElements(activeViews, (n) => n.OnNavigatedFrom(navigationContext)); } private static void InvokeOnNavigationAwareElements(IEnumerable<object> items, Action<INavigationAware> invocation) { foreach (var item in items) { InvokeOnNavigationAwareElement(item, invocation); } } private static void InvokeOnNavigationAwareElement(object item, Action<INavigationAware> invocation) { var navigationAwareItem = item as INavigationAware; if (navigationAwareItem != null) { invocation(navigationAwareItem); } FrameworkElement frameworkElement = item as FrameworkElement; if (frameworkElement != null) { INavigationAware navigationAwareDataContext = frameworkElement.DataContext as INavigationAware; if (navigationAwareDataContext != null) { invocation(navigationAwareDataContext); } } } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // namespace Revit.SDK.Samples.Openings.CS { using System; using System.Collections.Generic; using System.Text; using System.Drawing; /// <summary> /// represent a geometry segment line /// </summary> public class Line2D { private PointF m_startPnt = new PointF(); // start point private PointF m_endPnt = new PointF(); // end point private float m_length; // length of the line // normal of the line; start point to end point private PointF m_normal = new PointF(); private RectangleF m_boundingBox = new RectangleF();// rectangle box contains the line /// <summary> /// rectangle box contains the line /// </summary> public RectangleF BoundingBox { get { return m_boundingBox; } } /// <summary> /// start point of the line; if it is set to new value, /// EndPoint is changeless; Length, Normal and BoundingBox will updated /// </summary> public PointF StartPnt { get { return m_startPnt; } set { if (m_startPnt == value) { return; } m_startPnt = value; CalculateDirection(); CalculateBoundingBox(); } } /// <summary> /// end point of the line; if it is set to new value, /// StartPoint is changeless; Length, Normal and BoundingBox will updated /// </summary> public PointF EndPnt { get { return m_endPnt; } set { if (m_endPnt == value) { return; } m_endPnt = value; CalculateDirection(); CalculateBoundingBox(); } } /// <summary> /// Length of the line; if it is set to new value, /// StartPoint and Normal is changeless; EndPoint and BoundingBox will updated /// </summary> public float Length { get { return m_length; } set { if (m_length == value) { return; } m_length = value; CalculateEndPoint(); CalculateBoundingBox(); } } /// <summary> /// Normal of the line; if it is set to new value, /// StartPoint is changeless; EndPoint and BoundingBox will updated /// </summary> public PointF Normal { get { return m_normal; } set { if (m_normal == value) { return; } m_normal = value; CalculateEndPoint(); CalculateBoundingBox(); } } /// <summary> /// constructor /// default StartPoint = (0.0, 0.0), EndPoint = (1.0, 0.0) /// </summary> public Line2D() { m_startPnt.X = 0.0f; m_startPnt.Y = 0.0f; m_endPnt.X = 1.0f; m_endPnt.Y = 0.0f; CalculateDirection(); CalculateBoundingBox(); } /// <summary> /// constructor /// </summary> /// <param name="startPnt">StartPoint</param> /// <param name="endPnt">EndPoint</param> public Line2D(PointF startPnt, PointF endPnt) { m_startPnt = startPnt; m_endPnt = endPnt; CalculateDirection(); CalculateBoundingBox(); } /// <summary> /// calculate BoundingBox according to StartPoint and EndPoint /// </summary> private void CalculateBoundingBox() { float x1 = m_endPnt.X; float x2 = m_startPnt.X; float y1 = m_endPnt.Y; float y2 = m_startPnt.Y; float width = Math.Abs(x1 - x2); float height = Math.Abs(y1 - y2); if (x1 > x2) { x1 = x2; } if (y1 > y2) { y1 = y2; } m_boundingBox = new RectangleF(x1, y1, width, height); } /// <summary> /// calculate length by StartPoint and EndPoint /// </summary> private void CalculateLength() { m_length = (float)Math.Sqrt(Math.Pow((m_startPnt.X - m_endPnt.X), 2) + Math.Pow((m_startPnt.Y - m_endPnt.Y), 2)); } /// <summary> /// calculate Direction by StartPoint and EndPoint /// </summary> private void CalculateDirection() { CalculateLength(); m_normal.X = (m_endPnt.X - m_startPnt.X) / m_length; m_normal.Y = (m_endPnt.Y - m_startPnt.Y) / m_length; } /// <summary> /// calculate EndPoint by StartPoint, Length and Direction /// </summary> private void CalculateEndPoint() { m_endPnt.X = m_startPnt.X + m_length * m_normal.X; m_endPnt.Y = m_startPnt.Y + m_length * m_normal.Y; } } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter; namespace DocuSign.eSign.Model { /// <summary> /// Contains information about an attachment. /// </summary> [DataContract] public partial class Attachment : IEquatable<Attachment>, IValidatableObject { public Attachment() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="Attachment" /> class. /// </summary> /// <param name="AccessControl">AccessControl.</param> /// <param name="AttachmentId">AttachmentId.</param> /// <param name="AttachmentType">Specifies the type of the attachment for the recipient..</param> /// <param name="Data">Data.</param> /// <param name="Label">Label.</param> /// <param name="Name">Name.</param> /// <param name="RemoteUrl">RemoteUrl.</param> public Attachment(string AccessControl = default(string), string AttachmentId = default(string), string AttachmentType = default(string), string Data = default(string), string Label = default(string), string Name = default(string), string RemoteUrl = default(string)) { this.AccessControl = AccessControl; this.AttachmentId = AttachmentId; this.AttachmentType = AttachmentType; this.Data = Data; this.Label = Label; this.Name = Name; this.RemoteUrl = RemoteUrl; } /// <summary> /// Gets or Sets AccessControl /// </summary> [DataMember(Name="accessControl", EmitDefaultValue=false)] public string AccessControl { get; set; } /// <summary> /// Gets or Sets AttachmentId /// </summary> [DataMember(Name="attachmentId", EmitDefaultValue=false)] public string AttachmentId { get; set; } /// <summary> /// Specifies the type of the attachment for the recipient. /// </summary> /// <value>Specifies the type of the attachment for the recipient.</value> [DataMember(Name="attachmentType", EmitDefaultValue=false)] public string AttachmentType { get; set; } /// <summary> /// Gets or Sets Data /// </summary> [DataMember(Name="data", EmitDefaultValue=false)] public string Data { get; set; } /// <summary> /// Gets or Sets Label /// </summary> [DataMember(Name="label", EmitDefaultValue=false)] public string Label { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Gets or Sets RemoteUrl /// </summary> [DataMember(Name="remoteUrl", EmitDefaultValue=false)] public string RemoteUrl { 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 Attachment {\n"); sb.Append(" AccessControl: ").Append(AccessControl).Append("\n"); sb.Append(" AttachmentId: ").Append(AttachmentId).Append("\n"); sb.Append(" AttachmentType: ").Append(AttachmentType).Append("\n"); sb.Append(" Data: ").Append(Data).Append("\n"); sb.Append(" Label: ").Append(Label).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" RemoteUrl: ").Append(RemoteUrl).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 string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as Attachment); } /// <summary> /// Returns true if Attachment instances are equal /// </summary> /// <param name="other">Instance of Attachment to be compared</param> /// <returns>Boolean</returns> public bool Equals(Attachment other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.AccessControl == other.AccessControl || this.AccessControl != null && this.AccessControl.Equals(other.AccessControl) ) && ( this.AttachmentId == other.AttachmentId || this.AttachmentId != null && this.AttachmentId.Equals(other.AttachmentId) ) && ( this.AttachmentType == other.AttachmentType || this.AttachmentType != null && this.AttachmentType.Equals(other.AttachmentType) ) && ( this.Data == other.Data || this.Data != null && this.Data.Equals(other.Data) ) && ( this.Label == other.Label || this.Label != null && this.Label.Equals(other.Label) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.RemoteUrl == other.RemoteUrl || this.RemoteUrl != null && this.RemoteUrl.Equals(other.RemoteUrl) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.AccessControl != null) hash = hash * 59 + this.AccessControl.GetHashCode(); if (this.AttachmentId != null) hash = hash * 59 + this.AttachmentId.GetHashCode(); if (this.AttachmentType != null) hash = hash * 59 + this.AttachmentType.GetHashCode(); if (this.Data != null) hash = hash * 59 + this.Data.GetHashCode(); if (this.Label != null) hash = hash * 59 + this.Label.GetHashCode(); if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.RemoteUrl != null) hash = hash * 59 + this.RemoteUrl.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
using System; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; namespace BTDB.IL { public static class ILGenExtensions { public static IILGen Do(this IILGen il, Action<IILGen> action) { action(il); return il; } public static IILGen LdcI4(this IILGen il, int value) { switch (value) { case 0: il.Emit(OpCodes.Ldc_I4_0); break; case 1: il.Emit(OpCodes.Ldc_I4_1); break; case 2: il.Emit(OpCodes.Ldc_I4_2); break; case 3: il.Emit(OpCodes.Ldc_I4_3); break; case 4: il.Emit(OpCodes.Ldc_I4_4); break; case 5: il.Emit(OpCodes.Ldc_I4_5); break; case 6: il.Emit(OpCodes.Ldc_I4_6); break; case 7: il.Emit(OpCodes.Ldc_I4_7); break; case 8: il.Emit(OpCodes.Ldc_I4_8); break; case -1: il.Emit(OpCodes.Ldc_I4_M1); break; default: if (value >= -128 && value <= 127) il.Emit(OpCodes.Ldc_I4_S, (sbyte)value); else il.Emit(OpCodes.Ldc_I4, value); break; } return il; } public static IILGen LdcI8(this IILGen il, long value) { il.Emit(OpCodes.Ldc_I8, value); return il; } public static IILGen LdcR4(this IILGen il, float value) { il.Emit(OpCodes.Ldc_R4, value); return il; } public static IILGen LdcR8(this IILGen il, double value) { il.Emit(OpCodes.Ldc_R8, value); return il; } public static IILGen Ldarg(this IILGen il, ushort parameterIndex) { switch (parameterIndex) { case 0: il.Emit(OpCodes.Ldarg_0); break; case 1: il.Emit(OpCodes.Ldarg_1); break; case 2: il.Emit(OpCodes.Ldarg_2); break; case 3: il.Emit(OpCodes.Ldarg_3); break; default: if (parameterIndex <= 255) il.Emit(OpCodes.Ldarg_S, (byte)parameterIndex); else il.Emit(OpCodes.Ldarg, parameterIndex); break; } return il; } public static IILGen Starg(this IILGen il, ushort parameterIndex) { if (parameterIndex <= 255) il.Emit(OpCodes.Starg_S, (byte)parameterIndex); else il.Emit(OpCodes.Starg, parameterIndex); return il; } public static IILGen Ldfld(this IILGen il, FieldInfo fieldInfo) { il.Emit(OpCodes.Ldfld, fieldInfo); return il; } public static IILGen Ldfld(this IILGen il, IILField fieldInfo) { il.Emit(OpCodes.Ldfld, fieldInfo); return il; } public static IILGen Ldflda(this IILGen il, FieldInfo fieldInfo) { il.Emit(OpCodes.Ldflda, fieldInfo); return il; } public static IILGen Ldflda(this IILGen il, IILField fieldInfo) { il.Emit(OpCodes.Ldflda, fieldInfo); return il; } public static IILGen Ldsfld(this IILGen il, FieldInfo fieldInfo) { il.Emit(OpCodes.Ldsfld, fieldInfo); return il; } public static IILGen Ldsfld(this IILGen il, IILField fieldInfo) { il.Emit(OpCodes.Ldsfld, fieldInfo); return il; } public static IILGen Stfld(this IILGen il, FieldInfo fieldInfo) { il.Emit(OpCodes.Stfld, fieldInfo); return il; } public static IILGen Stfld(this IILGen il, IILField fieldInfo) { il.Emit(OpCodes.Stfld, fieldInfo); return il; } public static IILGen Stsfld(this IILGen il, FieldInfo fieldInfo) { il.Emit(OpCodes.Stsfld, fieldInfo); return il; } public static IILGen Stsfld(this IILGen il, IILField fieldInfo) { il.Emit(OpCodes.Stsfld, fieldInfo); return il; } public static IILGen Stloc(this IILGen il, ushort localVariableIndex) { switch (localVariableIndex) { case 0: il.Emit(OpCodes.Stloc_0); break; case 1: il.Emit(OpCodes.Stloc_1); break; case 2: il.Emit(OpCodes.Stloc_2); break; case 3: il.Emit(OpCodes.Stloc_3); break; case 65535: throw new ArgumentOutOfRangeException(nameof(localVariableIndex)); default: if (localVariableIndex <= 255) il.Emit(OpCodes.Stloc_S, (byte)localVariableIndex); else il.Emit(OpCodes.Stloc, localVariableIndex); break; } return il; } public static IILGen Stloc(this IILGen il, IILLocal localBuilder) { il.Emit(OpCodes.Stloc, localBuilder); return il; } public static IILGen Ldloc(this IILGen il, ushort localVariableIndex) { switch (localVariableIndex) { case 0: il.Emit(OpCodes.Ldloc_0); break; case 1: il.Emit(OpCodes.Ldloc_1); break; case 2: il.Emit(OpCodes.Ldloc_2); break; case 3: il.Emit(OpCodes.Ldloc_3); break; case 65535: throw new ArgumentOutOfRangeException(nameof(localVariableIndex)); default: if (localVariableIndex <= 255) il.Emit(OpCodes.Ldloc_S, (byte)localVariableIndex); else il.Emit(OpCodes.Ldloc, localVariableIndex); break; } return il; } public static IILGen Ldloc(this IILGen il, IILLocal localBuilder) { il.Emit(OpCodes.Ldloc, localBuilder); return il; } public static IILGen Ldloca(this IILGen il, IILLocal localBuilder) { il.Emit(OpCodes.Ldloca, localBuilder); return il; } public static IILGen Constrained(this IILGen il, Type type) { il.Emit(OpCodes.Constrained, type); return il; } public static IILGen BleUnS(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Ble_Un_S, targetLabel); return il; } public static IILGen Blt(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Blt, targetLabel); return il; } public static IILGen Bgt(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Bgt, targetLabel); return il; } public static IILGen Brfalse(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Brfalse, targetLabel); return il; } public static IILGen BrfalseS(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Brfalse_S, targetLabel); return il; } public static IILGen Brtrue(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Brtrue, targetLabel); return il; } public static IILGen BrtrueS(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Brtrue_S, targetLabel); return il; } public static IILGen Br(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Br, targetLabel); return il; } public static IILGen BrS(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Br_S, targetLabel); return il; } public static IILGen BneUnS(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Bne_Un_S, targetLabel); return il; } public static IILGen BeqS(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Beq_S, targetLabel); return il; } public static IILGen Beq(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Beq, targetLabel); return il; } public static IILGen BgeUnS(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Bge_Un_S, targetLabel); return il; } public static IILGen BgeUn(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Bge_Un, targetLabel); return il; } public static IILGen Newobj(this IILGen il, ConstructorInfo constructorInfo) { il.Emit(OpCodes.Newobj, constructorInfo); return il; } public static IILGen InitObj(this IILGen il, Type type) { il.Emit(OpCodes.Initobj, type); return il; } public static IILGen Callvirt(this IILGen il, MethodInfo methodInfo) { if (methodInfo.IsStatic) throw new ArgumentException("Method in Callvirt cannot be static"); il.Emit(OpCodes.Callvirt, methodInfo); return il; } public static IILGen Call(this IILGen il, MethodInfo methodInfo) { il.Emit(OpCodes.Call, methodInfo); return il; } public static IILGen Call(this IILGen il, ConstructorInfo constructorInfo) { il.Emit(OpCodes.Call, constructorInfo); return il; } public static IILGen Ldftn(this IILGen il, MethodInfo methodInfo) { il.Emit(OpCodes.Ldftn, methodInfo); return il; } public static IILGen Ldnull(this IILGen il) { il.Emit(OpCodes.Ldnull); return il; } public static IILGen Throw(this IILGen il) { il.Emit(OpCodes.Throw); return il; } public static IILGen Ret(this IILGen il) { il.Emit(OpCodes.Ret); return il; } public static IILGen Pop(this IILGen il) { il.Emit(OpCodes.Pop); return il; } public static IILGen Castclass(this IILGen il, Type toType) { il.Emit(OpCodes.Castclass, toType); return il; } public static IILGen Isinst(this IILGen il, Type asType) { il.Emit(OpCodes.Isinst, asType); return il; } public static IILGen ConvU1(this IILGen il) { il.Emit(OpCodes.Conv_U1); return il; } public static IILGen ConvU2(this IILGen il) { il.Emit(OpCodes.Conv_U2); return il; } public static IILGen ConvU4(this IILGen il) { il.Emit(OpCodes.Conv_U4); return il; } public static IILGen ConvU8(this IILGen il) { il.Emit(OpCodes.Conv_U8); return il; } public static IILGen ConvI1(this IILGen il) { il.Emit(OpCodes.Conv_I1); return il; } public static IILGen ConvI2(this IILGen il) { il.Emit(OpCodes.Conv_I2); return il; } public static IILGen ConvI4(this IILGen il) { il.Emit(OpCodes.Conv_I4); return il; } public static IILGen ConvI8(this IILGen il) { il.Emit(OpCodes.Conv_I8); return il; } public static IILGen ConvR4(this IILGen il) { il.Emit(OpCodes.Conv_R4); return il; } public static IILGen ConvR8(this IILGen il) { il.Emit(OpCodes.Conv_R8); return il; } public static IILGen Tail(this IILGen il) { il.Emit(OpCodes.Tailcall); return il; } public static IILGen LdelemRef(this IILGen il) { il.Emit(OpCodes.Ldelem_Ref); return il; } public static IILGen StelemRef(this IILGen il) { il.Emit(OpCodes.Stelem_Ref); return il; } public static IILGen Ldelem(this IILGen il, Type itemType) { if (itemType == typeof(int)) il.Emit(OpCodes.Ldelem_I4); else if (itemType == typeof(short)) il.Emit(OpCodes.Ldelem_I2); else if (itemType == typeof(sbyte)) il.Emit(OpCodes.Ldelem_I1); else if (itemType == typeof(long)) il.Emit(OpCodes.Ldelem_I8); else if (itemType == typeof(ushort)) il.Emit(OpCodes.Ldelem_U2); else if (itemType == typeof(byte)) il.Emit(OpCodes.Ldelem_U1); else if (itemType == typeof(uint)) il.Emit(OpCodes.Ldelem_U4); else if (itemType == typeof(float)) il.Emit(OpCodes.Ldelem_R4); else if (itemType == typeof(double)) il.Emit(OpCodes.Ldelem_R8); else if (!itemType.IsValueType) il.Emit(OpCodes.Ldelem_Ref); else il.Emit(OpCodes.Ldelem, itemType); return il; } public static IILGen Stelem(this IILGen il, Type itemType) { if (itemType == typeof(int)) il.Emit(OpCodes.Stelem_I4); else if (itemType == typeof(short)) il.Emit(OpCodes.Stelem_I2); else if (itemType == typeof(sbyte)) il.Emit(OpCodes.Stelem_I1); else if (itemType == typeof(long)) il.Emit(OpCodes.Stelem_I8); else if (itemType == typeof(float)) il.Emit(OpCodes.Stelem_R4); else if (itemType == typeof(double)) il.Emit(OpCodes.Stelem_R8); else if (!itemType.IsValueType) il.Emit(OpCodes.Stelem_Ref); else il.Emit(OpCodes.Stelem, itemType); return il; } public static IILGen Ldind(this IILGen il, Type itemType) { if (itemType == typeof(int)) il.Emit(OpCodes.Ldind_I4); else if (itemType == typeof(short)) il.Emit(OpCodes.Ldind_I2); else if (itemType == typeof(sbyte)) il.Emit(OpCodes.Ldind_I1); else if (itemType == typeof(long)) il.Emit(OpCodes.Ldind_I8); else if (itemType == typeof(ushort)) il.Emit(OpCodes.Ldind_U2); else if (itemType == typeof(byte)) il.Emit(OpCodes.Ldind_U1); else if (itemType == typeof(uint)) il.Emit(OpCodes.Ldind_U4); else if (itemType == typeof(float)) il.Emit(OpCodes.Ldind_R4); else if (itemType == typeof(double)) il.Emit(OpCodes.Ldind_R8); else if (!itemType.IsValueType) il.Emit(OpCodes.Ldind_Ref); else throw new ArgumentOutOfRangeException(nameof(itemType)); return il; } public static IILGen Add(this IILGen il) { il.Emit(OpCodes.Add); return il; } public static IILGen Sub(this IILGen il) { il.Emit(OpCodes.Sub); return il; } public static IILGen Mul(this IILGen il) { il.Emit(OpCodes.Mul); return il; } public static IILGen Div(this IILGen il) { il.Emit(OpCodes.Div); return il; } public static IILGen Dup(this IILGen il) { il.Emit(OpCodes.Dup); return il; } public static IILGen Ldtoken(this IILGen il, Type type) { il.Emit(OpCodes.Ldtoken, type); return il; } public static IILGen Callvirt(this IILGen il, Expression<Action> expression) { var methodInfo = ((MethodCallExpression)expression.Body).Method; return il.Callvirt(methodInfo); } public static IILGen Callvirt<T>(this IILGen il, Expression<Func<T>> expression) { if (expression.Body is MemberExpression newExpression) { return il.Callvirt(((PropertyInfo)newExpression.Member).GetAnyGetMethod()!); } var methodInfo = ((MethodCallExpression)expression.Body).Method; return il.Callvirt(methodInfo); } public static IILGen Call(this IILGen il, Expression<Action> expression) { if (expression.Body is NewExpression newExpression) { return il.Call(newExpression.Constructor); } var methodInfo = ((MethodCallExpression)expression.Body).Method; return il.Call(methodInfo); } public static IILGen Call<T>(this IILGen il, Expression<Func<T>> expression) { if (expression.Body is MemberExpression memberExpression) { return il.Call(((PropertyInfo)memberExpression.Member).GetAnyGetMethod()!); } if (expression.Body is NewExpression newExpression) { return il.Call(newExpression.Constructor); } var methodInfo = ((MethodCallExpression)expression.Body).Method; return il.Call(methodInfo); } public static IILGen Newobj<T>(this IILGen il, Expression<Func<T>> expression) { var constructorInfo = ((NewExpression)expression.Body).Constructor; return il.Newobj(constructorInfo); } public static IILGen Ldfld<T>(this IILGen il, Expression<Func<T>> expression) { return il.Ldfld((FieldInfo)((MemberExpression)expression.Body).Member); } public static IILGen Newarr(this IILGen il, Type arrayMemberType) { il.Emit(OpCodes.Newarr, arrayMemberType); return il; } public static IILGen Box(this IILGen il, Type boxedType) { il.Emit(OpCodes.Box, boxedType); return il; } public static IILGen Unbox(this IILGen il, Type valueType) { if (!valueType.IsValueType) throw new ArgumentException("Unboxed could be only valuetype"); il.Emit(OpCodes.Unbox, valueType); return il; } public static IILGen UnboxAny(this IILGen il, Type anyType) { il.Emit(OpCodes.Unbox_Any, anyType); return il; } public static IILGen Break(this IILGen il) { il.Emit(OpCodes.Break); return il; } public static IILGen Localloc(this IILGen il) { il.Emit(OpCodes.Localloc); return il; } public static IILGen Localloc(this IILGen il, uint length) { il .LdcI4((int)length) .Emit(OpCodes.Conv_U); il .Emit(OpCodes.Localloc); return il; } public static IILGen Ld(this IILGen il, object? value) { switch (value) { case null: il.Ldnull(); break; case bool b when !b: il.LdcI4(0); break; case bool b when b: il.LdcI4(1); break; case short i16: il.LdcI4(i16); // there is no instruction for 16b int break; case int i32: il.LdcI4(i32); break; case long i64: il.LdcI8(i64); break; case float f: il.LdcR4(f); break; case double d: il.LdcR8(d); break; case string s: il.Ldstr(s); break; default: throw new ArgumentException($"{value} is not supported.", nameof(value)); } return il; } public static IILGen Ceq(this IILGen il) { il.Emit(OpCodes.Ceq); return il; } public static IILGen Cgt(this IILGen il) { il.Emit(OpCodes.Cgt); return il; } public static IILGen CgtUn(this IILGen il) { il.Emit(OpCodes.Cgt_Un); return il; } } }
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.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Orleans.Async; using Orleans.CodeGeneration; using Orleans.CodeGenerator.Utilities; using Orleans.Runtime; using GrainInterfaceUtils = Orleans.CodeGeneration.GrainInterfaceUtils; using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory; /// <summary> /// Code generator which generates <see cref="IGrainMethodInvoker"/> for grains. /// </summary> public static class GrainMethodInvokerGenerator { /// <summary> /// The suffix appended to the name of generated classes. /// </summary> private const string ClassSuffix = "MethodInvoker"; /// <summary> /// Generates the class for the provided grain types. /// </summary> /// <param name="grainType"> /// The grain interface type. /// </param> /// <returns> /// The generated class. /// </returns> internal static TypeDeclarationSyntax GenerateClass(Type grainType) { var baseTypes = new List<BaseTypeSyntax> { SF.SimpleBaseType(typeof(IGrainMethodInvoker).GetTypeSyntax()) }; var grainTypeInfo = grainType.GetTypeInfo(); var genericTypes = grainTypeInfo.IsGenericTypeDefinition ? grainType.GetGenericArguments() .Select(_ => SF.TypeParameter(_.ToString())) .ToArray() : new TypeParameterSyntax[0]; // Create the special method invoker marker attribute. var interfaceId = GrainInterfaceUtils.GetGrainInterfaceId(grainType); var interfaceIdArgument = SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(interfaceId)); var grainTypeArgument = SF.TypeOfExpression(grainType.GetTypeSyntax(includeGenericParameters: false)); var attributes = new List<AttributeSyntax> { CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax(), SF.Attribute(typeof(MethodInvokerAttribute).GetNameSyntax()) .AddArgumentListArguments( SF.AttributeArgument(grainTypeArgument), SF.AttributeArgument(interfaceIdArgument)), #if !NETSTANDARD SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax()) #endif }; var members = new List<MemberDeclarationSyntax>(GenerateGenericInvokerFields(grainType)) { GenerateInvokeMethod(grainType), GenerateInterfaceIdProperty(grainType), GenerateInterfaceVersionProperty(grainType), }; // If this is an IGrainExtension, make the generated class implement IGrainExtensionMethodInvoker. if (typeof(IGrainExtension).GetTypeInfo().IsAssignableFrom(grainTypeInfo)) { baseTypes.Add(SF.SimpleBaseType(typeof(IGrainExtensionMethodInvoker).GetTypeSyntax())); members.Add(GenerateExtensionInvokeMethod(grainType)); } var classDeclaration = SF.ClassDeclaration( CodeGeneratorCommon.ClassPrefix + TypeUtils.GetSuitableClassName(grainType) + ClassSuffix) .AddModifiers(SF.Token(SyntaxKind.InternalKeyword)) .AddBaseListTypes(baseTypes.ToArray()) .AddConstraintClauses(grainType.GetTypeConstraintSyntax()) .AddMembers(members.ToArray()) .AddAttributeLists(SF.AttributeList().AddAttributes(attributes.ToArray())); if (genericTypes.Length > 0) { classDeclaration = classDeclaration.AddTypeParameterListParameters(genericTypes); } return classDeclaration; } /// <summary> /// Returns method declaration syntax for the InterfaceId property. /// </summary> /// <param name="grainType">The grain type.</param> /// <returns>Method declaration syntax for the InterfaceId property.</returns> private static MemberDeclarationSyntax GenerateInterfaceIdProperty(Type grainType) { var property = TypeUtils.Member((IGrainMethodInvoker _) => _.InterfaceId); var returnValue = SF.LiteralExpression( SyntaxKind.NumericLiteralExpression, SF.Literal(GrainInterfaceUtils.GetGrainInterfaceId(grainType))); return SF.PropertyDeclaration(typeof(int).GetTypeSyntax(), property.Name) .AddAccessorListAccessors( SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .AddBodyStatements(SF.ReturnStatement(returnValue))) .AddModifiers(SF.Token(SyntaxKind.PublicKeyword)); } private static MemberDeclarationSyntax GenerateInterfaceVersionProperty(Type grainType) { var property = TypeUtils.Member((IGrainMethodInvoker _) => _.InterfaceVersion); var returnValue = SF.LiteralExpression( SyntaxKind.NumericLiteralExpression, SF.Literal(GrainInterfaceUtils.GetGrainInterfaceVersion(grainType))); return SF.PropertyDeclaration(typeof(ushort).GetTypeSyntax(), property.Name) .AddAccessorListAccessors( SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .AddBodyStatements(SF.ReturnStatement(returnValue))) .AddModifiers(SF.Token(SyntaxKind.PublicKeyword)); } /// <summary> /// Generates syntax for the <see cref="IGrainMethodInvoker.Invoke"/> method. /// </summary> /// <param name="grainType"> /// The grain type. /// </param> /// <returns> /// Syntax for the <see cref="IGrainMethodInvoker.Invoke"/> method. /// </returns> private static MethodDeclarationSyntax GenerateInvokeMethod(Type grainType) { // Get the method with the correct type. var invokeMethod = TypeUtils.Method( (IGrainMethodInvoker x) => x.Invoke(default(IAddressable), default(InvokeMethodRequest))); return GenerateInvokeMethod(grainType, invokeMethod); } /// <summary> /// Generates syntax for the <see cref="IGrainExtensionMethodInvoker"/> invoke method. /// </summary> /// <param name="grainType"> /// The grain type. /// </param> /// <returns> /// Syntax for the <see cref="IGrainExtensionMethodInvoker"/> invoke method. /// </returns> private static MethodDeclarationSyntax GenerateExtensionInvokeMethod(Type grainType) { // Get the method with the correct type. var invokeMethod = TypeUtils.Method( (IGrainExtensionMethodInvoker x) => x.Invoke(default(IGrainExtension), default(InvokeMethodRequest))); return GenerateInvokeMethod(grainType, invokeMethod); } /// <summary> /// Generates syntax for an invoke method. /// </summary> /// <param name="grainType"> /// The grain type. /// </param> /// <param name="invokeMethod"> /// The invoke method to generate. /// </param> /// <returns> /// Syntax for an invoke method. /// </returns> private static MethodDeclarationSyntax GenerateInvokeMethod(Type grainType, MethodInfo invokeMethod) { var parameters = invokeMethod.GetParameters(); var grainArgument = parameters[0].Name.ToIdentifierName(); var requestArgument = parameters[1].Name.ToIdentifierName(); // Store the relevant values from the request in local variables. var interfaceIdDeclaration = SF.LocalDeclarationStatement( SF.VariableDeclaration(typeof(int).GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("interfaceId") .WithInitializer(SF.EqualsValueClause(requestArgument.Member((InvokeMethodRequest _) => _.InterfaceId))))); var interfaceIdVariable = SF.IdentifierName("interfaceId"); var methodIdDeclaration = SF.LocalDeclarationStatement( SF.VariableDeclaration(typeof(int).GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("methodId") .WithInitializer(SF.EqualsValueClause(requestArgument.Member((InvokeMethodRequest _) => _.MethodId))))); var methodIdVariable = SF.IdentifierName("methodId"); var argumentsDeclaration = SF.LocalDeclarationStatement( SF.VariableDeclaration(typeof(object[]).GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("arguments") .WithInitializer(SF.EqualsValueClause(requestArgument.Member((InvokeMethodRequest _) => _.Arguments))))); var argumentsVariable = SF.IdentifierName("arguments"); var methodDeclaration = invokeMethod.GetDeclarationSyntax() .AddBodyStatements(interfaceIdDeclaration, methodIdDeclaration, argumentsDeclaration); var interfaceCases = CodeGeneratorCommon.GenerateGrainInterfaceAndMethodSwitch( grainType, methodIdVariable, methodType => GenerateInvokeForMethod(grainType, grainArgument, methodType, argumentsVariable)); // Generate the default case, which will throw a NotImplementedException. var errorMessage = SF.BinaryExpression( SyntaxKind.AddExpression, "interfaceId=".GetLiteralExpression(), interfaceIdVariable); var throwStatement = SF.ThrowStatement( SF.ObjectCreationExpression(typeof(NotImplementedException).GetTypeSyntax()) .AddArgumentListArguments(SF.Argument(errorMessage))); var defaultCase = SF.SwitchSection().AddLabels(SF.DefaultSwitchLabel()).AddStatements(throwStatement); var interfaceIdSwitch = SF.SwitchStatement(interfaceIdVariable).AddSections(interfaceCases.ToArray()).AddSections(defaultCase); // If the provided grain is null, throw an argument exception. var argumentNullException = SF.ObjectCreationExpression(typeof(ArgumentNullException).GetTypeSyntax()) .AddArgumentListArguments(SF.Argument(parameters[0].Name.GetLiteralExpression())); var grainArgumentCheck = SF.IfStatement( SF.BinaryExpression( SyntaxKind.EqualsExpression, grainArgument, SF.LiteralExpression(SyntaxKind.NullLiteralExpression)), SF.ThrowStatement(argumentNullException)); return methodDeclaration.AddBodyStatements(grainArgumentCheck, interfaceIdSwitch); } /// <summary> /// Generates syntax to invoke a method on a grain. /// </summary> /// <param name="grainType"> /// The grain type. /// </param> /// <param name="grain"> /// The grain instance expression. /// </param> /// <param name="method"> /// The method. /// </param> /// <param name="arguments"> /// The arguments expression. /// </param> /// <returns> /// Syntax to invoke a method on a grain. /// </returns> private static StatementSyntax[] GenerateInvokeForMethod( Type grainType, IdentifierNameSyntax grain, MethodInfo method, ExpressionSyntax arguments) { var castGrain = SF.ParenthesizedExpression(SF.CastExpression(grainType.GetTypeSyntax(), grain)); // Construct expressions to retrieve each of the method's parameters. var parameters = new List<ExpressionSyntax>(); var methodParameters = method.GetParameters().ToList(); for (var i = 0; i < methodParameters.Count; i++) { var parameter = methodParameters[i]; var parameterType = parameter.ParameterType.GetTypeSyntax(); var indexArg = SF.Argument(SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(i))); var arg = SF.CastExpression( parameterType, SF.ElementAccessExpression(arguments).AddArgumentListArguments(indexArg)); parameters.Add(arg); } // If the method is a generic method definition, use the generic method invoker field to invoke the method. if (method.IsGenericMethodDefinition) { var invokerFieldName = GetGenericMethodInvokerFieldName(method); var invokerCall = SF.InvocationExpression( SF.IdentifierName(invokerFieldName) .Member((GenericMethodInvoker invoker) => invoker.Invoke(null, null))) .AddArgumentListArguments(SF.Argument(grain), SF.Argument(arguments)); return new StatementSyntax[] { SF.ReturnStatement(invokerCall) }; } // Invoke the method. var grainMethodCall = SF.InvocationExpression(castGrain.Member(method.Name)) .AddArgumentListArguments(parameters.Select(SF.Argument).ToArray()); // For void methods, invoke the method and return a completed task. if (method.ReturnType == typeof(void)) { var completed = (Expression<Func<Task<object>>>)(() => TaskUtility.Completed()); return new StatementSyntax[] { SF.ExpressionStatement(grainMethodCall), SF.ReturnStatement(completed.Invoke()) }; } // For methods which return the expected type, Task<object>, simply return that. if (method.ReturnType == typeof(Task<object>)) { return new StatementSyntax[] { SF.ReturnStatement(grainMethodCall) }; } // The invoke method expects a Task<object>, so we need to upcast the returned value. // For methods which do not return a value, the Box extension method returns a meaningless value. return new StatementSyntax[] { SF.ReturnStatement(SF.InvocationExpression(grainMethodCall.Member((Task _) => _.Box()))) }; } /// <summary> /// Generates <see cref="GenericMethodInvoker"/> fields for the generic methods in <paramref name="grainType"/>. /// </summary> /// <param name="grainType">The grain type.</param> /// <returns>The generated fields.</returns> private static MemberDeclarationSyntax[] GenerateGenericInvokerFields(Type grainType) { var methods = GrainInterfaceUtils.GetMethods(grainType); var result = new List<MemberDeclarationSyntax>(); foreach (var method in methods) { if (!method.IsGenericMethodDefinition) continue; result.Add(GenerateGenericInvokerField(method)); } return result.ToArray(); } /// <summary> /// Generates a <see cref="GenericMethodInvoker"/> field for the provided generic method. /// </summary> /// <param name="method">The method.</param> /// <returns>The generated field.</returns> private static MemberDeclarationSyntax GenerateGenericInvokerField(MethodInfo method) { var fieldInfoVariable = SF.VariableDeclarator(GetGenericMethodInvokerFieldName(method)) .WithInitializer( SF.EqualsValueClause( SF.ObjectCreationExpression(typeof(GenericMethodInvoker).GetTypeSyntax()) .AddArgumentListArguments( SF.Argument(SF.TypeOfExpression(method.DeclaringType.GetTypeSyntax())), SF.Argument(method.Name.GetLiteralExpression()), SF.Argument( SF.LiteralExpression( SyntaxKind.NumericLiteralExpression, SF.Literal(method.GetGenericArguments().Length)))))); return SF.FieldDeclaration( SF.VariableDeclaration(typeof(GenericMethodInvoker).GetTypeSyntax()).AddVariables(fieldInfoVariable)) .AddModifiers( SF.Token(SyntaxKind.PrivateKeyword), SF.Token(SyntaxKind.StaticKeyword), SF.Token(SyntaxKind.ReadOnlyKeyword)); } /// <summary> /// Returns the name of the <see cref="GenericMethodInvoker"/> field corresponding to <paramref name="method"/>. /// </summary> /// <param name="method">The method.</param> /// <returns>The name of the invoker field corresponding to the provided method.</returns> private static string GetGenericMethodInvokerFieldName(MethodInfo method) { return method.Name + string.Join("_", method.GetGenericArguments().Select(arg => arg.Name)); } } }
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: support@ultracart.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// CartPaymentCreditCard /// </summary> [DataContract] public partial class CartPaymentCreditCard : IEquatable<CartPaymentCreditCard>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="CartPaymentCreditCard" /> class. /// </summary> /// <param name="cardExpirationMonth">Card expiration month (1-12).</param> /// <param name="cardExpirationYear">Card expiration year (four digit year).</param> /// <param name="cardNumber">Card number (masked to the last 4).</param> /// <param name="cardNumberToken">Hosted field token for the card number.</param> /// <param name="cardType">Card type.</param> /// <param name="cardVerificationNumber">Card verification number (masked).</param> /// <param name="cardVerificationNumberToken">Hosted field token for the card verification number.</param> /// <param name="customerProfileCreditCardId">ID of the stored credit card to use.</param> /// <param name="storeCreditCard">True if the customer wants to store the card on their profile for future re-use.</param> public CartPaymentCreditCard(int? cardExpirationMonth = default(int?), int? cardExpirationYear = default(int?), string cardNumber = default(string), string cardNumberToken = default(string), string cardType = default(string), string cardVerificationNumber = default(string), string cardVerificationNumberToken = default(string), int? customerProfileCreditCardId = default(int?), bool? storeCreditCard = default(bool?)) { this.CardExpirationMonth = cardExpirationMonth; this.CardExpirationYear = cardExpirationYear; this.CardNumber = cardNumber; this.CardNumberToken = cardNumberToken; this.CardType = cardType; this.CardVerificationNumber = cardVerificationNumber; this.CardVerificationNumberToken = cardVerificationNumberToken; this.CustomerProfileCreditCardId = customerProfileCreditCardId; this.StoreCreditCard = storeCreditCard; } /// <summary> /// Card expiration month (1-12) /// </summary> /// <value>Card expiration month (1-12)</value> [DataMember(Name="card_expiration_month", EmitDefaultValue=false)] public int? CardExpirationMonth { get; set; } /// <summary> /// Card expiration year (four digit year) /// </summary> /// <value>Card expiration year (four digit year)</value> [DataMember(Name="card_expiration_year", EmitDefaultValue=false)] public int? CardExpirationYear { get; set; } /// <summary> /// Card number (masked to the last 4) /// </summary> /// <value>Card number (masked to the last 4)</value> [DataMember(Name="card_number", EmitDefaultValue=false)] public string CardNumber { get; set; } /// <summary> /// Hosted field token for the card number /// </summary> /// <value>Hosted field token for the card number</value> [DataMember(Name="card_number_token", EmitDefaultValue=false)] public string CardNumberToken { get; set; } /// <summary> /// Card type /// </summary> /// <value>Card type</value> [DataMember(Name="card_type", EmitDefaultValue=false)] public string CardType { get; set; } /// <summary> /// Card verification number (masked) /// </summary> /// <value>Card verification number (masked)</value> [DataMember(Name="card_verification_number", EmitDefaultValue=false)] public string CardVerificationNumber { get; set; } /// <summary> /// Hosted field token for the card verification number /// </summary> /// <value>Hosted field token for the card verification number</value> [DataMember(Name="card_verification_number_token", EmitDefaultValue=false)] public string CardVerificationNumberToken { get; set; } /// <summary> /// ID of the stored credit card to use /// </summary> /// <value>ID of the stored credit card to use</value> [DataMember(Name="customer_profile_credit_card_id", EmitDefaultValue=false)] public int? CustomerProfileCreditCardId { get; set; } /// <summary> /// True if the customer wants to store the card on their profile for future re-use /// </summary> /// <value>True if the customer wants to store the card on their profile for future re-use</value> [DataMember(Name="store_credit_card", EmitDefaultValue=false)] public bool? StoreCreditCard { 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 CartPaymentCreditCard {\n"); sb.Append(" CardExpirationMonth: ").Append(CardExpirationMonth).Append("\n"); sb.Append(" CardExpirationYear: ").Append(CardExpirationYear).Append("\n"); sb.Append(" CardNumber: ").Append(CardNumber).Append("\n"); sb.Append(" CardNumberToken: ").Append(CardNumberToken).Append("\n"); sb.Append(" CardType: ").Append(CardType).Append("\n"); sb.Append(" CardVerificationNumber: ").Append(CardVerificationNumber).Append("\n"); sb.Append(" CardVerificationNumberToken: ").Append(CardVerificationNumberToken).Append("\n"); sb.Append(" CustomerProfileCreditCardId: ").Append(CustomerProfileCreditCardId).Append("\n"); sb.Append(" StoreCreditCard: ").Append(StoreCreditCard).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 CartPaymentCreditCard); } /// <summary> /// Returns true if CartPaymentCreditCard instances are equal /// </summary> /// <param name="input">Instance of CartPaymentCreditCard to be compared</param> /// <returns>Boolean</returns> public bool Equals(CartPaymentCreditCard input) { if (input == null) return false; return ( this.CardExpirationMonth == input.CardExpirationMonth || (this.CardExpirationMonth != null && this.CardExpirationMonth.Equals(input.CardExpirationMonth)) ) && ( this.CardExpirationYear == input.CardExpirationYear || (this.CardExpirationYear != null && this.CardExpirationYear.Equals(input.CardExpirationYear)) ) && ( this.CardNumber == input.CardNumber || (this.CardNumber != null && this.CardNumber.Equals(input.CardNumber)) ) && ( this.CardNumberToken == input.CardNumberToken || (this.CardNumberToken != null && this.CardNumberToken.Equals(input.CardNumberToken)) ) && ( this.CardType == input.CardType || (this.CardType != null && this.CardType.Equals(input.CardType)) ) && ( this.CardVerificationNumber == input.CardVerificationNumber || (this.CardVerificationNumber != null && this.CardVerificationNumber.Equals(input.CardVerificationNumber)) ) && ( this.CardVerificationNumberToken == input.CardVerificationNumberToken || (this.CardVerificationNumberToken != null && this.CardVerificationNumberToken.Equals(input.CardVerificationNumberToken)) ) && ( this.CustomerProfileCreditCardId == input.CustomerProfileCreditCardId || (this.CustomerProfileCreditCardId != null && this.CustomerProfileCreditCardId.Equals(input.CustomerProfileCreditCardId)) ) && ( this.StoreCreditCard == input.StoreCreditCard || (this.StoreCreditCard != null && this.StoreCreditCard.Equals(input.StoreCreditCard)) ); } /// <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.CardExpirationMonth != null) hashCode = hashCode * 59 + this.CardExpirationMonth.GetHashCode(); if (this.CardExpirationYear != null) hashCode = hashCode * 59 + this.CardExpirationYear.GetHashCode(); if (this.CardNumber != null) hashCode = hashCode * 59 + this.CardNumber.GetHashCode(); if (this.CardNumberToken != null) hashCode = hashCode * 59 + this.CardNumberToken.GetHashCode(); if (this.CardType != null) hashCode = hashCode * 59 + this.CardType.GetHashCode(); if (this.CardVerificationNumber != null) hashCode = hashCode * 59 + this.CardVerificationNumber.GetHashCode(); if (this.CardVerificationNumberToken != null) hashCode = hashCode * 59 + this.CardVerificationNumberToken.GetHashCode(); if (this.CustomerProfileCreditCardId != null) hashCode = hashCode * 59 + this.CustomerProfileCreditCardId.GetHashCode(); if (this.StoreCreditCard != null) hashCode = hashCode * 59 + this.StoreCreditCard.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; } } }
using BulletMLSample; using FilenameBuddy; using NUnit.Framework; using System; using BulletMLLib; namespace BulletMLTests { [TestFixture()] public class FireTaskTest { MoverManager manager; Myship dude; [SetUp()] public void setupHarness() { Filename.SetCurrentDirectory(@"C:\Projects\BulletMLLib\BulletMLLib\BulletMLLib.Tests\bin\Debug"); dude = new Myship(); manager = new MoverManager(dude.Position); } [Test()] public void CorrectNode() { var filename = new Filename(@"FireEmpty.xml"); BulletPattern pattern = new BulletPattern(manager); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); Assert.IsNotNull(mover.Tasks[0].Node); Assert.IsNotNull(mover.Tasks[0].Node is ActionNode); } [Test()] public void RepeatOnce() { var filename = new Filename(@"FireEmpty.xml"); BulletPattern pattern = new BulletPattern(manager); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); ActionTask myAction = mover.Tasks[0] as ActionTask; ActionNode testNode = pattern.RootNode.FindLabelNode("top", ENodeName.action) as ActionNode; Assert.AreEqual(1, testNode.RepeatNum(myAction, mover)); } [Test()] public void CorrectAction() { var filename = new Filename(@"FireEmpty.xml"); BulletPattern pattern = new BulletPattern(manager); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); BulletMLTask myTask = mover.Tasks[0]; Assert.AreEqual(1, myTask.ChildTasks.Count); } [Test()] public void CorrectAction1() { var filename = new Filename(@"FireEmpty.xml"); BulletPattern pattern = new BulletPattern(manager); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); BulletMLTask myTask = mover.Tasks[0]; Assert.AreEqual(1, myTask.ChildTasks.Count); Assert.IsTrue(myTask.ChildTasks[0] is FireTask); } [Test()] public void CorrectAction2() { var filename = new Filename(@"FireEmpty.xml"); BulletPattern pattern = new BulletPattern(manager); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); BulletMLTask myTask = mover.Tasks[0]; FireTask testTask = myTask.ChildTasks[0] as FireTask; Assert.IsNotNull(testTask.Node); Assert.IsTrue(testTask.Node.Name == ENodeName.fire); Assert.AreEqual(testTask.Node.Label, "test1"); } [Test()] public void NoSubTasks() { var filename = new Filename(@"FireEmpty.xml"); BulletPattern pattern = new BulletPattern(manager); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); BulletMLTask myTask = mover.Tasks[0]; FireTask testTask = myTask.ChildTasks[0] as FireTask; Assert.AreEqual(1, testTask.ChildTasks.Count); } [Test()] public void NoSubTasks1() { var filename = new Filename(@"FireSpeedBulletSpeed.xml"); BulletPattern pattern = new BulletPattern(manager); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); BulletMLTask myTask = mover.Tasks[0]; FireTask testTask = myTask.ChildTasks[0] as FireTask; Assert.AreEqual(1, testTask.ChildTasks.Count); } [Test()] public void FireDirectionInitCorrect() { var filename = new Filename(@"FireEmpty.xml"); BulletPattern pattern = new BulletPattern(manager); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); BulletMLTask myTask = mover.Tasks[0]; FireTask testTask = myTask.ChildTasks[0] as FireTask; float direction = testTask.FireDirection * 180 / (float)Math.PI; Assert.AreEqual(direction, 180.0f); } [Test()] public void FireDirectionInitCorrect1() { dude.pos.Y = -100.0f; var filename = new Filename(@"FireEmpty.xml"); BulletPattern pattern = new BulletPattern(manager); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); BulletMLTask myTask = mover.Tasks[0]; FireTask testTask = myTask.ChildTasks[0] as FireTask; float direction = testTask.FireDirection * 180 / (float)Math.PI; Assert.AreEqual(direction, 0.0f); } [Test()] public void FireDirectionInitCorrect2() { dude.pos.X = 100.0f; dude.pos.Y = 0.0f; var filename = new Filename(@"FireEmpty.xml"); BulletPattern pattern = new BulletPattern(manager); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); BulletMLTask myTask = mover.Tasks[0]; FireTask testTask = myTask.ChildTasks[0] as FireTask; float direction = testTask.FireDirection * 180 / (float)Math.PI; Assert.AreEqual(direction, 90.0f); } [Test()] public void FireDirectionInitCorrect3() { dude.pos.X = -100.0f; dude.pos.Y = 0.0f; var filename = new Filename(@"FireEmpty.xml"); BulletPattern pattern = new BulletPattern(manager); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); BulletMLTask myTask = mover.Tasks[0]; FireTask testTask = myTask.ChildTasks[0] as FireTask; float direction = testTask.FireDirection * 180 / (float)Math.PI; Assert.AreEqual(270.0f, direction); } [Test()] public void FireSpeedInitCorrect() { var filename = new Filename(@"FireEmpty.xml"); BulletPattern pattern = new BulletPattern(manager); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); BulletMLTask myTask = mover.Tasks[0]; FireTask testTask = myTask.ChildTasks[0] as FireTask; Assert.AreEqual(0, testTask.FireSpeed); } [Test()] public void FireInitialRunInitCorrect() { var filename = new Filename(@"FireEmpty.xml"); BulletPattern pattern = new BulletPattern(manager); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); BulletMLTask myTask = mover.Tasks[0]; FireTask testTask = myTask.ChildTasks[0] as FireTask; Assert.AreEqual(false, testTask.InitialRun); } [Test()] public void FireBulletRefInitCorrect() { var filename = new Filename(@"FireEmpty.xml"); BulletPattern pattern = new BulletPattern(manager); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); BulletMLTask myTask = mover.Tasks[0]; FireTask testTask = myTask.ChildTasks[0] as FireTask; Assert.IsNotNull(testTask.BulletRefTask); } [Test()] public void FireInitDirInitCorrect() { var filename = new Filename(@"FireEmpty.xml"); BulletPattern pattern = new BulletPattern(manager); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); BulletMLTask myTask = mover.Tasks[0]; FireTask testTask = myTask.ChildTasks[0] as FireTask; Assert.IsNull(testTask.InitialDirectionTask); } [Test()] public void FireSpeedInitInitCorrect() { var filename = new Filename(@"FireEmpty.xml"); BulletPattern pattern = new BulletPattern(manager); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); BulletMLTask myTask = mover.Tasks[0]; FireTask testTask = myTask.ChildTasks[0] as FireTask; Assert.IsNull(testTask.InitialSpeedTask); } [Test()] public void FireDirSeqInitCorrect() { var filename = new Filename(@"FireEmpty.xml"); BulletPattern pattern = new BulletPattern(manager); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); BulletMLTask myTask = mover.Tasks[0]; FireTask testTask = myTask.ChildTasks[0] as FireTask; Assert.IsNull(testTask.SequenceDirectionTask); } [Test()] public void FireSpeedSeqInitCorrect() { var filename = new Filename(@"FireEmpty.xml"); BulletPattern pattern = new BulletPattern(manager); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); BulletMLTask myTask = mover.Tasks[0]; FireTask testTask = myTask.ChildTasks[0] as FireTask; Assert.IsNull(testTask.SequenceSpeedTask); } [Test()] public void FoundBullet() { var filename = new Filename(@"BulletSpeed.xml"); BulletPattern pattern = new BulletPattern(manager); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); BulletMLTask myTask = mover.Tasks[0]; FireTask testTask = myTask.ChildTasks[0] as FireTask; Assert.IsNotNull(testTask.BulletRefTask); } [Test()] public void FoundBulletNoSubTasks() { var filename = new Filename(@"BulletSpeed.xml"); BulletPattern pattern = new BulletPattern(manager); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); BulletMLTask myTask = mover.Tasks[0]; FireTask testTask = myTask.ChildTasks[0] as FireTask; Assert.AreEqual(1, testTask.ChildTasks.Count); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Xml; using System.Collections.Generic; using System.IO; using System.Threading; using Microsoft.Build.Evaluation; using Microsoft.Build.Exceptions; using Microsoft.Build.Execution; using Microsoft.Build.Framework; using Microsoft.Build.BackEnd; using Microsoft.Build.Unittest; using TaskItem = Microsoft.Build.Execution.ProjectItemInstance.TaskItem; using Xunit; namespace Microsoft.Build.UnitTests.BackEnd { using NodeLoggingContext = Microsoft.Build.BackEnd.Logging.NodeLoggingContext; public class BuildRequestEngine_Tests : IDisposable { internal class MockRequestBuilder : IRequestBuilder, IBuildComponent { public bool ThrowExceptionOnRequest { get; set; } public bool ThrowExceptionOnContinue { get; set; } public bool ThrowExceptionOnCancel { get; set; } public bool CompleteRequestSuccessfully { get; set; } public List<FullyQualifiedBuildRequest[]> NewRequests { get; set; } private IBuildComponentHost _host; private Thread _builderThread; private BuildRequestEntry _entry; private AutoResetEvent _continueEvent; private AutoResetEvent _cancelEvent; public MockRequestBuilder() { ThrowExceptionOnRequest = false; ThrowExceptionOnContinue = false; ThrowExceptionOnCancel = false; CompleteRequestSuccessfully = true; NewRequests = new List<FullyQualifiedBuildRequest[]>(); } #region IRequestBuilder Members public event NewBuildRequestsDelegate OnNewBuildRequests; public event BuildRequestCompletedDelegate OnBuildRequestCompleted; public event BuildRequestBlockedDelegate OnBuildRequestBlocked; public void BuildRequest(NodeLoggingContext context, BuildRequestEntry entry) { Assert.Null(_builderThread); // "Received BuildRequest while one was in progress" _continueEvent = new AutoResetEvent(false); _cancelEvent = new AutoResetEvent(false); _entry = entry; entry.Continue(); _builderThread = new Thread(BuilderThreadProc); _builderThread.Start(); } private void Delay() { Thread.Sleep(1000); } private void BuilderThreadProc() { _entry.RequestConfiguration.Project = CreateStandinProject(); if (ThrowExceptionOnRequest) { BuildResult errorResult = new BuildResult(_entry.Request, new InvalidOperationException("ContinueRequest not received in time.")); _entry.Complete(errorResult); RaiseRequestComplete(_entry); return; } bool completeSuccess = CompleteRequestSuccessfully; if (_cancelEvent.WaitOne(1000)) { BuildResult res = new BuildResult(_entry.Request, new BuildAbortedException()); _entry.Complete(res); RaiseRequestComplete(_entry); return; } for (int i = 0; i < NewRequests.Count; ++i) { OnNewBuildRequests(_entry, NewRequests[i]); WaitHandle[] handles = new WaitHandle[2] { _cancelEvent, _continueEvent }; int evt = WaitHandle.WaitAny(handles, 5000); if (evt == 0) { BuildResult res = new BuildResult(_entry.Request, new BuildAbortedException()); _entry.Complete(res); RaiseRequestComplete(_entry); return; } else if (evt == 1) { IDictionary<int, BuildResult> results = _entry.Continue(); foreach (BuildResult configResult in results.Values) { if (configResult.OverallResult == BuildResultCode.Failure) { completeSuccess = false; break; } } } else { BuildResult errorResult = new BuildResult(_entry.Request, new InvalidOperationException("ContinueRequest not received in time.")); _entry.Complete(errorResult); RaiseRequestComplete(_entry); return; } if (!completeSuccess) { break; } Delay(); } BuildResult result = new BuildResult(_entry.Request); foreach (string target in _entry.Request.Targets) { result.AddResultsForTarget(target, new TargetResult(new TaskItem[1] { new TaskItem("include", _entry.RequestConfiguration.ProjectFullPath) }, completeSuccess ? BuildResultUtilities.GetSuccessResult() : BuildResultUtilities.GetStopWithErrorResult())); } _entry.Complete(result); } public void RaiseRequestComplete(BuildRequestEntry entry) { OnBuildRequestCompleted?.Invoke(entry); } public void RaiseRequestBlocked(BuildRequestEntry entry, int blockingId, string blockingTarget) { OnBuildRequestBlocked?.Invoke(entry, blockingId, blockingTarget, null); } public void ContinueRequest() { if (ThrowExceptionOnContinue) { throw new InvalidOperationException("ThrowExceptionOnContinue set."); } _continueEvent.Set(); } public void CancelRequest() { this.BeginCancel(); this.WaitForCancelCompletion(); } public void BeginCancel() { if (ThrowExceptionOnCancel) { throw new InvalidOperationException("ThrowExceptionOnCancel set."); } _cancelEvent.Set(); } public void WaitForCancelCompletion() { if (!_builderThread.Join(5000)) { Assert.True(false, "Builder thread did not terminate on cancel."); #if FEATURE_THREAD_ABORT _builderThread.Abort(); #endif } } #endregion #region IBuildComponent Members public void InitializeComponent(IBuildComponentHost host) { _host = host; } public void ShutdownComponent() { _host = null; } #endregion private ProjectInstance CreateStandinProject() { string content = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(content))); return project.CreateProjectInstance(); } } private MockHost _host; private AutoResetEvent _requestCompleteEvent; private BuildRequest _requestComplete_Request; private BuildResult _requestComplete_Result; private AutoResetEvent _requestResumedEvent; private BuildRequest _requestResumed_Request; private AutoResetEvent _newRequestEvent; private BuildRequestBlocker _newRequest_Request; private AutoResetEvent _engineStatusChangedEvent; private BuildRequestEngineStatus _engineStatusChanged_Status; private AutoResetEvent _newConfigurationEvent; private BuildRequestConfiguration _newConfiguration_Config; private AutoResetEvent _engineExceptionEvent; private Exception _engineException_Exception; private IBuildRequestEngine _engine; private IConfigCache _cache; private int _nodeRequestId; private int _globalRequestId; public BuildRequestEngine_Tests() { _host = new MockHost(); _nodeRequestId = 1; _globalRequestId = 1; _engineStatusChangedEvent = new AutoResetEvent(false); _requestCompleteEvent = new AutoResetEvent(false); _requestResumedEvent = new AutoResetEvent(false); _newRequestEvent = new AutoResetEvent(false); _newConfigurationEvent = new AutoResetEvent(false); _engineExceptionEvent = new AutoResetEvent(false); _engine = (IBuildRequestEngine)_host.GetComponent(BuildComponentType.RequestEngine); _cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); ConfigureEngine(_engine); } public void Dispose() { if (_engine.Status != BuildRequestEngineStatus.Uninitialized) { _engine.CleanupForBuild(); } ((IBuildComponent)_engine).ShutdownComponent(); _engineStatusChangedEvent.Dispose(); _requestCompleteEvent.Dispose(); _requestResumedEvent.Dispose(); _newRequestEvent.Dispose(); _newConfigurationEvent.Dispose(); _engineExceptionEvent.Dispose(); _host = null; } private void ConfigureEngine(IBuildRequestEngine engine) { engine.OnNewConfigurationRequest += this.Engine_NewConfigurationRequest; engine.OnRequestBlocked += this.Engine_NewRequest; engine.OnRequestComplete += this.Engine_RequestComplete; engine.OnRequestResumed += this.Engine_RequestResumed; engine.OnStatusChanged += this.Engine_EngineStatusChanged; engine.OnEngineException += this.Engine_Exception; } /// <summary> /// This test verifies that the engine properly shuts down even if there is an active build request. /// This should cause that request to cancel and fail. /// </summary> [Fact] public void TestEngineShutdownWhileActive() { BuildRequestData data = new BuildRequestData("TestFile", new Dictionary<string, string>(), "TestToolsVersion", new string[0], null); BuildRequestConfiguration config = new BuildRequestConfiguration(1, data, "2.0"); _cache.AddConfiguration(config); string[] targets = new string[3] { "target1", "target2", "target3" }; BuildRequest request = CreateNewBuildRequest(1, targets); VerifyEngineStatus(BuildRequestEngineStatus.Uninitialized); _engine.InitializeForBuild(new NodeLoggingContext(_host.LoggingService, 0, false)); _engine.SubmitBuildRequest(request); Thread.Sleep(250); VerifyEngineStatus(BuildRequestEngineStatus.Active); _engine.CleanupForBuild(); WaitForEvent(_requestCompleteEvent, "RequestComplete"); Assert.Equal(request, _requestComplete_Request); Assert.Equal(BuildResultCode.Failure, _requestComplete_Result.OverallResult); VerifyEngineStatus(BuildRequestEngineStatus.Uninitialized); } /// <summary> /// This test verifies that issuing a simple request results in a successful completion. /// </summary> [Fact] public void TestSimpleBuildScenario() { BuildRequestData data = new BuildRequestData("TestFile", new Dictionary<string, string>(), "TestToolsVersion", new string[0], null); BuildRequestConfiguration config = new BuildRequestConfiguration(1, data, "2.0"); _cache.AddConfiguration(config); string[] targets = new string[3] { "target1", "target2", "target3" }; BuildRequest request = CreateNewBuildRequest(1, targets); VerifyEngineStatus(BuildRequestEngineStatus.Uninitialized); _engine.InitializeForBuild(new NodeLoggingContext(_host.LoggingService, 0, false)); _engine.SubmitBuildRequest(request); Thread.Sleep(250); VerifyEngineStatus(BuildRequestEngineStatus.Active); WaitForEvent(_requestCompleteEvent, "RequestComplete"); Assert.Equal(request, _requestComplete_Request); Assert.Equal(BuildResultCode.Success, _requestComplete_Result.OverallResult); VerifyEngineStatus(BuildRequestEngineStatus.Idle); } /// <summary> /// This test verifies that a project which has project dependencies can issue and consume them through the /// engine interface. /// </summary> [Fact] public void TestBuildWithChildren() { BuildRequestData data = new BuildRequestData("TestFile", new Dictionary<string, string>(), "TestToolsVersion", new string[0], null); BuildRequestConfiguration config = new BuildRequestConfiguration(1, data, "2.0"); _cache.AddConfiguration(config); // Configure the builder to spawn build requests MockRequestBuilder builder = (MockRequestBuilder)_host.GetComponent(BuildComponentType.RequestBuilder); builder.NewRequests.Add(new FullyQualifiedBuildRequest[1] { new FullyQualifiedBuildRequest(config, new string[1] { "requiredTarget1" }, true) }); // Create the initial build request string[] targets = new string[3] { "target1", "target2", "target3" }; BuildRequest request = CreateNewBuildRequest(1, targets); // Kick it off VerifyEngineStatus(BuildRequestEngineStatus.Uninitialized); _engine.InitializeForBuild(new NodeLoggingContext(_host.LoggingService, 0, false)); _engine.SubmitBuildRequest(request); Thread.Sleep(250); VerifyEngineStatus(BuildRequestEngineStatus.Active); // Wait for the new requests to be spawned by the builder WaitForEvent(_newRequestEvent, "NewRequestEvent"); Assert.Equal(1, _newRequest_Request.BuildRequests[0].ConfigurationId); Assert.Single(_newRequest_Request.BuildRequests[0].Targets); Assert.Equal("requiredTarget1", _newRequest_Request.BuildRequests[0].Targets[0]); // Wait for a moment, because the build request engine thread may not have gotten around // to going to the waiting state. Thread.Sleep(250); VerifyEngineStatus(BuildRequestEngineStatus.Waiting); // Report a result to satisfy the build request BuildResult result = new BuildResult(_newRequest_Request.BuildRequests[0]); result.AddResultsForTarget("requiredTarget1", BuildResultUtilities.GetEmptySucceedingTargetResult()); _engine.UnblockBuildRequest(new BuildRequestUnblocker(result)); // Continue the request. _engine.UnblockBuildRequest(new BuildRequestUnblocker(request.GlobalRequestId)); // Wait for the original request to complete WaitForEvent(_requestCompleteEvent, "RequestComplete"); Assert.Equal(request, _requestComplete_Request); Assert.Equal(BuildResultCode.Success, _requestComplete_Result.OverallResult); VerifyEngineStatus(BuildRequestEngineStatus.Idle); } /// <summary> /// This test verifies that a project can issue a build request with an unresolved configuration and that if we resolve it, /// the build will continue and complete successfully. /// </summary> [Fact] public void TestBuildWithNewConfiguration() { BuildRequestData data = new BuildRequestData(Path.GetFullPath("TestFile"), new Dictionary<string, string>(), "TestToolsVersion", new string[0], null); BuildRequestConfiguration config = new BuildRequestConfiguration(1, data, "2.0"); _cache.AddConfiguration(config); // Configure the builder to spawn build requests MockRequestBuilder builder = (MockRequestBuilder)_host.GetComponent(BuildComponentType.RequestBuilder); BuildRequestData data2 = new BuildRequestData(Path.GetFullPath("OtherFile"), new Dictionary<string, string>(), "TestToolsVersion", new string[0], null); BuildRequestConfiguration unresolvedConfig = new BuildRequestConfiguration(data2, "2.0"); builder.NewRequests.Add(new FullyQualifiedBuildRequest[1] { new FullyQualifiedBuildRequest(unresolvedConfig, new string[1] { "requiredTarget1" }, true) }); // Create the initial build request string[] targets = new string[3] { "target1", "target2", "target3" }; BuildRequest request = CreateNewBuildRequest(1, targets); // Kick it off VerifyEngineStatus(BuildRequestEngineStatus.Uninitialized); _engine.InitializeForBuild(new NodeLoggingContext(_host.LoggingService, 0, false)); _engine.SubmitBuildRequest(request); Thread.Sleep(250); VerifyEngineStatus(BuildRequestEngineStatus.Active); // Wait for the request to generate the child request with the unresolved configuration WaitForEvent(_newConfigurationEvent, "NewConfigurationEvent"); Assert.Equal(Path.GetFullPath("OtherFile"), _newConfiguration_Config.ProjectFullPath); Assert.Equal("TestToolsVersion", _newConfiguration_Config.ToolsVersion); Assert.True(_newConfiguration_Config.WasGeneratedByNode); Thread.Sleep(250); VerifyEngineStatus(BuildRequestEngineStatus.Waiting); // Resolve the configuration BuildRequestConfigurationResponse response = new BuildRequestConfigurationResponse(_newConfiguration_Config.ConfigurationId, 2, 0); _engine.ReportConfigurationResponse(response); // Now wait for the actual requests to be issued. WaitForEvent(_newRequestEvent, "NewRequestEvent"); Assert.Equal(2, _newRequest_Request.BuildRequests[0].ConfigurationId); Assert.Equal(2, _newRequest_Request.BuildRequests[0].ConfigurationId); Assert.Single(_newRequest_Request.BuildRequests[0].Targets); Assert.Equal("requiredTarget1", _newRequest_Request.BuildRequests[0].Targets[0]); // Report a result to satisfy the build request BuildResult result = new BuildResult(_newRequest_Request.BuildRequests[0]); result.AddResultsForTarget("requiredTarget1", BuildResultUtilities.GetEmptySucceedingTargetResult()); _engine.UnblockBuildRequest(new BuildRequestUnblocker(result)); // Continue the request _engine.UnblockBuildRequest(new BuildRequestUnblocker(request.GlobalRequestId)); // Wait for the original request to complete WaitForEvent(_requestCompleteEvent, "RequestComplete"); Assert.Equal(request, _requestComplete_Request); Assert.Equal(BuildResultCode.Success, _requestComplete_Result.OverallResult); Thread.Sleep(250); VerifyEngineStatus(BuildRequestEngineStatus.Idle); } [Fact] public void TestShutdown() { } private BuildRequest CreateNewBuildRequest(int configurationId, string[] targets) { BuildRequest request = new BuildRequest(1 /* submission id */, _nodeRequestId++, configurationId, targets, null, BuildEventContext.Invalid, null); request.GlobalRequestId = _globalRequestId++; return request; } private void VerifyEngineStatus(BuildRequestEngineStatus expectedStatus) { IBuildRequestEngine engine = (IBuildRequestEngine)_host.GetComponent(BuildComponentType.RequestEngine); if (engine.Status == expectedStatus) { return; } WaitForEvent(_engineStatusChangedEvent, "EngineStatusChanged"); BuildRequestEngineStatus engineStatus = engine.Status; Assert.Equal(expectedStatus, engineStatus); } private void WaitForEvent(WaitHandle evt, string eventName) { WaitHandle[] events = new WaitHandle[2] { _engineExceptionEvent, evt }; int index = WaitHandle.WaitAny(events, 5000); if (WaitHandle.WaitTimeout == index) { Assert.True(false, "Did not receive " + eventName + " callback before the timeout expired."); } else if (index == 0) { Assert.True(false, "Received engine exception " + _engineException_Exception); } } /// <summary> /// Callback for event raised when a build request is completed /// </summary> /// <param name="request">The request which completed</param> /// <param name="result">The result for the request</param> private void Engine_RequestComplete(BuildRequest request, BuildResult result) { _requestComplete_Request = request; _requestComplete_Result = result; _requestCompleteEvent.Set(); } /// <summary> /// Callback for event raised when a request is resumed /// </summary> /// <param name="request">The request being resumed</param> private void Engine_RequestResumed(BuildRequest request) { _requestResumed_Request = request; _requestResumedEvent.Set(); } /// <summary> /// Callback for event raised when a new build request is generated by an MSBuild callback /// </summary> /// <param name="request">The new build request</param> private void Engine_NewRequest(BuildRequestBlocker blocker) { _newRequest_Request = blocker; _newRequestEvent.Set(); } /// <summary> /// Callback for event raised when the build request engine's status changes. /// </summary> /// <param name="newStatus">The new status for the engine</param> private void Engine_EngineStatusChanged(BuildRequestEngineStatus newStatus) { _engineStatusChanged_Status = newStatus; _engineStatusChangedEvent.Set(); } /// <summary> /// Callback for event raised when a new configuration needs an ID resolved. /// </summary> /// <param name="config">The configuration needing an ID</param> private void Engine_NewConfigurationRequest(BuildRequestConfiguration config) { _newConfiguration_Config = config; _newConfigurationEvent.Set(); } /// <summary> /// Callback for event raised when a new configuration needs an ID resolved. /// </summary> /// <param name="config">The configuration needing an ID</param> private void Engine_Exception(Exception e) { _engineException_Exception = e; _engineExceptionEvent.Set(); } } }
using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Configuration; using System.Data.Common; using System.Data.OleDb; using System.IO; using MySql.Data.MySqlClient; using Npgsql; using SPD.Exceptions; namespace SPD.DAL { /// <summary> /// Utility to manage the database connection /// </summary> internal class DbUtil { const string SQL_LAST_INSERTED_ROW = "SELECT @@Identity"; private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static Databases database = Databases.Undefined; public static Databases Database { get { if (database == Databases.Undefined) { database = SPD.DAL.Properties.Settings.Default.Database; } return database; } } /// <summary> /// Chached connection variable /// </summary> private static IDbConnection conn = null; /// <summary> /// Chached open connection counter /// </summary> private static int nestedOpens = 0; /// <summary> /// Chached connection string /// </summary> private static string connString = ""; /// <summary> /// Gets the cached connection. /// </summary> /// <returns></returns> private static IDbConnection GetCachedConnection() { if (conn == null) { if (String.IsNullOrEmpty(connString)) { switch (Database) { case Databases.Access : if (!File.Exists(DBTools.GetDatabaseFullFilename())) { log.Error("GetCachedConnection: Databasefile: " + DBTools.GetDatabaseFullFilename() + "does not exist."); throw new SPDException(null, "Databasefile:" + Environment.NewLine + DBTools.GetDatabaseFullFilename() + Environment.NewLine + "does not exist!", null); } FileAttributes fileAttributesMdb = File.GetAttributes(DBTools.GetDatabaseFullFilename()); if ((fileAttributesMdb & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { log.Error("GetCachedConnection: Databasefile: " + DBTools.GetDatabaseFullFilename() + " is Readonly."); throw new SPDException(null, "Databasefile:" + Environment.NewLine + DBTools.GetDatabaseFullFilename() + Environment.NewLine + "is Readonly!", null); } connString = String.Format("Data Source={0};Provider=Microsoft.Jet.OLEDB.4.0;", DBTools.GetDatabaseFullFilename()); break; case Databases.Access2007: if (!File.Exists(DBTools.GetDatabaseFullFilename())) { log.Error("GetCachedConnection: Databasefile: " + DBTools.GetDatabaseFullFilename() + "does not exist."); throw new SPDException(null, "Databasefile:" + Environment.NewLine + DBTools.GetDatabaseFullFilename() + Environment.NewLine + "does not exist!", null); } FileAttributes fileAttributesAccb = File.GetAttributes(DBTools.GetDatabaseFullFilename()); if ((fileAttributesAccb & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { log.Error("GetCachedConnection: Databasefile: " + DBTools.GetDatabaseFullFilename() + " is Readonly."); throw new SPDException(null, "Databasefile:" + Environment.NewLine + DBTools.GetDatabaseFullFilename() + Environment.NewLine + "is Readonly!", null); } connString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Persist Security Info=False;", DBTools.GetDatabaseFullFilename()); break; case Databases.MySql : connString = String.Format("SERVER={0};DATABASE={1};UID={2};PASSWORD={3};Port={4}", SPD.DAL.Properties.Settings.Default.MySQLServer, SPD.DAL.Properties.Settings.Default.MySQLDatabase, SPD.DAL.Properties.Settings.Default.MySQLUser, SPD.DAL.Properties.Settings.Default.MySQLPassword, SPD.DAL.Properties.Settings.Default.MySQLPort); break; case Databases.PostgreSQL: connString = String.Format("Server={0};Port={1};User Id={2};Password={3};Database={4};", SPD.DAL.Properties.Settings.Default.PostgreSQLServer, SPD.DAL.Properties.Settings.Default.PostgreSQLPort, SPD.DAL.Properties.Settings.Default.PostgreSQLUser, SPD.DAL.Properties.Settings.Default.PostgreSQLPassword, SPD.DAL.Properties.Settings.Default.PostgreSQLDatabase); break; default : break; } } switch (Database) { case Databases.Access : case Databases.Access2007: conn = new OleDbConnection(connString); break; case Databases.MySql : conn = new MySqlConnection(connString); break; case Databases.PostgreSQL: conn = new NpgsqlConnection(connString); break; default: break; } } log.Debug("GetCachedConnection: " + connString); return conn; } /// <summary> /// Opens the connection. /// </summary> /// <returns></returns> public static IDbConnection OpenConnection() { IDbConnection conn = GetCachedConnection(); if (conn.State != ConnectionState.Open) { try { conn.Open(); } catch (InvalidOperationException e) { if (Database == Databases.Access2007) { throw new SPDException(e, "Error while opening Database Connection. Download and install the 32 bit Version of", @"https://www.microsoft.com/en-us/download/details.aspx?id=54920"); } else { throw new SPDException(e, "Error while opening Database Connection.", null); } } nestedOpens = 0; } nestedOpens++; log.Debug("OpenConnection - nestedOpens: " + nestedOpens); return conn; } /// <summary> /// Gets the current cached connection. /// </summary> /// <value>The current chached connection.</value> public static IDbConnection CurrentConnection { get { return conn; } } /// <summary> /// Decrements the connection Counter if no one is left close the connection. /// </summary> public static void CloseConnection() { if (--nestedOpens == 0) { conn.Close(); } log.Debug("CloseConnection - nestedOpens: " + nestedOpens); } /// <summary> /// Creates the command. /// </summary> /// <param name="sqlStr">The SQL STR.</param> /// <param name="conn">The conn.</param> /// <returns></returns> public static IDbCommand CreateCommand(string sqlStr, IDbConnection conn) { IDbCommand cmd; switch (Database) { case Databases.Access : case Databases.Access2007: cmd = new OleDbCommand(sqlStr); break; case Databases.MySql : cmd = conn.CreateCommand(); break; case Databases.PostgreSQL: cmd = conn.CreateCommand(); break; default : cmd = null; break; } cmd.Connection = conn; cmd.CommandText = sqlStr; log.Debug("Create Command: " + sqlStr); return cmd; } /// <summary> /// Creates the parameter. /// </summary> /// <param name="pName">Name of the Parameter</param> /// <param name="dbType">Type of the database-datatype</param> /// <returns></returns> public static IDbDataParameter CreateParameter(string pName, DbType dbType) { IDbDataParameter param; switch (Database) { case Databases.Access : case Databases.Access2007: param = new OleDbParameter(pName, dbType); break; case Databases.MySql: MySqlDbType mysqldbtype; switch (dbType) { case DbType.Int64 : mysqldbtype = MySqlDbType.Int64; break; case DbType.String: mysqldbtype = MySqlDbType.Text; break; default: //ulgy!! mysqldbtype = MySqlDbType.Int64; break; } param = new MySqlParameter(pName, mysqldbtype); break; case Databases.PostgreSQL: param = new NpgsqlParameter(pName, dbType); break; default : param = null; break; } log.Debug("Create Parameter " + pName); return param; } /// <summary> /// Creates the adapter. /// </summary> /// <param name="selStr">The select string</param> /// <param name="conn">The connection</param> /// <returns></returns> public static DbDataAdapter CreateAdapter(string selStr, IDbConnection conn) { DbDataAdapter adpt = new OleDbDataAdapter(); adpt.SelectCommand = (DbCommand)CreateCommand(selStr, conn); log.Debug("Create Adapter: " + selStr); return adpt; } /// <summary> /// Creates the command builder. /// </summary> /// <param name="adpt">The adapter</param> /// <returns></returns> public static DbCommandBuilder CreateCommandBuilder( DbDataAdapter adpt) { DbCommandBuilder cmdBuilder = new OleDbCommandBuilder(); cmdBuilder.DataAdapter = adpt; log.Debug("CreateCommandBuilder"); return cmdBuilder; } /// <summary> /// Returns the last generated primary Key /// </summary> /// <param name="comm">the insert command</param> /// <param name="lastInsertedRowCmd"> the ole specific last inserted row command</param> /// <param name="insertRet"> the return of insertscecure scalar</param> /// <returns></returns> public static long getGeneratedId(IDbCommand comm, IDbCommand lastInsertedRowCmd, Object insertRet) { switch (Database) { case Databases.Access: case Databases.Access2007: if (lastInsertedRowCmd == null) { lastInsertedRowCmd = DbUtil.CreateCommand(SQL_LAST_INSERTED_ROW, DbUtil.CurrentConnection); } return Convert.ToInt64(lastInsertedRowCmd.ExecuteScalar()); case Databases.MySql: return ((MySqlCommand)comm).LastInsertedId; case Databases.PostgreSQL: return (long) insertRet; default: return 0; } } /// <summary> /// returns is Backup is supported with DB engine /// </summary> /// <returns></returns> public static bool SupportsBackup() { switch (Database) { case Databases.Access: case Databases.Access2007: return true; case Databases.MySql: case Databases.PostgreSQL: return false; default: return false; } } /// <summary> /// returnind insert Appendix /// </summary> /// <param name="id"></param> /// <returns></returns> public static String GetAppendix(string id) { switch (Database) { case Databases.Access: case Databases.Access2007: case Databases.MySql: return String.Empty; case Databases.PostgreSQL: return " RETURNING " + id + " "; default: return String.Empty; } } } }
/* 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.Web; using Adxstudio.Xrm.Core; using Adxstudio.Xrm.Core.Flighting; using Adxstudio.Xrm.Resources; using Microsoft.Xrm.Client; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Client; using Microsoft.Xrm.Sdk.Metadata; namespace Adxstudio.Xrm.Products { /// <summary> /// Provides data operations for a single product, as represented by a Product entity. /// </summary> public class ProductDataAdapter : IProductDataAdapter { internal enum StateCode { Active = 0, Inactive = 1 } /// <summary> /// Constructor /// </summary> /// <param name="product">Product Entity Reference</param> /// <param name="dependencies">Data Adapter Dependencies</param> public ProductDataAdapter(EntityReference product, IDataAdapterDependencies dependencies) { if (product == null) throw new ArgumentNullException("product"); if (product.LogicalName != "product") throw new ArgumentException(string.Format(ResourceManager.GetString("Value_Missing_For_LogicalName"), product.LogicalName), "product"); if (dependencies == null) throw new ArgumentNullException("dependencies"); Product = product; Dependencies = dependencies; } /// <summary> /// Constructor /// </summary> /// <param name="product">Product Entity Reference</param> /// <param name="dependencies">Data Adapter Dependencies</param> public ProductDataAdapter(Entity product, IDataAdapterDependencies dependencies) : this(product.ToEntityReference(), dependencies) { } /// <summary> /// Constructor /// </summary> /// <param name="product">Product Entity Reference</param> /// <param name="dependencies">Data Adapter Dependencies</param> public ProductDataAdapter(IProduct product, IDataAdapterDependencies dependencies) : this(product.Entity, dependencies) { } /// <summary> /// Constructor /// </summary> /// <param name="product">Product Entity Reference</param> /// <param name="portalName">The configured name of the portal to get and set data for.</param> public ProductDataAdapter(EntityReference product, string portalName = null) : this(product, new PortalConfigurationDataAdapterDependencies(portalName)) { } /// <summary> /// Constructor /// </summary> /// <param name="product">Product Entity Reference</param> /// <param name="portalName">The configured name of the portal to get and set data for.</param> public ProductDataAdapter(Entity product, string portalName = null) : this(product, new PortalConfigurationDataAdapterDependencies(portalName)) { } /// <summary> /// Constructor /// </summary> /// <param name="product">Product Entity Reference</param> /// <param name="portalName">The configured name of the portal to get and set data for.</param> public ProductDataAdapter(IProduct product, string portalName = null) : this(product, new PortalConfigurationDataAdapterDependencies(portalName)) { } protected IDataAdapterDependencies Dependencies { get; private set; } protected EntityReference Product { get; set; } public virtual IProduct Select() { var serviceContext = Dependencies.GetServiceContext(); var product = serviceContext.GetProduct(Product.Id); return product == null ? null : new ProductFactory(serviceContext, Dependencies.GetPortalUser(), Dependencies.GetWebsite()).Create(new[] { product }).FirstOrDefault(); } public IEnumerable<ISalesLiterature> SelectSalesLiterature(string name) { var serviceContext = Dependencies.GetServiceContext(); var product = serviceContext.GetProduct(Product.Id); return product.GetRelatedEntities(serviceContext, "productsalesliterature_association") .Where(e => e.GetAttributeValue<bool?>("iscustomerviewable").GetValueOrDefault() && e.GetAttributeValue<string>("name") == name) .ToArray() .Select(e => new SalesLiterature(e, serviceContext.GetEntityMetadata(e.LogicalName, EntityFilters.Attributes))) .OrderBy(e => e.Name) .ToArray(); } public virtual IEnumerable<ISalesAttachment> SelectSalesAttachments(SalesLiteratureTypeCode type) { var serviceContext = Dependencies.GetServiceContext(); var salesAttachments = Enumerable.Empty<ISalesAttachment>(); var product = serviceContext.GetProduct(Product.Id); var salesLiterature = product.GetRelatedEntities(serviceContext, "productsalesliterature_association") .Where(e => e.GetAttributeValue<bool?>("iscustomerviewable").GetValueOrDefault() && e.GetAttributeValue<OptionSetValue>("literaturetypecode") != null && e.GetAttributeValue<OptionSetValue>("literaturetypecode").Value == (int)type) .ToList(); if (!salesLiterature.Any()) { return salesAttachments; } return salesLiterature.Select(literature => SelectSalesAttachments(literature.ToEntityReference())) .Aggregate(salesAttachments, (current, attachments) => current.Union(attachments)) .OrderBy(e => e.FileName); } public virtual IEnumerable<ISalesAttachment> SelectSalesAttachments(EntityReference salesLiterature) { var serviceContext = Dependencies.GetServiceContext(); var website = Dependencies.GetWebsite(); return serviceContext.CreateQuery("salesliteratureitem") .Where(e => e.GetAttributeValue<EntityReference>("salesliteratureid") == salesLiterature) .ToArray() .Select(e => new SalesAttachment(e, website)) .OrderBy(e => e.FileName) .ToArray(); } public virtual IEnumerable<IProductImageGalleryNode> SelectImageGalleryNodes() { var salesAttachments = SelectSalesAttachments(SalesLiteratureTypeCode.ImageGallery).Where(o => o.HasFile); var nodes = from attachment in salesAttachments group attachment by attachment.Title into g let thumbnail = g.FirstOrDefault(o => o.Keywords != null && o.Keywords.Contains("thumbnail")) let image = g.FirstOrDefault(o => o.Keywords == null || !o.Keywords.Contains("thumbnail")) orderby image.Title select new ProductImageGalleryNode(image, thumbnail, image == null ? string.Empty : image.URL, thumbnail == null ? string.Empty : thumbnail.URL); return nodes; } public virtual void CreateReview(string title, string content, double rating, int maximumRatingValue, string reviewerName, string reviewerLocation, string reviewerEmail, bool recommend) { var context = Dependencies.GetServiceContext(); var httpContext = Dependencies.GetRequestContext().HttpContext; var reviewerContact = Dependencies.GetPortalUser(); title.ThrowOnNullOrWhitespace("title", ResourceManager.GetString("Value_Null_In_Create_Review_Exception")); reviewerName.ThrowOnNullOrWhitespace("reviewerName", ResourceManager.GetString("Value_Null_In_Create_Review_Exception")); if (!httpContext.Request.IsAuthenticated) { reviewerEmail.ThrowOnNullOrWhitespace("reviewerEmail", ResourceManager.GetString("Value_Null_In_Anonymous_Review_Exception")); } if (rating < 1) { throw new ArgumentNullException("rating", ResourceManager.GetString("Must_Be_Greater_Than_Zero_Exception")); } var review = new Entity("adx_review"); review["adx_title"] = title; review["adx_name"] = title; if (!string.IsNullOrWhiteSpace(content)) { review["adx_content"] = content; } review["adx_rating"] = rating; if (maximumRatingValue < 1) { maximumRatingValue = 5; } review["adx_ratingrationalvalue"] = rating / maximumRatingValue; review["adx_maximumvalue"] = maximumRatingValue; review["adx_recommend"] = recommend; review["adx_submittedon"] = DateTime.UtcNow; review["adx_createdbyusername"] = httpContext.Request.IsAuthenticated ? httpContext.User.Identity.Name : httpContext.Request.AnonymousID; // review["adx_createdbyipaddress"] = httpContext.Request.UserHostAddress; if (reviewerContact != null) { review["adx_reviewercontact"] = reviewerContact; //var contact = new Entity("contact") {Id = reviewerContact.Id}; //contact["nickname"] = reviewerName; //if (!context.IsAttached(contact)) //{ // context.Attach(contact); //} //context.UpdateObject(contact); } review["adx_reviewername"] = reviewerName; if (!httpContext.Request.IsAuthenticated) { review["adx_revieweremail"] = reviewerEmail; } if (!string.IsNullOrWhiteSpace(reviewerLocation)) { review["adx_reviewerlocation"] = reviewerLocation; } if (Product != null) { review["adx_product"] = Product; } context.AddObject(review); context.SaveChanges(); if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage)) { PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.ProductReview, HttpContext.Current, "create_product_review", 1, review.ToEntityReference(), "create"); } } /// <summary> /// Indicates if a user has reviewed the product. /// </summary> /// <param name="user"></param> public bool HasReview(EntityReference user) { if (user == null) throw new ArgumentNullException("user"); ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Start: {0}:{1}", user.LogicalName, user.Id)); var serviceContext = Dependencies.GetServiceContext(); var existingReview = SelectReview(serviceContext, user); var hasReview = existingReview != null; ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("End: {0}:{1}, {2}", user.LogicalName, user.Id, hasReview)); return hasReview; } /// <summary> /// Indicates if an anonymous user has reviewed the product. /// </summary> /// <param name="username"></param> public bool HasReview(string username) { var serviceContext = Dependencies.GetServiceContext(); var existingReview = SelectReview(serviceContext, username); var hasReview = existingReview != null; return hasReview; } protected Entity SelectReview(OrganizationServiceContext serviceContext, EntityReference user) { if (serviceContext == null) throw new ArgumentNullException("serviceContext"); if (user == null) throw new ArgumentNullException("user"); return serviceContext.CreateQuery("adx_review") .FirstOrDefault(e => e.GetAttributeValue<EntityReference>("adx_reviewercontact") == user && e.GetAttributeValue<EntityReference>("adx_product") == Product); } protected Entity SelectReview(OrganizationServiceContext serviceContext, string username) { if (serviceContext == null) throw new ArgumentNullException("serviceContext"); return serviceContext.CreateQuery("adx_review") .FirstOrDefault(e => e.GetAttributeValue<string>("adx_createdbyusername") == username && e.GetAttributeValue<EntityReference>("adx_product") == Product); } } }
using System; using System.Collections.Generic; using Microsoft.Extensions.Logging; using Orleans.Serialization; namespace Orleans.Runtime { internal class IncomingMessageBuffer { private const int Kb = 1024; private const int DEFAULT_MAX_SUSTAINED_RECEIVE_BUFFER_SIZE = 1024 * Kb; // 1mg private const int GROW_MAX_BLOCK_SIZE = 1024 * Kb; // 1mg private static readonly ArraySegment<byte>[] EmptyBuffers = {new ArraySegment<byte>(new byte[0]), }; private readonly List<ArraySegment<byte>> readBuffer; private readonly int maxSustainedBufferSize; private int currentBufferSize; private readonly byte[] lengthBuffer; private int headerLength; private int bodyLength; private int receiveOffset; private int decodeOffset; private readonly bool supportForwarding; private ILogger Log; private readonly SerializationManager serializationManager; private readonly DeserializationContext deserializationContext; internal const int DEFAULT_RECEIVE_BUFFER_SIZE = 128 * Kb; // 128k public IncomingMessageBuffer( ILoggerFactory loggerFactory, SerializationManager serializationManager, bool supportForwarding = false, int receiveBufferSize = DEFAULT_RECEIVE_BUFFER_SIZE, int maxSustainedReceiveBufferSize = DEFAULT_MAX_SUSTAINED_RECEIVE_BUFFER_SIZE) { Log = loggerFactory.CreateLogger<IncomingMessageBuffer>(); this.serializationManager = serializationManager; this.supportForwarding = supportForwarding; currentBufferSize = receiveBufferSize; maxSustainedBufferSize = maxSustainedReceiveBufferSize; lengthBuffer = new byte[Message.LENGTH_HEADER_SIZE]; readBuffer = BufferPool.GlobalPool.GetMultiBuffer(currentBufferSize); receiveOffset = 0; decodeOffset = 0; headerLength = 0; bodyLength = 0; deserializationContext = new DeserializationContext(this.serializationManager) { StreamReader = new BinaryTokenStreamReader(EmptyBuffers) }; } public List<ArraySegment<byte>> BuildReceiveBuffer() { // Opportunistic reset to start of buffer if (decodeOffset == receiveOffset) { decodeOffset = 0; receiveOffset = 0; } return ByteArrayBuilder.BuildSegmentList(readBuffer, receiveOffset); } // Copies receive buffer into read buffer for futher processing public void UpdateReceivedData(byte[] receiveBuffer, int bytesRead) { var newReceiveOffset = receiveOffset + bytesRead; while (newReceiveOffset > currentBufferSize) { GrowBuffer(); } int receiveBufferOffset = 0; var lengthSoFar = 0; foreach (var segment in readBuffer) { var bytesStillToSkip = receiveOffset - lengthSoFar; lengthSoFar += segment.Count; if (segment.Count <= bytesStillToSkip) { continue; } if(bytesStillToSkip > 0) // This is the first buffer { var bytesToCopy = Math.Min(segment.Count - bytesStillToSkip, bytesRead - receiveBufferOffset); Buffer.BlockCopy(receiveBuffer, receiveBufferOffset, segment.Array, bytesStillToSkip, bytesToCopy); receiveBufferOffset += bytesToCopy; } else { var bytesToCopy = Math.Min(segment.Count, bytesRead - receiveBufferOffset); Buffer.BlockCopy(receiveBuffer, receiveBufferOffset, segment.Array, 0, bytesToCopy); receiveBufferOffset += Math.Min(bytesToCopy, segment.Count); } if (receiveBufferOffset == bytesRead) { break; } } receiveOffset += bytesRead; } public void UpdateReceivedData(int bytesRead) { receiveOffset += bytesRead; } public void Reset() { receiveOffset = 0; decodeOffset = 0; headerLength = 0; bodyLength = 0; } public bool TryDecodeMessage(out Message msg) { msg = null; // Is there enough read into the buffer to continue (at least read the lengths?) if (receiveOffset - decodeOffset < CalculateKnownMessageSize()) return false; // parse lengths if needed if (headerLength == 0 || bodyLength == 0) { // get length segments List<ArraySegment<byte>> lenghts = ByteArrayBuilder.BuildSegmentListWithLengthLimit(readBuffer, decodeOffset, Message.LENGTH_HEADER_SIZE); // copy length segment to buffer int lengthBufferoffset = 0; foreach (ArraySegment<byte> seg in lenghts) { Buffer.BlockCopy(seg.Array, seg.Offset, lengthBuffer, lengthBufferoffset, seg.Count); lengthBufferoffset += seg.Count; } // read lengths headerLength = BitConverter.ToInt32(lengthBuffer, 0); bodyLength = BitConverter.ToInt32(lengthBuffer, 4); } // If message is too big for current buffer size, grow while (decodeOffset + CalculateKnownMessageSize() > currentBufferSize) { GrowBuffer(); } // Is there enough read into the buffer to read full message if (receiveOffset - decodeOffset < CalculateKnownMessageSize()) return false; // decode header int headerOffset = decodeOffset + Message.LENGTH_HEADER_SIZE; List<ArraySegment<byte>> header = ByteArrayBuilder.BuildSegmentListWithLengthLimit(readBuffer, headerOffset, headerLength); // decode body int bodyOffset = headerOffset + headerLength; List<ArraySegment<byte>> body = ByteArrayBuilder.BuildSegmentListWithLengthLimit(readBuffer, bodyOffset, bodyLength); // build message this.deserializationContext.Reset(); this.deserializationContext.StreamReader.Reset(header); msg = new Message { Headers = SerializationManager.DeserializeMessageHeaders(this.deserializationContext) }; try { if (this.supportForwarding) { // If forwarding is supported, then deserialization will be deferred until the body value is needed. // Need to maintain ownership of buffer, so we need to duplicate the body buffer. msg.SetBodyBytes(this.DuplicateBuffer(body)); } else { // Attempt to deserialize the body immediately. msg.DeserializeBodyObject(this.serializationManager, body); } } finally { MessagingStatisticsGroup.OnMessageReceive(msg, headerLength, bodyLength); if (headerLength + bodyLength > this.serializationManager.LargeObjectSizeThreshold) { Log.Info( ErrorCode.Messaging_LargeMsg_Incoming, "Receiving large message Size={0} HeaderLength={1} BodyLength={2}. Msg={3}", headerLength + bodyLength, headerLength, bodyLength, msg.ToString()); if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Received large message {0}", msg.ToLongString()); } // update parse receiveOffset and clear lengths decodeOffset = bodyOffset + bodyLength; headerLength = 0; bodyLength = 0; AdjustBuffer(); } return true; } /// <summary> /// This call cleans up the buffer state to make it optimal for next read. /// The leading chunks, used by any processed messages, are removed from the front /// of the buffer and added to the back. Decode and receiver offsets are adjusted accordingly. /// If the buffer was grown over the max sustained buffer size (to read a large message) it is shrunken. /// </summary> private void AdjustBuffer() { // drop buffers consumed by messages and adjust offsets // TODO: This can be optimized further. Linked lists? int consumedBytes = 0; while (readBuffer.Count != 0) { ArraySegment<byte> seg = readBuffer[0]; if (seg.Count <= decodeOffset - consumedBytes) { consumedBytes += seg.Count; readBuffer.Remove(seg); BufferPool.GlobalPool.Release(seg.Array); } else { break; } } decodeOffset -= consumedBytes; receiveOffset -= consumedBytes; // backfill any consumed buffers, to preserve buffer size. if (consumedBytes != 0) { int backfillBytes = consumedBytes; // If buffer is larger than max sustained size, backfill only up to max sustained buffer size. if (currentBufferSize > maxSustainedBufferSize) { backfillBytes = Math.Max(consumedBytes + maxSustainedBufferSize - currentBufferSize, 0); currentBufferSize -= consumedBytes; currentBufferSize += backfillBytes; } if (backfillBytes > 0) { readBuffer.AddRange(BufferPool.GlobalPool.GetMultiBuffer(backfillBytes)); } } } private int CalculateKnownMessageSize() { return headerLength + bodyLength + Message.LENGTH_HEADER_SIZE; } private List<ArraySegment<byte>> DuplicateBuffer(List<ArraySegment<byte>> body) { var dupBody = new List<ArraySegment<byte>>(body.Count); foreach (ArraySegment<byte> seg in body) { var dupSeg = new ArraySegment<byte>(BufferPool.GlobalPool.GetBuffer(), seg.Offset, seg.Count); Buffer.BlockCopy(seg.Array, seg.Offset, dupSeg.Array, dupSeg.Offset, seg.Count); dupBody.Add(dupSeg); } return dupBody; } private void GrowBuffer() { //TODO: Add configurable max message size for safety //TODO: Review networking layer and add max size checks to all dictionaries, arrays, or other variable sized containers. // double buffer size up to max grow block size, then only grow it in those intervals int growBlockSize = Math.Min(currentBufferSize, GROW_MAX_BLOCK_SIZE); readBuffer.AddRange(BufferPool.GlobalPool.GetMultiBuffer(growBlockSize)); currentBufferSize += growBlockSize; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Security; using System.Threading; namespace Internal.Runtime.Augments { public class RuntimeThread : CriticalFinalizerObject { private static int s_optimalMaxSpinWaitsPerSpinIteration; internal RuntimeThread() { } public static RuntimeThread Create(ThreadStart start) => new Thread(start); public static RuntimeThread Create(ThreadStart start, int maxStackSize) => new Thread(start, maxStackSize); public static RuntimeThread Create(ParameterizedThreadStart start) => new Thread(start); public static RuntimeThread Create(ParameterizedThreadStart start, int maxStackSize) => new Thread(start, maxStackSize); private Thread AsThread() { Debug.Assert(this is Thread); return (Thread)this; } public static RuntimeThread CurrentThread => Thread.CurrentThread; /*========================================================================= ** Returns true if the thread has been started and is not dead. =========================================================================*/ public extern bool IsAlive { [MethodImpl(MethodImplOptions.InternalCall)] get; } /*========================================================================= ** Return whether or not this thread is a background thread. Background ** threads do not affect when the Execution Engine shuts down. ** ** Exceptions: ThreadStateException if the thread is dead. =========================================================================*/ public bool IsBackground { get { return IsBackgroundNative(); } set { SetBackgroundNative(value); } } [MethodImpl(MethodImplOptions.InternalCall)] private extern bool IsBackgroundNative(); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetBackgroundNative(bool isBackground); /*========================================================================= ** Returns true if the thread is a threadpool thread. =========================================================================*/ public extern bool IsThreadPoolThread { [MethodImpl(MethodImplOptions.InternalCall)] get; } public int ManagedThreadId => AsThread().ManagedThreadId; public string Name { get { return AsThread().Name; } set { AsThread().Name = value; } } /*========================================================================= ** Returns the priority of the thread. ** ** Exceptions: ThreadStateException if the thread is dead. =========================================================================*/ public ThreadPriority Priority { get { return (ThreadPriority)GetPriorityNative(); } set { SetPriorityNative((int)value); } } [MethodImpl(MethodImplOptions.InternalCall)] private extern int GetPriorityNative(); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetPriorityNative(int priority); /*========================================================================= ** Return the thread state as a consistent set of bits. This is more ** general then IsAlive or IsBackground. =========================================================================*/ public ThreadState ThreadState { get { return (ThreadState)GetThreadStateNative(); } } [MethodImpl(MethodImplOptions.InternalCall)] private extern int GetThreadStateNative(); public ApartmentState GetApartmentState() { #if FEATURE_COMINTEROP_APARTMENT_SUPPORT return (ApartmentState)GetApartmentStateNative(); #else // !FEATURE_COMINTEROP_APARTMENT_SUPPORT Debug.Assert(false); // the Thread class in CoreFX should have handled this case return ApartmentState.MTA; #endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT } /*========================================================================= ** An unstarted thread can be marked to indicate that it will host a ** single-threaded or multi-threaded apartment. =========================================================================*/ public bool TrySetApartmentState(ApartmentState state) { #if FEATURE_COMINTEROP_APARTMENT_SUPPORT return SetApartmentStateHelper(state, false); #else // !FEATURE_COMINTEROP_APARTMENT_SUPPORT Debug.Assert(false); // the Thread class in CoreFX should have handled this case return false; #endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT } #if FEATURE_COMINTEROP_APARTMENT_SUPPORT internal bool SetApartmentStateHelper(ApartmentState state, bool fireMDAOnMismatch) { ApartmentState retState = (ApartmentState)SetApartmentStateNative((int)state, fireMDAOnMismatch); // Special case where we pass in Unknown and get back MTA. // Once we CoUninitialize the thread, the OS will still // report the thread as implicitly in the MTA if any // other thread in the process is CoInitialized. if ((state == System.Threading.ApartmentState.Unknown) && (retState == System.Threading.ApartmentState.MTA)) return true; if (retState != state) return false; return true; } [MethodImpl(MethodImplOptions.InternalCall)] internal extern int GetApartmentStateNative(); [MethodImpl(MethodImplOptions.InternalCall)] internal extern int SetApartmentStateNative(int state, bool fireMDAOnMismatch); #endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT #if FEATURE_COMINTEROP [MethodImpl(MethodImplOptions.InternalCall)] public extern void DisableComObjectEagerCleanup(); #else // !FEATURE_COMINTEROP public void DisableComObjectEagerCleanup() { Debug.Assert(false); // the Thread class in CoreFX should have handled this case } #endif // FEATURE_COMINTEROP /*========================================================================= ** Interrupts a thread that is inside a Wait(), Sleep() or Join(). If that ** thread is not currently blocked in that manner, it will be interrupted ** when it next begins to block. =========================================================================*/ public void Interrupt() => InterruptInternal(); // Internal helper (since we can't place security demands on // ecalls/fcalls). [MethodImpl(MethodImplOptions.InternalCall)] private extern void InterruptInternal(); /*========================================================================= ** Waits for the thread to die or for timeout milliseconds to elapse. ** Returns true if the thread died, or false if the wait timed out. If ** Timeout.Infinite is given as the parameter, no timeout will occur. ** ** Exceptions: ArgumentException if timeout < 0. ** ThreadInterruptedException if the thread is interrupted while waiting. ** ThreadStateException if the thread has not been started yet. =========================================================================*/ public void Join() => JoinInternal(Timeout.Infinite); public bool Join(int millisecondsTimeout) => JoinInternal(millisecondsTimeout); [MethodImpl(MethodImplOptions.InternalCall)] private extern bool JoinInternal(int millisecondsTimeout); public static void Sleep(int millisecondsTimeout) => Thread.Sleep(millisecondsTimeout); [DllImport(JitHelpers.QCall)] [SuppressUnmanagedCodeSecurity] private static extern int GetOptimalMaxSpinWaitsPerSpinIterationInternal(); /// <summary> /// Max value to be passed into <see cref="SpinWait(int)"/> for optimal delaying. This value is normalized to be /// appropriate for the processor. /// </summary> internal static int OptimalMaxSpinWaitsPerSpinIteration { get { if (s_optimalMaxSpinWaitsPerSpinIteration != 0) { return s_optimalMaxSpinWaitsPerSpinIteration; } // This is done lazily because the first call to the function below in the process triggers a measurement that // takes a nontrivial amount of time if the measurement has not already been done in the backgorund. // See Thread::InitializeYieldProcessorNormalized(), which describes and calculates this value. s_optimalMaxSpinWaitsPerSpinIteration = GetOptimalMaxSpinWaitsPerSpinIterationInternal(); Debug.Assert(s_optimalMaxSpinWaitsPerSpinIteration > 0); return s_optimalMaxSpinWaitsPerSpinIteration; } } public static void SpinWait(int iterations) => Thread.SpinWait(iterations); public static bool Yield() => Thread.Yield(); public void Start() => AsThread().Start(); public void Start(object parameter) => AsThread().Start(parameter); } }
// 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. #if !NET46 using System.Buffers; #endif using System.Diagnostics; using System.Diagnostics.Contracts; using System.IO; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Net.Http { public abstract class HttpContent : IDisposable { private HttpContentHeaders _headers; private MemoryStream _bufferedContent; private bool _disposed; private Task<Stream> _contentReadStream; private bool _canCalculateLength; internal const int MaxBufferSize = int.MaxValue; internal static readonly Encoding DefaultStringEncoding = Encoding.UTF8; private const int UTF8CodePage = 65001; private const int UTF8PreambleLength = 3; private const byte UTF8PreambleByte0 = 0xEF; private const byte UTF8PreambleByte1 = 0xBB; private const byte UTF8PreambleByte2 = 0xBF; private const int UTF8PreambleFirst2Bytes = 0xEFBB; #if !uap // UTF32 not supported on Phone private const int UTF32CodePage = 12000; private const int UTF32PreambleLength = 4; private const byte UTF32PreambleByte0 = 0xFF; private const byte UTF32PreambleByte1 = 0xFE; private const byte UTF32PreambleByte2 = 0x00; private const byte UTF32PreambleByte3 = 0x00; #endif private const int UTF32OrUnicodePreambleFirst2Bytes = 0xFFFE; private const int UnicodeCodePage = 1200; private const int UnicodePreambleLength = 2; private const byte UnicodePreambleByte0 = 0xFF; private const byte UnicodePreambleByte1 = 0xFE; private const int BigEndianUnicodeCodePage = 1201; private const int BigEndianUnicodePreambleLength = 2; private const byte BigEndianUnicodePreambleByte0 = 0xFE; private const byte BigEndianUnicodePreambleByte1 = 0xFF; private const int BigEndianUnicodePreambleFirst2Bytes = 0xFEFF; #if DEBUG static HttpContent() { // Ensure the encoding constants used in this class match the actual data from the Encoding class AssertEncodingConstants(Encoding.UTF8, UTF8CodePage, UTF8PreambleLength, UTF8PreambleFirst2Bytes, UTF8PreambleByte0, UTF8PreambleByte1, UTF8PreambleByte2); #if !uap // UTF32 not supported on Phone AssertEncodingConstants(Encoding.UTF32, UTF32CodePage, UTF32PreambleLength, UTF32OrUnicodePreambleFirst2Bytes, UTF32PreambleByte0, UTF32PreambleByte1, UTF32PreambleByte2, UTF32PreambleByte3); #endif AssertEncodingConstants(Encoding.Unicode, UnicodeCodePage, UnicodePreambleLength, UTF32OrUnicodePreambleFirst2Bytes, UnicodePreambleByte0, UnicodePreambleByte1); AssertEncodingConstants(Encoding.BigEndianUnicode, BigEndianUnicodeCodePage, BigEndianUnicodePreambleLength, BigEndianUnicodePreambleFirst2Bytes, BigEndianUnicodePreambleByte0, BigEndianUnicodePreambleByte1); } private static void AssertEncodingConstants(Encoding encoding, int codePage, int preambleLength, int first2Bytes, params byte[] preamble) { Debug.Assert(encoding != null); Debug.Assert(preamble != null); Debug.Assert(codePage == encoding.CodePage, "Encoding code page mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.CodePage): {1}", codePage, encoding.CodePage); byte[] actualPreamble = encoding.GetPreamble(); Debug.Assert(preambleLength == actualPreamble.Length, "Encoding preamble length mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.GetPreamble().Length): {1}", preambleLength, actualPreamble.Length); Debug.Assert(actualPreamble.Length >= 2); int actualFirst2Bytes = actualPreamble[0] << 8 | actualPreamble[1]; Debug.Assert(first2Bytes == actualFirst2Bytes, "Encoding preamble first 2 bytes mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual: {1}", first2Bytes, actualFirst2Bytes); Debug.Assert(preamble.Length == actualPreamble.Length, "Encoding preamble mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.GetPreamble()): {1}", BitConverter.ToString(preamble), BitConverter.ToString(actualPreamble)); for (int i = 0; i < preamble.Length; i++) { Debug.Assert(preamble[i] == actualPreamble[i], "Encoding preamble mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.GetPreamble()): {1}", BitConverter.ToString(preamble), BitConverter.ToString(actualPreamble)); } } #endif public HttpContentHeaders Headers { get { if (_headers == null) { _headers = new HttpContentHeaders(this); } return _headers; } } private bool IsBuffered { get { return _bufferedContent != null; } } internal void SetBuffer(byte[] buffer, int offset, int count) { _bufferedContent = new MemoryStream(buffer, offset, count, writable: false, publiclyVisible: true); } internal bool TryGetBuffer(out ArraySegment<byte> buffer) { #if NET46 buffer = default(ArraySegment<byte>); #endif return _bufferedContent != null && _bufferedContent.TryGetBuffer(out buffer); } protected HttpContent() { // Log to get an ID for the current content. This ID is used when the content gets associated to a message. if (NetEventSource.IsEnabled) NetEventSource.Enter(this); // We start with the assumption that we can calculate the content length. _canCalculateLength = true; if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } public Task<string> ReadAsStringAsync() { CheckDisposed(); return WaitAndReturnAsync(LoadIntoBufferAsync(), this, s => s.ReadBufferedContentAsString()); } private string ReadBufferedContentAsString() { Debug.Assert(IsBuffered); if (_bufferedContent.Length == 0) { return string.Empty; } ArraySegment<byte> buffer; if (!TryGetBuffer(out buffer)) { buffer = new ArraySegment<byte>(_bufferedContent.ToArray()); } return ReadBufferAsString(buffer, Headers); } internal static string ReadBufferAsString(ArraySegment<byte> buffer, HttpContentHeaders headers) { // We don't validate the Content-Encoding header: If the content was encoded, it's the caller's // responsibility to make sure to only call ReadAsString() on already decoded content. E.g. if the // Content-Encoding is 'gzip' the user should set HttpClientHandler.AutomaticDecompression to get a // decoded response stream. Encoding encoding = null; int bomLength = -1; // If we do have encoding information in the 'Content-Type' header, use that information to convert // the content to a string. if ((headers.ContentType != null) && (headers.ContentType.CharSet != null)) { try { encoding = Encoding.GetEncoding(headers.ContentType.CharSet); // Byte-order-mark (BOM) characters may be present even if a charset was specified. bomLength = GetPreambleLength(buffer, encoding); } catch (ArgumentException e) { throw new InvalidOperationException(SR.net_http_content_invalid_charset, e); } } // If no content encoding is listed in the ContentType HTTP header, or no Content-Type header present, // then check for a BOM in the data to figure out the encoding. if (encoding == null) { if (!TryDetectEncoding(buffer, out encoding, out bomLength)) { // Use the default encoding (UTF8) if we couldn't detect one. encoding = DefaultStringEncoding; // We already checked to see if the data had a UTF8 BOM in TryDetectEncoding // and DefaultStringEncoding is UTF8, so the bomLength is 0. bomLength = 0; } } // Drop the BOM when decoding the data. return encoding.GetString(buffer.Array, buffer.Offset + bomLength, buffer.Count - bomLength); } public Task<byte[]> ReadAsByteArrayAsync() { CheckDisposed(); return WaitAndReturnAsync(LoadIntoBufferAsync(), this, s => s.ReadBufferedContentAsByteArray()); } internal byte[] ReadBufferedContentAsByteArray() { // The returned array is exposed out of the library, so use ToArray rather // than TryGetBuffer in order to make a copy. return _bufferedContent.ToArray(); } public Task<Stream> ReadAsStreamAsync() { CheckDisposed(); ArraySegment<byte> buffer; if (_contentReadStream == null && TryGetBuffer(out buffer)) { _contentReadStream = Task.FromResult<Stream>(new MemoryStream(buffer.Array, buffer.Offset, buffer.Count, writable: false)); } if (_contentReadStream != null) { return _contentReadStream; } _contentReadStream = CreateContentReadStreamAsync(); return _contentReadStream; } protected abstract Task SerializeToStreamAsync(Stream stream, TransportContext context); public Task CopyToAsync(Stream stream, TransportContext context) { CheckDisposed(); if (stream == null) { throw new ArgumentNullException(nameof(stream)); } try { Task task = null; ArraySegment<byte> buffer; if (TryGetBuffer(out buffer)) { task = stream.WriteAsync(buffer.Array, buffer.Offset, buffer.Count); } else { task = SerializeToStreamAsync(stream, context); CheckTaskNotNull(task); } return CopyToAsyncCore(task); } catch (Exception e) when (StreamCopyExceptionNeedsWrapping(e)) { return Task.FromException(GetStreamCopyException(e)); } } private static async Task CopyToAsyncCore(Task copyTask) { try { await copyTask.ConfigureAwait(false); } catch (Exception e) when (StreamCopyExceptionNeedsWrapping(e)) { throw GetStreamCopyException(e); } } public Task CopyToAsync(Stream stream) { return CopyToAsync(stream, null); } #if NET46 // Workaround for HttpWebRequest synchronous resubmit. This code is required because the underlying // .NET Framework HttpWebRequest implementation cannot use CopyToAsync and only uses sync based CopyTo. internal void CopyTo(Stream stream) { CopyToAsync(stream).Wait(); } #endif public Task LoadIntoBufferAsync() { return LoadIntoBufferAsync(MaxBufferSize); } // No "CancellationToken" parameter needed since canceling the CTS will close the connection, resulting // in an exception being thrown while we're buffering. // If buffering is used without a connection, it is supposed to be fast, thus no cancellation required. public Task LoadIntoBufferAsync(long maxBufferSize) { CheckDisposed(); if (maxBufferSize > HttpContent.MaxBufferSize) { // This should only be hit when called directly; HttpClient/HttpClientHandler // will not exceed this limit. throw new ArgumentOutOfRangeException(nameof(maxBufferSize), maxBufferSize, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_limit, HttpContent.MaxBufferSize)); } if (IsBuffered) { // If we already buffered the content, just return a completed task. return Task.CompletedTask; } Exception error = null; MemoryStream tempBuffer = CreateMemoryStream(maxBufferSize, out error); if (tempBuffer == null) { // We don't throw in LoadIntoBufferAsync(): return a faulted task. return Task.FromException(error); } try { Task task = SerializeToStreamAsync(tempBuffer, null); CheckTaskNotNull(task); return LoadIntoBufferAsyncCore(task, tempBuffer); } catch (Exception e) when (StreamCopyExceptionNeedsWrapping(e)) { return Task.FromException(GetStreamCopyException(e)); } // other synchronous exceptions from SerializeToStreamAsync/CheckTaskNotNull will propagate } private async Task LoadIntoBufferAsyncCore(Task serializeToStreamTask, MemoryStream tempBuffer) { try { await serializeToStreamTask.ConfigureAwait(false); } catch (Exception e) { tempBuffer.Dispose(); // Cleanup partially filled stream. Exception we = GetStreamCopyException(e); if (we != e) throw we; throw; } try { tempBuffer.Seek(0, SeekOrigin.Begin); // Rewind after writing data. _bufferedContent = tempBuffer; } catch (Exception e) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, e); throw; } } protected virtual Task<Stream> CreateContentReadStreamAsync() { // By default just buffer the content to a memory stream. Derived classes can override this behavior // if there is a better way to retrieve the content as stream (e.g. byte array/string use a more efficient // way, like wrapping a read-only MemoryStream around the bytes/string) return WaitAndReturnAsync(LoadIntoBufferAsync(), this, s => (Stream)s._bufferedContent); } // Derived types return true if they're able to compute the length. It's OK if derived types return false to // indicate that they're not able to compute the length. The transport channel needs to decide what to do in // that case (send chunked, buffer first, etc.). protected internal abstract bool TryComputeLength(out long length); internal long? GetComputedOrBufferLength() { CheckDisposed(); if (IsBuffered) { return _bufferedContent.Length; } // If we already tried to calculate the length, but the derived class returned 'false', then don't try // again; just return null. if (_canCalculateLength) { long length = 0; if (TryComputeLength(out length)) { return length; } // Set flag to make sure next time we don't try to compute the length, since we know that we're unable // to do so. _canCalculateLength = false; } return null; } private MemoryStream CreateMemoryStream(long maxBufferSize, out Exception error) { Contract.Ensures((Contract.Result<MemoryStream>() != null) || (Contract.ValueAtReturn<Exception>(out error) != null)); error = null; // If we have a Content-Length allocate the right amount of buffer up-front. Also check whether the // content length exceeds the max. buffer size. long? contentLength = Headers.ContentLength; if (contentLength != null) { Debug.Assert(contentLength >= 0); if (contentLength > maxBufferSize) { error = new HttpRequestException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_exceeded, maxBufferSize)); return null; } // We can safely cast contentLength to (int) since we just checked that it is <= maxBufferSize. return new LimitMemoryStream((int)maxBufferSize, (int)contentLength); } // We couldn't determine the length of the buffer. Create a memory stream with an empty buffer. return new LimitMemoryStream((int)maxBufferSize, 0); } #region IDisposable Members protected virtual void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; if (_contentReadStream != null && _contentReadStream.Status == TaskStatus.RanToCompletion) { _contentReadStream.Result.Dispose(); _contentReadStream = null; } if (IsBuffered) { _bufferedContent.Dispose(); } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion #region Helpers private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(this.GetType().ToString()); } } private void CheckTaskNotNull(Task task) { if (task == null) { var e = new InvalidOperationException(SR.net_http_content_no_task_returned); if (NetEventSource.IsEnabled) NetEventSource.Error(this, e); throw e; } } private static bool StreamCopyExceptionNeedsWrapping(Exception e) => e is IOException || e is ObjectDisposedException; private static Exception GetStreamCopyException(Exception originalException) { // HttpContent derived types should throw HttpRequestExceptions if there is an error. However, since the stream // provided by CopyToAsync() can also throw, we wrap such exceptions in HttpRequestException. This way custom content // types don't have to worry about it. The goal is that users of HttpContent don't have to catch multiple // exceptions (depending on the underlying transport), but just HttpRequestExceptions // Custom stream should throw either IOException or HttpRequestException. // We don't want to wrap other exceptions thrown by Stream (e.g. InvalidOperationException), since we // don't want to hide such "usage error" exceptions in HttpRequestException. // ObjectDisposedException is also wrapped, since aborting HWR after a request is complete will result in // the response stream being closed. return StreamCopyExceptionNeedsWrapping(originalException) ? new HttpRequestException(SR.net_http_content_stream_copy_error, originalException) : originalException; } private static int GetPreambleLength(ArraySegment<byte> buffer, Encoding encoding) { byte[] data = buffer.Array; int offset = buffer.Offset; int dataLength = buffer.Count; Debug.Assert(data != null); Debug.Assert(encoding != null); switch (encoding.CodePage) { case UTF8CodePage: return (dataLength >= UTF8PreambleLength && data[offset + 0] == UTF8PreambleByte0 && data[offset + 1] == UTF8PreambleByte1 && data[offset + 2] == UTF8PreambleByte2) ? UTF8PreambleLength : 0; #if !uap // UTF32 not supported on Phone case UTF32CodePage: return (dataLength >= UTF32PreambleLength && data[offset + 0] == UTF32PreambleByte0 && data[offset + 1] == UTF32PreambleByte1 && data[offset + 2] == UTF32PreambleByte2 && data[offset + 3] == UTF32PreambleByte3) ? UTF32PreambleLength : 0; #endif case UnicodeCodePage: return (dataLength >= UnicodePreambleLength && data[offset + 0] == UnicodePreambleByte0 && data[offset + 1] == UnicodePreambleByte1) ? UnicodePreambleLength : 0; case BigEndianUnicodeCodePage: return (dataLength >= BigEndianUnicodePreambleLength && data[offset + 0] == BigEndianUnicodePreambleByte0 && data[offset + 1] == BigEndianUnicodePreambleByte1) ? BigEndianUnicodePreambleLength : 0; default: byte[] preamble = encoding.GetPreamble(); return BufferHasPrefix(buffer, preamble) ? preamble.Length : 0; } } private static bool TryDetectEncoding(ArraySegment<byte> buffer, out Encoding encoding, out int preambleLength) { byte[] data = buffer.Array; int offset = buffer.Offset; int dataLength = buffer.Count; Debug.Assert(data != null); if (dataLength >= 2) { int first2Bytes = data[offset + 0] << 8 | data[offset + 1]; switch (first2Bytes) { case UTF8PreambleFirst2Bytes: if (dataLength >= UTF8PreambleLength && data[offset + 2] == UTF8PreambleByte2) { encoding = Encoding.UTF8; preambleLength = UTF8PreambleLength; return true; } break; case UTF32OrUnicodePreambleFirst2Bytes: #if !uap // UTF32 not supported on Phone if (dataLength >= UTF32PreambleLength && data[offset + 2] == UTF32PreambleByte2 && data[offset + 3] == UTF32PreambleByte3) { encoding = Encoding.UTF32; preambleLength = UTF32PreambleLength; } else #endif { encoding = Encoding.Unicode; preambleLength = UnicodePreambleLength; } return true; case BigEndianUnicodePreambleFirst2Bytes: encoding = Encoding.BigEndianUnicode; preambleLength = BigEndianUnicodePreambleLength; return true; } } encoding = null; preambleLength = 0; return false; } private static bool BufferHasPrefix(ArraySegment<byte> buffer, byte[] prefix) { byte[] byteArray = buffer.Array; if (prefix == null || byteArray == null || prefix.Length > buffer.Count || prefix.Length == 0) return false; for (int i = 0, j = buffer.Offset; i < prefix.Length; i++, j++) { if (prefix[i] != byteArray[j]) return false; } return true; } #endregion Helpers private static async Task<TResult> WaitAndReturnAsync<TState, TResult>(Task waitTask, TState state, Func<TState, TResult> returnFunc) { await waitTask.ConfigureAwait(false); return returnFunc(state); } private static Exception CreateOverCapacityException(int maxBufferSize) { return new HttpRequestException(SR.Format(SR.net_http_content_buffersize_exceeded, maxBufferSize)); } internal sealed class LimitMemoryStream : MemoryStream { private readonly int _maxSize; public LimitMemoryStream(int maxSize, int capacity) : base(capacity) { Debug.Assert(capacity <= maxSize); _maxSize = maxSize; } public int MaxSize => _maxSize; public byte[] GetSizedBuffer() { ArraySegment<byte> buffer; return TryGetBuffer(out buffer) && buffer.Offset == 0 && buffer.Count == buffer.Array.Length ? buffer.Array : ToArray(); } public override void Write(byte[] buffer, int offset, int count) { CheckSize(count); base.Write(buffer, offset, count); } public override void WriteByte(byte value) { CheckSize(1); base.WriteByte(value); } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { CheckSize(count); return base.WriteAsync(buffer, offset, count, cancellationToken); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { CheckSize(count); return base.BeginWrite(buffer, offset, count, callback, state); } public override void EndWrite(IAsyncResult asyncResult) { base.EndWrite(asyncResult); } public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { ArraySegment<byte> buffer; if (TryGetBuffer(out buffer)) { StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); long pos = Position; long length = Length; Position = length; long bytesToWrite = length - pos; return destination.WriteAsync(buffer.Array, (int)(buffer.Offset + pos), (int)bytesToWrite, cancellationToken); } return base.CopyToAsync(destination, bufferSize, cancellationToken); } private void CheckSize(int countToAdd) { if (_maxSize - Length < countToAdd) { throw CreateOverCapacityException(_maxSize); } } } #if !NET46 internal sealed class LimitArrayPoolWriteStream : Stream { private const int MaxByteArrayLength = 0x7FFFFFC7; private const int InitialLength = 256; private readonly int _maxBufferSize; private byte[] _buffer; private int _length; public LimitArrayPoolWriteStream(int maxBufferSize) : this(maxBufferSize, InitialLength) { } public LimitArrayPoolWriteStream(int maxBufferSize, long capacity) { if (capacity < InitialLength) { capacity = InitialLength; } else if (capacity > maxBufferSize) { throw CreateOverCapacityException(maxBufferSize); } _maxBufferSize = maxBufferSize; _buffer = ArrayPool<byte>.Shared.Rent((int)capacity); } protected override void Dispose(bool disposing) { Debug.Assert(_buffer != null); ArrayPool<byte>.Shared.Return(_buffer); _buffer = null; base.Dispose(disposing); } public ArraySegment<byte> GetBuffer() => new ArraySegment<byte>(_buffer, 0, _length); public byte[] ToArray() { var arr = new byte[_length]; Buffer.BlockCopy(_buffer, 0, arr, 0, _length); return arr; } private void EnsureCapacity(int value) { if ((uint)value > (uint)_maxBufferSize) // value cast handles overflow to negative as well { throw CreateOverCapacityException(_maxBufferSize); } else if (value > _buffer.Length) { Grow(value); } } private void Grow(int value) { Debug.Assert(value > _buffer.Length); // Extract the current buffer to be replaced. byte[] currentBuffer = _buffer; _buffer = null; // Determine the capacity to request for the new buffer. It should be // at least twice as long as the current one, if not more if the requested // value is more than that. If the new value would put it longer than the max // allowed byte array, than shrink to that (and if the required length is actually // longer than that, we'll let the runtime throw). uint twiceLength = 2 * (uint)currentBuffer.Length; int newCapacity = twiceLength > MaxByteArrayLength ? (value > MaxByteArrayLength ? value : MaxByteArrayLength) : Math.Max(value, (int)twiceLength); // Get a new buffer, copy the current one to it, return the current one, and // set the new buffer as current. byte[] newBuffer = ArrayPool<byte>.Shared.Rent(newCapacity); Buffer.BlockCopy(currentBuffer, 0, newBuffer, 0, _length); ArrayPool<byte>.Shared.Return(currentBuffer); _buffer = newBuffer; } public override void Write(byte[] buffer, int offset, int count) { Debug.Assert(buffer != null); Debug.Assert(offset >= 0); Debug.Assert(count >= 0); EnsureCapacity(_length + count); Buffer.BlockCopy(buffer, offset, _buffer, _length, count); _length += count; } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { Write(buffer, offset, count); return Task.CompletedTask; } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) => TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState); public override void EndWrite(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); public override void WriteByte(byte value) { int newLength = _length + 1; EnsureCapacity(newLength); _buffer[_length] = value; _length = newLength; } public override void Flush() { } public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask; public override long Length => _length; public override bool CanWrite => true; public override bool CanRead => false; public override bool CanSeek => false; public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } } #endif } }
// // Adjustment.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 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 Xwt.Backends; namespace Xwt { [BackendType (typeof(IScrollAdjustmentBackend))] public class ScrollAdjustment: XwtComponent { double lowerValue; double upperValue; double stepIncrement; double pageIncrement; double pageSize; EventHandler valueChanged; class ScrollAdjustmentBackendHost: BackendHost<ScrollAdjustment,IScrollAdjustmentBackend>, IScrollAdjustmentEventSink { protected override IBackend OnCreateBackend () { // When creating a standalone ScrollAdjustment (not bound to any widget) we always use // a default platform-agnostic implementation return new DefaultScrollAdjustmentBackend (); } protected override void OnBackendCreated () { base.OnBackendCreated (); Backend.Initialize (this); } public void OnValueChanged () { Parent.OnValueChanged (EventArgs.Empty); } } protected override Xwt.Backends.BackendHost CreateBackendHost () { return new ScrollAdjustmentBackendHost (); } public ScrollAdjustment () { lowerValue = 0; upperValue = 100; pageSize = 10; stepIncrement = 1; pageIncrement = 10; UpdateRange (); } internal ScrollAdjustment (IScrollAdjustmentBackend backend) { BackendHost.SetCustomBackend (backend); backend.Initialize ((ScrollAdjustmentBackendHost)BackendHost); } IScrollAdjustmentBackend Backend { get { return (IScrollAdjustmentBackend) BackendHost.Backend; } } /// <summary> /// Updates the adjustment value to ensure that a range is in the current page /// </summary> /// <param name='lower'> /// The lower value /// </param> /// <param name='upper'> /// The upper value /// </param> /// <remarks> /// Updates the adjustment value to ensure that the range between lower and upper is in the current page /// (i.e. between Value and Value + PageSize). If the range is larger than the page size, then only the /// start of it will be in the current page. A "Changed" event will be raised if the value is changed. /// </remarks> public void ClampPage (double lower, double upper) { if (upper - lower >= PageSize || upper <= lower) { Value = lower; return; } if (lower >= Value && upper < Value + PageSize) return; if (lower < Value) Value = lower; else Value = upper - PageSize; } public double Value { get { return Backend.Value; } set { Backend.Value = value; } } /// <summary> /// Gets or sets the lowest value of the scroll range. /// </summary> /// <value> /// The lower value. /// </value> /// <remarks>It must be &lt;= UpperValue</remarks> public double LowerValue { get { return lowerValue; } set { lowerValue = value; UpdateRange (); } } /// <summary> /// Gets or sets the highest value of the scroll range /// </summary> /// <value> /// The upper value. /// </value> /// <remarks>It must be >= LowerValue</remarks> public double UpperValue { get { return upperValue; } set { upperValue = value; UpdateRange (); } } /// <summary> /// How much Value will be incremented when you click on the scrollbar to move /// to the next page (when the scrollbar supports it) /// </summary> /// <value> /// The page increment. /// </value> public double PageIncrement { get { return pageIncrement; } set { pageIncrement = value; UpdateRange (); } } /// <summary> /// How much the Value is incremented/decremented when you click on the down/up button in the scrollbar /// </summary> /// <value> /// The step increment. /// </value> public double StepIncrement { get { return stepIncrement; } set { stepIncrement = value; UpdateRange (); } } /// <summary> /// Size of the visible range /// </summary> /// <remarks> /// For example, if LowerValue=0, UpperValue=100, Value=25 and PageSize=50, the visible range will be 25 to 75 /// </remarks> public double PageSize { get { return pageSize; } set { pageSize = value; UpdateRange (); } } void UpdateRange () { var realUpper = Math.Max (lowerValue, upperValue); var realPageSize = Math.Min (pageSize, realUpper - lowerValue); var realValue = Math.Min (Value, realUpper - realPageSize); if (realValue < lowerValue) realValue = lowerValue; Backend.SetRange (lowerValue, realUpper, realPageSize, pageIncrement, stepIncrement, realValue); OnAdjustmentChanged (); } [MappedEvent(ScrollAdjustmentEvent.ValueChanged)] protected virtual void OnValueChanged (EventArgs e) { if (valueChanged != null) valueChanged (this, e); } public event EventHandler ValueChanged { add { BackendHost.OnBeforeEventAdd (ScrollAdjustmentEvent.ValueChanged, valueChanged); valueChanged += value; } remove { valueChanged -= value; BackendHost.OnAfterEventRemove (ScrollAdjustmentEvent.ValueChanged, valueChanged); } } /// <summary> /// </summary> /// <remarks> /// This method is called when one of the properties of the adjustment changes. /// It is not called if the Value changes. You can override OnValueChanged for /// this use case. /// </remarks> protected virtual void OnAdjustmentChanged () { } class DefaultScrollAdjustmentBackend: IScrollAdjustmentBackend { IScrollAdjustmentEventSink eventSink; double currentValue; public void Initialize (IScrollAdjustmentEventSink eventSink) { this.eventSink = eventSink; } public double Value { get { return currentValue; } set { currentValue = value; eventSink.OnValueChanged (); } } public void SetRange (double lowerValue, double upperValue, double pageSize, double pageIncrement, double stepIncrement, double value) { if (Value != value) Value = value; } public void InitializeBackend (object frontend, ApplicationContext context) { } public void EnableEvent (object eventId) { } public void DisableEvent (object eventId) { } } } }
// 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.Linq; using System.Text; using Gallio.Common.Reflection; using Gallio.Framework; using Gallio.Model; using Gallio.Tests; using MbUnit.Framework; namespace MbUnit.Tests.Integration { [RunSample(typeof(Fixture))] [RunSample(typeof(FixtureWithFailingConstructor))] [RunSample(typeof(FixtureWithFailingFixtureInitializer))] [RunSample(typeof(FixtureWithFailingTest))] [RunSample(typeof(FixtureWithFailingDispose))] public class ConstructorFixtureInitializerAndDisposeTest : BaseTestWithSampleRunner { [Test] public void WhenNoFailure_FixturePasses() { var fixtureRun = Runner.GetPrimaryTestStepRun(CodeReference.CreateFromType(typeof(Fixture))); Assert.Multiple(() => { Assert.AreEqual(TestOutcome.Passed, fixtureRun.Result.Outcome); Assert.IsFalse(fixtureRun.Step.IsTestCase); AssertLogContains(fixtureRun, "[Constructor] Outcome: passed\n[FixtureInitializer] Outcome: passed\n[Dispose] Outcome: passed"); }); } [Test] public void WhenNoFailure_TestPasses() { var fixtureRun = Runner.GetPrimaryTestStepRun(CodeReference.CreateFromType(typeof(Fixture))); var testRun = fixtureRun.Children[0]; Assert.Multiple(() => { Assert.AreEqual(TestOutcome.Passed, testRun.Result.Outcome); Assert.IsTrue(testRun.Step.IsTestCase); AssertLogContains(testRun, "[Test] Outcome: passed"); }); } [Test] public void WhenConstructorFails_FixtureFailsAndBecomesATestCase() { var fixtureRun = Runner.GetPrimaryTestStepRun(CodeReference.CreateFromType(typeof(FixtureWithFailingConstructor))); Assert.Multiple(() => { Assert.AreEqual(TestOutcome.Failed, fixtureRun.Result.Outcome); Assert.IsTrue(fixtureRun.Step.IsTestCase); AssertLogContains(fixtureRun, "[Constructor] Outcome: passed"); }); } [Test] public void WhenConstructorFails_TestDoesNotRun() { var fixtureRun = Runner.GetPrimaryTestStepRun(CodeReference.CreateFromType(typeof(FixtureWithFailingConstructor))); Assert.Count(0, fixtureRun.Children); } [Test] public void WhenFixtureInitializerFails_FixtureFailsAndBecomesATestCase() { var fixtureRun = Runner.GetPrimaryTestStepRun(CodeReference.CreateFromType(typeof(FixtureWithFailingFixtureInitializer))); Assert.Multiple(() => { Assert.AreEqual(TestOutcome.Failed, fixtureRun.Result.Outcome); Assert.IsTrue(fixtureRun.Step.IsTestCase); AssertLogContains(fixtureRun, "[Constructor] Outcome: passed\n[FixtureInitializer] Outcome: passed\n[Dispose] Outcome: failed"); }); } [Test] public void WhenFixtureInitializerFails_TestDoesNotRun() { var fixtureRun = Runner.GetPrimaryTestStepRun(CodeReference.CreateFromType(typeof(FixtureWithFailingFixtureInitializer))); Assert.Count(0, fixtureRun.Children); } [Test] public void WhenTestFails_FixtureFails() { var fixtureRun = Runner.GetPrimaryTestStepRun(CodeReference.CreateFromType(typeof(FixtureWithFailingTest))); Assert.Multiple(() => { Assert.AreEqual(TestOutcome.Failed, fixtureRun.Result.Outcome); Assert.IsFalse(fixtureRun.Step.IsTestCase); AssertLogContains(fixtureRun, "[Constructor] Outcome: passed\n[FixtureInitializer] Outcome: passed\n[Dispose] Outcome: failed"); }); } [Test] public void WhenTestFails_TestFails() { var fixtureRun = Runner.GetPrimaryTestStepRun(CodeReference.CreateFromType(typeof(FixtureWithFailingTest))); var testRun = fixtureRun.Children[0]; Assert.Multiple(() => { Assert.IsNotNull(testRun); Assert.AreEqual(TestOutcome.Failed, testRun.Result.Outcome); Assert.IsTrue(testRun.Step.IsTestCase); AssertLogContains(testRun, "[Test] Outcome: passed"); }); } [Test] public void WhenDisposeFails_FixtureFails() { var fixtureRun = Runner.GetPrimaryTestStepRun(CodeReference.CreateFromType(typeof(FixtureWithFailingDispose))); Assert.Multiple(() => { Assert.AreEqual(TestOutcome.Failed, fixtureRun.Result.Outcome); Assert.IsFalse(fixtureRun.Step.IsTestCase); AssertLogContains(fixtureRun, "[Constructor] Outcome: passed\n[FixtureInitializer] Outcome: passed\n[Dispose] Outcome: passed"); }); } [Test] public void WhenDisposeFails_TestStillPassesBecauseDisposeHappensLater() { var fixtureRun = Runner.GetPrimaryTestStepRun(CodeReference.CreateFromType(typeof(FixtureWithFailingDispose))); var testRun = fixtureRun.Children[0]; Assert.Multiple(() => { Assert.AreEqual(TestOutcome.Passed, testRun.Result.Outcome); Assert.IsTrue(testRun.Step.IsTestCase); AssertLogContains(testRun, "[Test] Outcome: passed"); }); } [Explicit("Sample")] public class Fixture : IDisposable { public Fixture() { TestLog.WriteLine("[Constructor] Outcome: {0}", TestContext.CurrentContext.Outcome); } [FixtureInitializer] public virtual void FixtureInitializer() { TestLog.WriteLine("[FixtureInitializer] Outcome: {0}", TestContext.CurrentContext.Outcome); } [Test] public virtual void Test() { TestLog.WriteLine("[Test] Outcome: {0}", TestContext.CurrentContext.Outcome); } public virtual void Dispose() { TestLog.WriteLine("[Dispose] Outcome: {0}", TestContext.CurrentContext.Outcome); } } [Explicit("Sample")] public class FixtureWithFailingConstructor : Fixture { public FixtureWithFailingConstructor() { Assert.Fail("Boom"); } } [Explicit("Sample")] public class FixtureWithFailingFixtureInitializer : Fixture { public override void FixtureInitializer() { base.FixtureInitializer(); Assert.Fail("Boom"); } } [Explicit("Sample")] public class FixtureWithFailingTest : Fixture { public override void Test() { base.Test(); Assert.Fail("Boom"); } } [Explicit("Sample")] public class FixtureWithFailingDispose : Fixture { public override void Dispose() { base.Dispose(); Assert.Fail("Boom"); } } } }
namespace YAMP { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; /// <summary> /// Provides internal access to the elements and handles the element registration and variable assignment. /// </summary> sealed class Elements : IElementMapping { #region Fields readonly IDictionary<String, Operator> _binaryOperators; readonly IDictionary<String, Operator> _unaryOperators; readonly List<Expression> _expressions; readonly IDictionary<String, Keyword> _keywords; readonly IDictionary<Guid, Plugin> _plugins; #endregion #region ctor public Elements(ParseContext context) { _binaryOperators = new Dictionary<String, Operator>(); _unaryOperators = new Dictionary<String, Operator>(); _expressions = new List<Expression>(); _keywords = new Dictionary<String, Keyword>(); _plugins = new Dictionary<Guid, Plugin>(); } #endregion #region Properties /// <summary> /// Gets the function loader, if any. /// </summary> public IEnumerable<IFunctionLoader> Loaders { get { return _plugins.SelectMany(m => m.Value.Loaders); } } /// <summary> /// Gets the list of possible keywords. /// </summary> public String[] Keywords { get { return _keywords.Keys.ToArray(); } } #endregion #region Register elements /// <summary> /// Registers the IFunction, IConstant and IRegisterToken token classes at the specified context. /// </summary> /// <param name="context"> /// The context where the IFunction and IConstant instances will be placed. /// </param> /// <param name="assembly"> /// The assembly to load. /// </param> /// <returns>The ID for the assembly.</returns> public Guid RegisterAssembly(ParseContext context, Assembly assembly) { var plugin = new Plugin(context, assembly); plugin.Install(); _plugins.Add(plugin.Id, plugin); return plugin.Id; } /// <summary> /// Removes a previously added assembly. /// </summary> /// <param name="pluginId">The id of the plugin to remove.</param> public void RemoveAssembly(Guid pluginId) { if (_plugins.ContainsKey(pluginId)) { var plugin = _plugins[pluginId]; plugin.Uninstall(); _plugins.Remove(pluginId); } } #endregion #region Add elements /// <summary> /// Adds an operator to the dictionary. /// </summary> /// <param name="pattern">The operator pattern, i.e. += for add and assign.</param> /// <param name="op">The instance of the operator.</param> public void AddOperator(String pattern, Operator op) { if (!op.IsRightToLeft && op.Expressions == 1) { _unaryOperators.Add(pattern, op); } else { _binaryOperators.Add(pattern, op); } } /// <summary> /// Adds an expression to the list of expressions. /// </summary> /// <param name="exp">The instance of the expression.</param> public void AddExpression(Expression exp) { _expressions.Add(exp); } /// <summary> /// Adds a keyword to the dictionary. /// </summary> /// <param name="pattern">The exact keyword pattern, i.e. for for the for-loop.</param> /// <param name="keyword">The instance of the keyword.</param> public void AddKeyword(String pattern, Keyword keyword) { _keywords.Add(pattern, keyword); } #endregion #region Find elements /// <summary> /// Searches for the given keyword in the list of available keywords. Creates a class if the keyword is found. /// </summary> /// <param name="keyword">The keyword to look for.</param> /// <param name="engine">The engine to use.</param> /// <returns>Keyword that matches the given keyword.</returns> public Expression FindKeywordExpression(String keyword, ParseEngine engine) { if (_keywords.ContainsKey(keyword)) { return _keywords[keyword].Scan(engine); } return null; } /// <summary> /// Finds the exact keyword by its type. /// </summary> /// <typeparam name="T">The type of the keyword.</typeparam> /// <returns>The keyword or null.</returns> public T FindKeywordExpression<T>() where T : Keyword { foreach (var keyword in _keywords.Values) { if (keyword is T) { return (T)keyword; } } return null; } /// <summary> /// Finds the closest matching expression. /// </summary> /// <param name="engine">The engine to parse the query.</param> /// <returns>Expression that matches the current characters.</returns> public Expression FindExpression(ParseEngine engine) { foreach (var origin in _expressions) { var exp = origin.Scan(engine); if (exp != null) { return exp; } } return null; } /// <summary> /// Finds the exact expression by its type. /// </summary> /// <typeparam name="T">The type of the expression.</typeparam> /// <returns>The expression or null.</returns> public T FindExpression<T>() where T : Expression { foreach (var exp in _expressions) { if (exp is T) { return (T)exp; } } return null; } /// <summary> /// Finds the closest matching operator (all except left unary). /// </summary> /// <param name="engine">The engine to parse the query.</param> /// <returns>Operator that matches the current characters.</returns> public Operator FindOperator(ParseEngine engine) { var maxop = FindArbitraryOperator(_binaryOperators.Keys, engine); if (maxop.Length == 0) { return null; } return _binaryOperators[maxop].Create(engine); } /// <summary> /// Finds the closest matching left unary operator. /// </summary> /// <param name="engine">The engine to parse the query.</param> /// <returns>Operator that matches the current characters.</returns> public Operator FindLeftUnaryOperator(ParseEngine engine) { var maxop = FindArbitraryOperator(_unaryOperators.Keys, engine); if (maxop.Length == 0) { return null; } return _unaryOperators[maxop].Create(engine); } String FindArbitraryOperator(IEnumerable<String> operators, ParseEngine engine) { var maxop = String.Empty; var notfound = true; var chars = engine.Characters; var ptr = engine.Pointer; var rest = chars.Length - ptr; foreach (var op in operators) { if (op.Length <= rest && op.Length > maxop.Length) { notfound = false; for (var i = 0; !notfound && i < op.Length; i++) { notfound = (chars[ptr + i] != op[i]); } if (!notfound) { maxop = op; } } } return maxop; } /// <summary> /// Finds the exact operator by its type. /// </summary> /// <typeparam name="T">The type of the operator.</typeparam> /// <returns>The operator or null.</returns> public T FindOperator<T>() where T : Operator { foreach (var op in _binaryOperators.Values) { if (op is T) { return (T)op; } } foreach (var op in _unaryOperators.Values) { if (op is T) { return (T)op; } } return null; } #endregion } }
using com.lover.astd.common.model; using System; namespace com.lover.astd.common.manager { public class WeaponHelper { private static int[] _redStandards = new int[] { 300, 200, 500, 300, 180, 500, 100 }; private static double[] _redFactors = new double[] { 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 6.0 }; private static double[] _purpleStandards = new double[] { 2040.0, 1360.0, 3400.0, 2040.0, 1224.0, 3400.0, 680.0 }; private static double[] _purpleInc_20 = new double[] { 102.0, 68.0, 170.0, 102.0, 61.2, 170.0, 34.0 }; private static double[] _purpleInc_30 = new double[] { 126.0, 84.0, 210.0, 126.0, 75.6, 210.0, 42.0 }; private static double[] _purpleInc_40plus = new double[] { 42.0, 28.0, 70.0, 42.0, 25.2, 70.0, 14.0 }; public static int getRedWeaponBaseAmount(Equipment equip) { if (equip.goodstype != GoodsType.Weapon) { return 0; } return WeaponHelper._redStandards[equip.Type - EquipmentType.Sword]; } public static int getRedWeaponMaxAmount(Equipment equip) { if (equip.goodstype != GoodsType.Weapon) { return 0; } return (int)((double)WeaponHelper._redStandards[equip.Type - EquipmentType.Sword] * WeaponHelper._redFactors[6]); } public static int getPurpleWeaponBaseAmount(int type, int star) { bool flag = type < 0 || type > 7 || star < 20; int result; if (flag) { result = 0; } else { double num = WeaponHelper._purpleStandards[type]; int num2 = (star > 30) ? 10 : (star - 20); int num3 = (star > 40) ? 10 : (star - 30); bool flag2 = num2 < 0; if (flag2) { num2 = 0; } bool flag3 = num3 < 0; if (flag3) { num3 = 0; } double num4 = num + WeaponHelper._purpleInc_20[type] * (double)num2 + WeaponHelper._purpleInc_30[type] * (double)num3; bool flag4 = star > 40; if (flag4) { int i = 40; int num5 = 1; while (i < star) { int num6 = star - i; int num7 = (num6 > 10) ? 10 : num6; bool flag5 = i < 60; if (flag5) { num4 += (WeaponHelper._purpleInc_30[type] + WeaponHelper._purpleInc_40plus[type] * (double)num5) * (double)num7; } else { num4 += (WeaponHelper._purpleInc_30[type] + WeaponHelper._purpleInc_40plus[type] * 3.0) * (double)num7; } i += 10; int num8 = num5; num5 = num8 + 1; } } result = (int)num4; } return result; } public static int calcRedWeaponStar(Equipment equip) { bool flag = equip.goodstype != GoodsType.Weapon; int result; if (flag) { result = 0; } else { int num = equip.Type - EquipmentType.Sword; int num2 = WeaponHelper._redStandards[num]; double num3 = WeaponHelper._redFactors[6]; int valueNow = equip.ValueNow; int num4 = 0; int num5; for (int i = 0; i < 7; i = num5 + 1) { bool flag2 = (int)((double)num2 * WeaponHelper._redFactors[i]) > valueNow; if (flag2) { num4 = i - 1; break; } num5 = i; } result = num4; } return result; } public static double getPurpleWeaponFullToughness(int star) { double[] array = new double[] { 37.6, 38.7, 39.8, 40.9, 42.0, 43.1, 44.25, 45.4, 46.55, 47.7, 48.85, 50.0, 51.2, 52.4, 53.6, 54.8, 56.1, 57.4, 58.7, 60.0, 61.3, 62.7, 64.1, 65.5, 66.9, 68.3, 69.9, 71.5, 73.1, 74.7, 76.3, 78.1, 79.9, 81.7, 83.5, 85.3, 87.4, 89.5, 91.6, 93.8, 95.9, 98.1, 100.3, 102.5, 104.7, 107.0, 109.3, 111.6, 113.9, 116.2, 118.5, 120.8, 123.1, 125.4, 127.7, 130.0, 132.3, 134.6, 136.9, 139.1, 141.4, 143.7, 146.0, 148.3, 150.7, 153.8, 156.9, 160.0, 163.1, 166.8, 170.5, 174.9, 179.3, 183.7, 188.1, 192.5 }; bool flag = star < 45; double num; if (flag) { num = array[0] - (double)(45 - star) * 0.6; } else { bool flag2 = star >= 45 && star <= 120; if (flag2) { num = array[star - 45]; } else { num = array[array.Length - 1] + (double)(star - 120) * 4.4; } } return num * 0.01; } public static void getWeaponInfo(Equipment equip, int star_expect, out int amount_expect, out double toughness, out double full_toughness, out int failcount, out int needcount) { toughness = 0.0; full_toughness = 0.0; failcount = 0; needcount = 0; amount_expect = 0; bool flag = equip.goodstype != GoodsType.Weapon; if (!flag) { int num = equip.Type - EquipmentType.Sword; bool flag2 = equip.Quality == EquipmentQuality.Red; if (flag2) { int num2 = WeaponHelper._redStandards[num]; double num3 = WeaponHelper._redFactors[6]; int valueNow = equip.ValueNow; int num4 = WeaponHelper.calcRedWeaponStar(equip); int num5 = (int)((double)num2 * WeaponHelper._redFactors[num4]); toughness = (double)(valueNow - num5) * 1.0 / (double)num5; amount_expect = (int)((double)num2 * WeaponHelper._redFactors[num4 + 1] * (1.0 + toughness)); failcount = (int)(toughness * 255.0 / 0.24); needcount = (int)Math.Pow(2.0, (double)(num4 + 3)) - 1 - failcount; } else { bool flag3 = equip.Quality == EquipmentQuality.Purple; if (flag3) { int valueNow2 = equip.ValueNow; int level = equip.Level; int purpleWeaponBaseAmount = WeaponHelper.getPurpleWeaponBaseAmount(num, level); toughness = (double)(valueNow2 - purpleWeaponBaseAmount) * 1.0 / (double)purpleWeaponBaseAmount; full_toughness = WeaponHelper.getPurpleWeaponFullToughness(level); int purpleWeaponBaseAmount2 = WeaponHelper.getPurpleWeaponBaseAmount(num, star_expect); amount_expect = (int)((double)purpleWeaponBaseAmount2 * (1.0 + toughness)); failcount = (int)(toughness * 100.0 / 0.02); } } } } } }
/* * Copyright 2012-2016 The Pkcs11Interop Project * * 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. */ /* * Written for the Pkcs11Interop project by: * Jaroslav IMRICH <jimrich@jimrich.sk> */ using System; using System.IO; using Net.Pkcs11Interop.Common; using Net.Pkcs11Interop.HighLevelAPI81; using Net.Pkcs11Interop.HighLevelAPI81.MechanismParams; using NUnit.Framework; namespace Net.Pkcs11Interop.Tests.HighLevelAPI81 { /// <summary> /// Encryption and decryption tests. /// </summary> [TestFixture()] public class _19_EncryptAndDecryptTest { /// <summary> /// Single-part encryption and decryption test. /// </summary> [Test()] public void _01_EncryptAndDecryptSinglePartTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking)) { // Find first slot with token present Slot slot = Helpers.GetUsableSlot(pkcs11); // Open RW session using (Session session = slot.OpenSession(false)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Generate symetric key ObjectHandle generatedKey = Helpers.GenerateKey(session); // Generate random initialization vector byte[] iv = session.GenerateRandom(8); // Specify encryption mechanism with initialization vector as parameter Mechanism mechanism = new Mechanism(CKM.CKM_DES3_CBC, iv); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Our new password"); // Encrypt data byte[] encryptedData = session.Encrypt(mechanism, generatedKey, sourceData); // Do something interesting with encrypted data // Decrypt data byte[] decryptedData = session.Decrypt(mechanism, generatedKey, encryptedData); // Do something interesting with decrypted data Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData)); session.DestroyObject(generatedKey); session.Logout(); } } } /// <summary> /// Multi-part encryption and decryption test. /// </summary> [Test()] public void _02_EncryptAndDecryptMultiPartTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking)) { // Find first slot with token present Slot slot = Helpers.GetUsableSlot(pkcs11); // Open RW session using (Session session = slot.OpenSession(false)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Generate symetric key ObjectHandle generatedKey = Helpers.GenerateKey(session); // Generate random initialization vector byte[] iv = session.GenerateRandom(8); // Specify encryption mechanism with initialization vector as parameter Mechanism mechanism = new Mechanism(CKM.CKM_DES3_CBC, iv); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Our new password"); byte[] encryptedData = null; byte[] decryptedData = null; // Multipart encryption can be used i.e. for encryption of streamed data using (MemoryStream inputStream = new MemoryStream(sourceData), outputStream = new MemoryStream()) { // Encrypt data // Note that in real world application we would rather use bigger read buffer i.e. 4096 session.Encrypt(mechanism, generatedKey, inputStream, outputStream, 8); // Read whole output stream to the byte array so we can compare results more easily encryptedData = outputStream.ToArray(); } // Do something interesting with encrypted data // Multipart decryption can be used i.e. for decryption of streamed data using (MemoryStream inputStream = new MemoryStream(encryptedData), outputStream = new MemoryStream()) { // Decrypt data // Note that in real world application we would rather use bigger read buffer i.e. 4096 session.Decrypt(mechanism, generatedKey, inputStream, outputStream, 8); // Read whole output stream to the byte array so we can compare results more easily decryptedData = outputStream.ToArray(); } // Do something interesting with decrypted data Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData)); session.DestroyObject(generatedKey); session.Logout(); } } } /// <summary> /// Single-part encryption and decryption test with CKM_RSA_PKCS_OAEP mechanism. /// </summary> [Test()] public void _03_EncryptAndDecryptSinglePartOaepTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking)) { // Find first slot with token present Slot slot = Helpers.GetUsableSlot(pkcs11); // Open RW session using (Session session = slot.OpenSession(false)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Generate key pair ObjectHandle publicKey = null; ObjectHandle privateKey = null; Helpers.GenerateKeyPair(session, out publicKey, out privateKey); // Specify mechanism parameters CkRsaPkcsOaepParams mechanismParams = new CkRsaPkcsOaepParams((ulong)CKM.CKM_SHA_1, (ulong)CKG.CKG_MGF1_SHA1, (ulong)CKZ.CKZ_DATA_SPECIFIED, null); // Specify encryption mechanism with parameters Mechanism mechanism = new Mechanism(CKM.CKM_RSA_PKCS_OAEP, mechanismParams); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world"); // Encrypt data byte[] encryptedData = session.Encrypt(mechanism, publicKey, sourceData); // Do something interesting with encrypted data // Decrypt data byte[] decryptedData = session.Decrypt(mechanism, privateKey, encryptedData); // Do something interesting with decrypted data Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData)); session.DestroyObject(privateKey); session.DestroyObject(publicKey); session.Logout(); } } } } }
// Author: abi // Project: DungeonQuest // Path: C:\code\Xna\DungeonQuest\Graphics // Creation date: 28.03.2007 01:01 // Last modified: 31.07.2007 04:40 #region Using directives using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.Text; using Texture = DungeonQuest.Graphics.Texture; using DungeonQuest.Game; #endregion namespace DungeonQuest.Graphics { /// <summary> /// Sprite helper class to manage and render sprites. /// </summary> internal class SpriteHelper { #region SpriteToRender helper class /// <summary> /// Sprite to render /// </summary> class SpriteToRender { #region Variables /// <summary> /// Texture /// </summary> public Texture texture; /// <summary> /// Rectangle /// </summary> public Rectangle rect; /// <summary> /// Source pixel rectangle /// </summary> public Rectangle pixelRect; /// <summary> /// Color /// </summary> public Color color = Color.White; /// <summary> /// Rotation /// </summary> public float rotation = 0; /// <summary> /// Rotation point for rotated sprites. /// </summary> public Vector2 rotationPoint = Vector2.Zero; /// <summary> /// Blend mode, defaults to SpriteBlendMode.AlphaBlend /// </summary> public SpriteBlendMode blendMode = SpriteBlendMode.AlphaBlend; #endregion #region Constructor /// <summary> /// Create sprite to render /// </summary> /// <param name="setTexture">Set texture</param> /// <param name="setRect">Set rectangle</param> /// <param name="setPixelRect">Set source rectangle</param> /// <param name="setColor">Set color</param> public SpriteToRender(Texture setTexture, Rectangle setRect, Rectangle setPixelRect, Color setColor) { texture = setTexture; rect = setRect; pixelRect = setPixelRect; color = setColor; } // SpriteToRender(setTexture, setRect, setSourceRect) /// <summary> /// Create sprite to render /// </summary> /// <param name="setTex">Set tex</param> /// <param name="setRect">Set rectangle</param> /// <param name="setPixelRect">Set pixel rectangle</param> /// <param name="setColor">Set color</param> /// <param name="alphaMode">Alpha mode</param> public SpriteToRender(Texture setTex, Rectangle setRect, Rectangle setPixelRect, Color setColor, SpriteBlendMode setBlendMode) { texture = setTex; rect = setRect; pixelRect = setPixelRect; color = setColor; blendMode = setBlendMode; } // SpriteToRender(setTex, setRect, setPixelRect) /// <summary> /// Create sprite to render /// </summary> /// <param name="setTex">Set tex</param> /// <param name="setRect">Set rectangle</param> /// <param name="setPixelRect">Set pixel rectangle</param> /// <param name="setRotation">Set rotation</param> /// <param name="setRotationPoint">Set rotation point</param> public SpriteToRender(Texture setTex, Rectangle setRect, Rectangle setPixelRect, float setRotation, Vector2 setRotationPoint) { texture = setTex; rect = setRect; pixelRect = setPixelRect; rotation = setRotation; rotationPoint = setRotationPoint; } // SpriteToRender(setTex, setRect, setPixelRect) /// <summary> /// Create sprite to render /// </summary> /// <param name="setTex">Set tex</param> /// <param name="setRect">Set rectangle</param> /// <param name="setPixelRect">Set pixel rectangle</param> /// <param name="setRotation">Set rotation</param> /// <param name="setRotationPoint">Set rotation point</param> public SpriteToRender(Texture setTex, Rectangle setRect, Rectangle setPixelRect, float setRotation, Vector2 setRotationPoint, Color setCol) { texture = setTex; rect = setRect; pixelRect = setPixelRect; rotation = setRotation; rotationPoint = setRotationPoint; color = setCol; } // SpriteToRender(setTex, setRect, setPixelRect) #endregion #region Render /// <summary> /// Render /// </summary> /// <param name="uiSprites">User interface sprites</param> public void Render(SpriteBatch uiSprites) { // Don't render if texture is null (else XNA throws an exception!) if (texture == null || texture.XnaTexture == null || color.A == 0) return; if (rotation == 0) uiSprites.Draw(texture.XnaTexture, rect, pixelRect, color); else uiSprites.Draw(texture.XnaTexture, rect, pixelRect, color, rotation, //new Vector2(rect.X + rect.Width / 2, rect.Y + rect.Height / 2), rotationPoint, SpriteEffects.None, 0); } // Render(uiSprites) #endregion } // class SpriteToRender #endregion #region Variables /// <summary> /// Keep a list of all sprites we have to render this frame. /// </summary> static List<SpriteToRender> sprites = new List<SpriteToRender>(); /// <summary> /// Sprite batch for rendering /// </summary> static SpriteBatch spriteBatch = null; #endregion #region Private constructor /// <summary> /// Create sprite helper, private. Instantiation is not allowed. /// </summary> private SpriteHelper() { } // SpriteHelper() #endregion #region Add sprite to render /// <summary> /// Add sprite to render /// </summary> /// <param name="texture">Texture</param> /// <param name="rect">Rectangle</param> /// <param name="gfxRect">Gfx rectangle</param> /// <param name="color">Color</param> public static void AddSpriteToRender( Texture texture, Rectangle rect, Rectangle gfxRect, Color color) { sprites.Add(new SpriteToRender(texture, rect, gfxRect, color)); } // AddSpriteToRender(texture, rect, gfxRect) /// <summary> /// Add sprite to render /// </summary> /// <param name="texture">Texture</param> /// <param name="rect">Rectangle</param> /// <param name="gfxRect">Gfx rectangle</param> public static void AddSpriteToRender( Texture texture, Rectangle rect, Rectangle gfxRect) { sprites.Add(new SpriteToRender(texture, rect, gfxRect, Color.White)); } // AddSpriteToRender(texture, rect, gfxRect) /// <summary> /// Add sprite to render /// </summary> /// <param name="texture">Texture</param> /// <param name="rect">Rectangle</param> /// <param name="gfxRect">Gfx rectangle</param> public static void AddSpriteToRender( Texture texture, Rectangle rect, Rectangle gfxRect, Color color, SpriteBlendMode blendMode) { sprites.Add( new SpriteToRender(texture, rect, gfxRect, color, blendMode)); } // AddSpriteToRender(texture, rect, gfxRect) /// <summary> /// Add sprite to render /// </summary> /// <param name="texture">Texture</param> /// <param name="rect">Rectangle</param> public static void AddSpriteToRender( Texture texture, Rectangle rect, Color color) { AddSpriteToRender(texture, rect, texture.GfxRectangle, color); } // AddSpriteToRender(texture, rect, color) /// <summary> /// Add sprite to render /// </summary> /// <param name="texture">Texture</param> /// <param name="rect">Rectangle</param> public static void AddSpriteToRender( Texture texture, Rectangle rect) { AddSpriteToRender(texture, rect, texture.GfxRectangle, Color.White); } // AddSpriteToRender(texture, rect) /// <summary> /// Add sprite to render /// </summary> /// <param name="texture">Texture</param> /// <param name="x">X</param> /// <param name="y">Y</param> public static void AddSpriteToRender( Texture texture, int x, int y, Color color) { AddSpriteToRender(texture, new Rectangle(x, y, texture.GfxRectangle.Width, texture.GfxRectangle.Height), color); } // AddSpriteToRender(texture, x, y) /// <summary> /// Add sprite to render /// </summary> /// <param name="texture">Texture</param> public static void AddSpriteToRender( Texture texture, int x, int y) { AddSpriteToRender(texture, new Rectangle(x, y, texture.GfxRectangle.Width, texture.GfxRectangle.Height)); } // AddSpriteToRender(texture, x, y) /// <summary> /// Add sprite to render /// </summary> /// <param name="texture">Texture</param> public static void AddSpriteToRender( Texture texture) { AddSpriteToRender(texture, new Rectangle(0, 0, 1024, 768)); } // AddSpriteToRender(texture) /// <summary> /// Add sprite to render /// </summary> /// <param name="tex">Tex</param> /// <param name="rect">Rectangle</param> /// <param name="pixelRect">Pixel rectangle</param> /// <param name="rotation">Rotation</param> public static void AddSpriteToRender(Texture tex, Rectangle rect, Rectangle pixelRect, float rotation, Vector2 rotationPoint) { sprites.Add(new SpriteToRender( tex, rect, pixelRect, rotation, rotationPoint)); } // AddSpriteToRender(tex, rect, pixelRect) /// <summary> /// Add sprite to render /// </summary> /// <param name="tex">Tex</param> /// <param name="rect">Rectangle</param> /// <param name="pixelRect">Pixel rectangle</param> /// <param name="rotation">Rotation</param> public static void AddSpriteToRender(Texture tex, Rectangle rect, Rectangle pixelRect, float rotation, Vector2 rotationPoint, Color col) { sprites.Add(new SpriteToRender( tex, rect, pixelRect, rotation, rotationPoint, col)); } // AddSpriteToRender(tex, rect, pixelRect) /// <summary> /// Add sprite to render centered /// </summary> /// <param name="texture">Texture</param> /// <param name="x">X</param> /// <param name="y">Y</param> /// <param name="scale">Scale</param> public static void AddSpriteToRenderCentered( Texture texture, float x, float y, float scale) { AddSpriteToRender(texture, new Rectangle( (int)(x * 1024 - scale * texture.GfxRectangle.Width/2), (int)(y * 768 - scale * texture.GfxRectangle.Height/2), (int)(scale * texture.GfxRectangle.Width), (int)(scale * texture.GfxRectangle.Height))); } // AddSpriteToRenderCentered(texture, x, y) /// <summary> /// Add sprite to render centered /// </summary> /// <param name="texture">Texture</param> /// <param name="pos">Position</param> public static void AddSpriteToRenderCentered( Texture texture, float x, float y) { AddSpriteToRenderCentered(texture, x, y, 1); } // AddSpriteToRenderCentered(texture, x, y) /// <summary> /// Add sprite to render centered /// </summary> /// <param name="texture">Texture</param> /// <param name="pos">Position</param> public static void AddSpriteToRenderCentered( Texture texture, Vector2 pos) { AddSpriteToRenderCentered(texture, pos.X, pos.Y); } // AddSpriteToRenderCentered(texture, pos) #endregion #region DrawAllSprites /// <summary> /// Draw all sprites collected this frame. /// </summary> public static void DrawAllSprites() { // No need to render if we got no sprites this frame if (sprites.Count == 0) return; // Disable depth buffer for UI and sprite rendering. BaseGame.Device.RenderState.DepthBufferEnable = false; // Create sprite batch if we have not done it yet. // Use device from texture to create the sprite batch. if (spriteBatch == null) spriteBatch = new SpriteBatch(BaseGame.Device); // Render all textures on our ui sprite batch if (sprites.Count > 0) { // We can improve a little performance by rendering // the additive stuff at first end! bool startedAdditiveSpriteMode = false; for (int spriteNum = 0; spriteNum < sprites.Count; spriteNum++) { SpriteToRender sprite = sprites[spriteNum]; if (sprite.blendMode == SpriteBlendMode.Additive) { if (startedAdditiveSpriteMode == false) { startedAdditiveSpriteMode = true; spriteBatch.Begin( SpriteBlendMode.Additive, SpriteSortMode.BackToFront, SaveStateMode.None); } // if (startedAdditiveSpriteMode) sprite.Render(spriteBatch); } // if (sprite.blendMode) } // for (spriteNum) if (startedAdditiveSpriteMode) spriteBatch.End(); // Handle all remembered sprites for (int spriteNum = 0; spriteNum < sprites.Count; spriteNum++) { SpriteToRender sprite = sprites[spriteNum]; if (sprite.blendMode != SpriteBlendMode.Additive) { spriteBatch.Begin( sprite.blendMode, SpriteSortMode.BackToFront, SaveStateMode.None); sprite.Render(spriteBatch); // Dunno why, but for some reason we have start a new sprite // for each texture change we have. Else stuff is not rendered // in the correct order on top of each other. spriteBatch.End(); } // if (sprite.blendMode) } // for (spriteNum) // Kill list of remembered sprites sprites.Clear(); } // if (sprites.Count) } // DrawAllSprites(width, height) #endregion #region DrawSprites /// <summary> /// Draw sprites /// </summary> /// <param name="width">Width</param> /// <param name="height">Height</param> public static void DrawSpritesOld(int width, int height) { // No need to render if we got no sprites this frame if (sprites.Count == 0) return; // Create sprite batch if we have not done it yet. // Use device from texture to create the sprite batch. if (spriteBatch == null) spriteBatch = new SpriteBatch(BaseGame.Device); // Render all textures on our ui sprite batch if (sprites.Count > 0) { // We can improve a little performance by rendering // the additive stuff at first end! bool startedAdditiveSpriteMode = false; for (int spriteNum = 0; spriteNum < sprites.Count; spriteNum++) { SpriteToRender sprite = sprites[spriteNum]; if (sprite.blendMode == SpriteBlendMode.Additive) { if (startedAdditiveSpriteMode == false) { startedAdditiveSpriteMode = true; spriteBatch.Begin( SpriteBlendMode.Additive, SpriteSortMode.BackToFront, SaveStateMode.SaveState); } // if (startedAdditiveSpriteMode) sprite.Render(spriteBatch); } // if (sprite.blendMode) } // for (spriteNum) if (startedAdditiveSpriteMode) spriteBatch.End(); // Handle all remembered sprites for (int spriteNum = 0; spriteNum < sprites.Count; spriteNum++) { SpriteToRender sprite = sprites[spriteNum]; if (sprite.blendMode != SpriteBlendMode.Additive) { spriteBatch.Begin( //SpriteBlendMode.Additive,//.AlphaBlend, sprite.blendMode, SpriteSortMode.BackToFront, SaveStateMode.SaveState); sprite.Render(spriteBatch); // Dunno why, but for some reason we have start a new sprite // for each texture change we have. Else stuff is not rendered // in the correct order on top of each other. spriteBatch.End(); } // if (sprite.blendMode) } // for (spriteNum) // Kill list of remembered sprites sprites.Clear(); } // if (sprites.Count) } // DrawSprites(width, height) /// <summary> /// Draw sprites to the current screen resolution. /// </summary> public static void DrawSprites() { DrawSpritesOld(BaseGame.Width, BaseGame.Height); } // DrawSprites() #endregion } // class SpriteHelper } // namespace DungeonQuest.Graphics
#region File Description //----------------------------------------------------------------------------- // SmokePlumeParticleSystem.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 ParticlesSettings; #endregion namespace Particles2DPipelineSample { public class ParticleSystem : DrawableGameComponent { // these two values control the order that particle systems are drawn in. // typically, particles that use additive blending should be drawn on top of // particles that use regular alpha blending. ParticleSystems should therefore // set their DrawOrder to the appropriate value in InitializeConstants, though // it is possible to use other values for more advanced effects. public const int AlphaBlendDrawOrder = 100; public const int AdditiveDrawOrder = 200; private SpriteBatch spriteBatch; // the texture this particle system will use. private Texture2D texture; // the origin when we're drawing textures. this will be the middle of the // texture. private Vector2 origin; // the array of particles used by this system. these are reused, so that calling // AddParticles will only cause allocations if we're trying to create more particles // than we have available private List<Particle> particles; // the queue of free particles keeps track of particles that are not curently // being used by an effect. when a new effect is requested, particles are taken // from this queue. when particles are finished they are put onto this queue. private Queue<Particle> freeParticles; // The settings used for this particle system private ParticleSystemSettings settings; // The asset name used to load our settings from a file. private string settingsAssetName; // the BlendState used when rendering the particles. private BlendState blendState; /// <summary> /// returns the number of particles that are available for a new effect. /// </summary> public int FreeParticleCount { get { return freeParticles.Count; } } /// <summary> /// Constructs a new ParticleSystem. /// </summary> /// <param name="game">The host for this particle system.</param> /// <param name="settingsAssetName">The name of the settings file to load /// used when creating and updating particles in the system.</param> public ParticleSystem(Game game, string settingsAssetName) : this(game, settingsAssetName, 10) { } /// <summary> /// Constructs a new ParticleSystem. /// </summary> /// <param name="game">The host for this particle system.</param> /// <param name="settingsAssetName">The name of the settings file to load /// used when creating and updating particles in the system.</param> /// <param name="initialParticleCount">The initial number of particles this /// system expects to use. The system will grow as needed, however setting /// this value to be as close as possible will reduce allocations.</param> public ParticleSystem(Game game, string settingsAssetName, int initialParticleCount) : base(game) { this.settingsAssetName = settingsAssetName; // we create the particle list and queue with our initial count and create that // many particles. If we picked a reasonable value, our system will not allocate // any more objects after this point, however the AddParticles method will allocate // more particles as needed. particles = new List<Particle>(initialParticleCount); freeParticles = new Queue<Particle>(initialParticleCount); for (int i = 0; i < initialParticleCount; i++) { particles.Add(new Particle()); freeParticles.Enqueue(particles[i]); } } /// <summary> /// Override the base class LoadContent to load the texture. once it's /// loaded, calculate the origin. /// </summary> protected override void LoadContent() { // Load our settings settings = Game.Content.Load<ParticleSystemSettings>(settingsAssetName); // load the texture.... texture = Game.Content.Load<Texture2D>(settings.TextureFilename); // ... and calculate the center. this'll be used in the draw call, we // always want to rotate and scale around this point. origin.X = texture.Width / 2; origin.Y = texture.Height / 2; // create the SpriteBatch that will draw the particles spriteBatch = new SpriteBatch(GraphicsDevice); // create the blend state using the values from our settings blendState = new BlendState { AlphaSourceBlend = settings.SourceBlend, ColorSourceBlend = settings.SourceBlend, AlphaDestinationBlend = settings.DestinationBlend, ColorDestinationBlend = settings.DestinationBlend }; base.LoadContent(); } /// <summary> /// PickRandomDirection is used by AddParticle to decide which direction /// particles will move. /// </summary> private Vector2 PickRandomDirection() { float angle = ParticleHelpers.RandomBetween(settings.MinDirectionAngle, settings.MaxDirectionAngle); // our settings angles are in degrees, so we must convert to radians angle = MathHelper.ToRadians(angle); return new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle)); } /// <summary> /// AddParticles's job is to add an effect somewhere on the screen. If there /// aren't enough particles in the freeParticles queue, it will use as many as /// it can. This means that if there not enough particles available, calling /// AddParticles will have no effect. /// </summary> /// <param name="where">Where the particle effect should be created</param> /// <param name="velocity">A base velocity for all particles. This is weighted /// by the EmitterVelocitySensitivity specified in the settings for the /// particle system.</param> public void AddParticles(Vector2 where, Vector2 velocity) { // the number of particles we want for this effect is a random number // somewhere between the two constants specified by the settings. int numParticles = ParticleHelpers.Random.Next(settings.MinNumParticles, settings.MaxNumParticles); // create that many particles, if you can. for (int i = 0; i < numParticles; i++) { // if we're out of free particles, we allocate another ten particles // which should keep us going. if (freeParticles.Count == 0) { for (int j = 0; j < 10; j++) { Particle newParticle = new Particle(); particles.Add(newParticle); freeParticles.Enqueue(newParticle); } } // grab a particle from the freeParticles queue, and Initialize it. Particle p = freeParticles.Dequeue(); InitializeParticle(p, where, velocity); } } /// <summary> /// InitializeParticle randomizes some properties for a particle, then /// calls initialize on it. It can be overriden by subclasses if they /// want to modify the way particles are created. For example, /// SmokePlumeParticleSystem overrides this function make all particles /// accelerate to the right, simulating wind. /// </summary> /// <param name="p">the particle to initialize</param> /// <param name="where">the position on the screen that the particle should be /// </param> /// <param name="velocity">The base velocity that the particle should have</param> private void InitializeParticle(Particle p, Vector2 where, Vector2 velocity) { // Adjust the input velocity based on how much // this particle system wants to be affected by it. velocity *= settings.EmitterVelocitySensitivity; // Adjust the velocity based on our random values Vector2 direction = PickRandomDirection(); float speed = ParticleHelpers.RandomBetween(settings.MinInitialSpeed, settings.MaxInitialSpeed); velocity += direction * speed; // pick some random values for our particle float lifetime = ParticleHelpers.RandomBetween(settings.MinLifetime, settings.MaxLifetime); float scale = ParticleHelpers.RandomBetween(settings.MinSize, settings.MaxSize); float rotationSpeed = ParticleHelpers.RandomBetween(settings.MinRotationSpeed, settings.MaxRotationSpeed); // our settings angles are in degrees, so we must convert to radians rotationSpeed = MathHelper.ToRadians(rotationSpeed); // figure out our acceleration base on our AccelerationMode Vector2 acceleration = Vector2.Zero; switch (settings.AccelerationMode) { case AccelerationMode.Scalar: // randomly pick our acceleration using our direction and // the MinAcceleration/MaxAcceleration values float accelerationScale = ParticleHelpers.RandomBetween( settings.MinAccelerationScale, settings.MaxAccelerationScale); acceleration = direction * accelerationScale; break; case AccelerationMode.EndVelocity: // Compute our acceleration based on our ending velocity from the settings. // We'll use the equation vt = v0 + (a0 * t). (If you're not familar with // this, it's one of the basic kinematics equations for constant // acceleration, and basically says: // velocity at time t = initial velocity + acceleration * t) // We're solving for a0 by substituting t for our lifetime, v0 for our // velocity, and vt as velocity * settings.EndVelocity. acceleration = (velocity * (settings.EndVelocity - 1)) / lifetime; break; case AccelerationMode.Vector: acceleration = new Vector2( ParticleHelpers.RandomBetween(settings.MinAccelerationVector.X, settings.MaxAccelerationVector.X), ParticleHelpers.RandomBetween(settings.MinAccelerationVector.Y, settings.MaxAccelerationVector.Y)); break; default: break; } // then initialize it with those random values. initialize will save those, // and make sure it is marked as active. p.Initialize( where, velocity, acceleration, lifetime, scale, rotationSpeed); } /// <summary> /// overriden from DrawableGameComponent, Update will update all of the active /// particles. /// </summary> public override void Update(GameTime gameTime) { // calculate dt, the change in the since the last frame. the particle // updates will use this value. float dt = (float)gameTime.ElapsedGameTime.TotalSeconds; // go through all of the particles... foreach (Particle p in particles) { if (p.Active) { // ... and if they're active, update them. p.Acceleration += settings.Gravity * dt; p.Update(dt); // if that update finishes them, put them onto the free particles // queue. if (!p.Active) { freeParticles.Enqueue(p); } } } base.Update(gameTime); } /// <summary> /// Must call before drawing if you wish to change - apply an offset to the /// particle system's drawing - in the case of a movable view. /// You can choose to use this per particle system to allow some "relative" /// and some "absolute" systems /// </summary> public void ApplyCameraOffsetDelta(Vector2 cameraOffsetDelta, float zoomDelta) { foreach (Particle p in particles) { p.Position -= cameraOffsetDelta; p.Scale -= zoomDelta; } } /// <summary> /// overriden from DrawableGameComponent, Draw will use ParticleSampleGame's /// sprite batch to render all of the active particles. /// </summary> public override void Draw(GameTime gameTime) { // tell sprite batch to begin, using the spriteBlendMode specified in // initializeConstants spriteBatch.Begin(SpriteSortMode.Deferred, blendState); foreach (Particle p in particles) { // skip inactive particles if (!p.Active) continue; // normalized lifetime is a value from 0 to 1 and represents how far // a particle is through its life. 0 means it just started, .5 is half // way through, and 1.0 means it's just about to be finished. // this value will be used to calculate alpha and scale, to avoid // having particles suddenly appear or disappear. float normalizedLifetime = p.TimeSinceStart / p.Lifetime; // we want particles to fade in and fade out, so we'll calculate alpha // to be (normalizedLifetime) * (1-normalizedLifetime). this way, when // normalizedLifetime is 0 or 1, alpha is 0. the maximum value is at // normalizedLifetime = .5, and is // (normalizedLifetime) * (1-normalizedLifetime) // (.5) * (1-.5) // .25 // since we want the maximum alpha to be 1, not .25, we'll scale the // entire equation by 4. float alpha = 4 * normalizedLifetime * (1 - normalizedLifetime); Color color = Color.White * alpha; // make particles grow as they age. they'll start at 75% of their size, // and increase to 100% once they're finished. float scale = p.Scale * (.75f + .25f * normalizedLifetime); spriteBatch.Draw(texture, p.Position, null, color, p.Rotation, origin, scale, SpriteEffects.None, 0.0f); } spriteBatch.End(); base.Draw(gameTime); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Collections; using System.Collections.Generic; namespace System.DirectoryServices.AccountManagement { public class PrincipalCollection : ICollection<Principal>, ICollection, IEnumerable<Principal>, IEnumerable { // // ICollection // [System.Security.SecurityCritical] void ICollection.CopyTo(Array array, int index) { CheckDisposed(); // Parameter validation if (index < 0) throw new ArgumentOutOfRangeException("index"); if (array == null) throw new ArgumentNullException("array"); if (array.Rank != 1) throw new ArgumentException(StringResources.PrincipalCollectionNotOneDimensional); if (index >= array.GetLength(0)) throw new ArgumentException(StringResources.PrincipalCollectionIndexNotInArray); ArrayList tempArray = new ArrayList(); lock (_resultSet) { ResultSetBookmark bookmark = null; try { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "CopyTo: bookmarking"); bookmark = _resultSet.BookmarkAndReset(); PrincipalCollectionEnumerator containmentEnumerator = new PrincipalCollectionEnumerator( _resultSet, this, _removedValuesCompleted, _removedValuesPending, _insertedValuesCompleted, _insertedValuesPending); int arraySize = array.GetLength(0) - index; int tempArraySize = 0; while (containmentEnumerator.MoveNext()) { tempArray.Add(containmentEnumerator.Current); checked { tempArraySize++; } // Make sure the array has enough space, allowing for the "index" offset. // We check inline, rather than doing a PrincipalCollection.Count upfront, // because counting is just as expensive as enumerating over all the results, so we // only want to do it once. if (arraySize < tempArraySize) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "PrincipalCollection", "CopyTo: array too small (has {0}, need >= {1}", arraySize, tempArraySize); throw new ArgumentException(StringResources.PrincipalCollectionArrayTooSmall); } } } finally { if (bookmark != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "CopyTo: restoring from bookmark"); _resultSet.RestoreBookmark(bookmark); } } } foreach (object o in tempArray) { array.SetValue(o, index); checked { index++; } } } int ICollection.Count { [System.Security.SecurityCritical] get { return Count; } } bool ICollection.IsSynchronized { [System.Security.SecurityCritical] get { return IsSynchronized; } } object ICollection.SyncRoot { [System.Security.SecurityCritical] get { return SyncRoot; } } public bool IsSynchronized { get { return false; } } public object SyncRoot { get { return this; } } // // IEnumerable // [System.Security.SecurityCritical] IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)GetEnumerator(); } // // ICollection<Principal> // public void CopyTo(Principal[] array, int index) { ((ICollection)this).CopyTo((Array)array, index); } public bool IsReadOnly { get { return false; } } public int Count { [System.Security.SecurityCritical] get { CheckDisposed(); // Yes, this is potentially quite expensive. Count is unfortunately // an expensive operation to perform. lock (_resultSet) { ResultSetBookmark bookmark = null; try { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Count: bookmarking"); bookmark = _resultSet.BookmarkAndReset(); PrincipalCollectionEnumerator containmentEnumerator = new PrincipalCollectionEnumerator( _resultSet, this, _removedValuesCompleted, _removedValuesPending, _insertedValuesCompleted, _insertedValuesPending); int count = 0; // Count all the members (including inserted members, but not including removed members) while (containmentEnumerator.MoveNext()) { count++; } return count; } finally { if (bookmark != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Count: restoring from bookmark"); _resultSet.Reset(); _resultSet.RestoreBookmark(bookmark); } } } } } // // IEnumerable<Principal> // [System.Security.SecurityCritical] public IEnumerator<Principal> GetEnumerator() { CheckDisposed(); return new PrincipalCollectionEnumerator( _resultSet, this, _removedValuesCompleted, _removedValuesPending, _insertedValuesCompleted, _insertedValuesPending); } // // Add // [System.Security.SecurityCritical] public void Add(UserPrincipal user) { Add((Principal)user); } [System.Security.SecurityCritical] public void Add(GroupPrincipal group) { Add((Principal)group); } [System.Security.SecurityCritical] public void Add(ComputerPrincipal computer) { Add((Principal)computer); } [System.Security.SecurityCritical] public void Add(Principal principal) { CheckDisposed(); if (principal == null) throw new ArgumentNullException("principal"); if (Contains(principal)) throw new PrincipalExistsException(StringResources.PrincipalExistsExceptionText); MarkChange(); // If the value to be added is an uncommitted remove, just remove the uncommitted remove from the list. if (_removedValuesPending.Contains(principal)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Add: removing from removedValuesPending"); _removedValuesPending.Remove(principal); // If they did a Add(x) --> Save() --> Remove(x) --> Add(x), we'll end up with x in neither // the ResultSet or the insertedValuesCompleted list. This is bad. Avoid that by adding x // back to the insertedValuesCompleted list here. // // Note, this will add x to insertedValuesCompleted even if it's already in the resultSet. // This is not a problem --- PrincipalCollectionEnumerator will detect such a situation and // only return x once. if (!_insertedValuesCompleted.Contains(principal)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Add: adding to insertedValuesCompleted"); _insertedValuesCompleted.Add(principal); } } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Add: making it a pending insert"); // make it a pending insert _insertedValuesPending.Add(principal); // in case the value to be added is also a previous-but-already-committed remove _removedValuesCompleted.Remove(principal); } } [System.Security.SecurityCritical] public void Add(PrincipalContext context, IdentityType identityType, string identityValue) { CheckDisposed(); if (context == null) throw new ArgumentNullException("context"); if (identityValue == null) throw new ArgumentNullException("identityValue"); Principal principal = Principal.FindByIdentity(context, identityType, identityValue); if (principal != null) { Add(principal); } else { // No Principal matching the IdentityReference could be found in the PrincipalContext GlobalDebug.WriteLineIf(GlobalDebug.Warn, "PrincipalCollection", "Add(urn/urn): no match"); throw new NoMatchingPrincipalException(StringResources.NoMatchingPrincipalExceptionText); } } // // Clear // [System.Security.SecurityCritical] public void Clear() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Clear"); CheckDisposed(); // Ask the StoreCtx to verify that this group can be cleared. Right now, the only // reason it couldn't is if it's an AD group with one principals that are members of it // by virtue of their primaryGroupId. // // If storeCtxToUse == null, then we must be unpersisted, in which case there clearly // can't be any such primary group members pointing to this group on the store. StoreCtx storeCtxToUse = _owningGroup.GetStoreCtxToUse(); string explanation; Debug.Assert(storeCtxToUse != null || _owningGroup.unpersisted == true); if ((storeCtxToUse != null) && (!storeCtxToUse.CanGroupBeCleared(_owningGroup, out explanation))) throw new InvalidOperationException(explanation); MarkChange(); // We wipe out everything that's been inserted/removed _insertedValuesPending.Clear(); _removedValuesPending.Clear(); _insertedValuesCompleted.Clear(); _removedValuesCompleted.Clear(); // flag that the collection has been cleared, so the StoreCtx and PrincipalCollectionEnumerator // can take appropriate action _clearPending = true; } // // Remove // [System.Security.SecurityCritical] public bool Remove(UserPrincipal user) { return Remove((Principal)user); } [System.Security.SecurityCritical] public bool Remove(GroupPrincipal group) { return Remove((Principal)group); } [System.Security.SecurityCritical] public bool Remove(ComputerPrincipal computer) { return Remove((Principal)computer); } [System.Security.SecurityCritical] public bool Remove(Principal principal) { CheckDisposed(); if (principal == null) throw new ArgumentNullException("principal"); // Ask the StoreCtx to verify that this member can be removed. Right now, the only // reason it couldn't is if it's actually a member by virtue of its primaryGroupId // pointing to this group. // // If storeCtxToUse == null, then we must be unpersisted, in which case there clearly // can't be any such primary group members pointing to this group on the store. StoreCtx storeCtxToUse = _owningGroup.GetStoreCtxToUse(); string explanation; Debug.Assert(storeCtxToUse != null || _owningGroup.unpersisted == true); if ((storeCtxToUse != null) && (!storeCtxToUse.CanGroupMemberBeRemoved(_owningGroup, principal, out explanation))) throw new InvalidOperationException(explanation); bool removed = false; // If the value was previously inserted, we just remove it from insertedValuesPending. if (_insertedValuesPending.Contains(principal)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Remove: removing from insertedValuesPending"); MarkChange(); _insertedValuesPending.Remove(principal); removed = true; // If they did a Remove(x) --> Save() --> Add(x) --> Remove(x), we'll end up with x in neither // the ResultSet or the removedValuesCompleted list. This is bad. Avoid that by adding x // back to the removedValuesCompleted list here. // // At worst, we end up with x on the removedValuesCompleted list even though it's not even in // resultSet. That's not a problem. The only thing we use the removedValuesCompleted list for // is deciding which values in resultSet to skip, anyway. if (!_removedValuesCompleted.Contains(principal)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Remove: adding to removedValuesCompleted"); _removedValuesCompleted.Add(principal); } } else { // They're trying to remove a already-persisted value. We add it to the // removedValues list. Then, if it's already been loaded into insertedValuesCompleted, // we remove it from insertedValuesCompleted. removed = Contains(principal); GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Remove: making it a pending remove, removed={0}", removed); if (removed) { MarkChange(); _removedValuesPending.Add(principal); // in case it's the result of a previous-but-already-committed insert _insertedValuesCompleted.Remove(principal); } } return removed; } [System.Security.SecurityCritical] public bool Remove(PrincipalContext context, IdentityType identityType, string identityValue) { CheckDisposed(); if (context == null) throw new ArgumentNullException("context"); if (identityValue == null) throw new ArgumentNullException("identityValue"); Principal principal = Principal.FindByIdentity(context, identityType, identityValue); if (principal == null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "PrincipalCollection", "Remove(urn/urn): no match"); throw new NoMatchingPrincipalException(StringResources.NoMatchingPrincipalExceptionText); } return Remove(principal); } // // Contains // [System.Security.SecuritySafeCritical] private bool ContainsEnumTest(Principal principal) { CheckDisposed(); if (principal == null) throw new ArgumentNullException("principal"); // Yes, this is potentially quite expensive. Contains is unfortunately // an expensive operation to perform. lock (_resultSet) { ResultSetBookmark bookmark = null; try { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "ContainsEnumTest: bookmarking"); bookmark = _resultSet.BookmarkAndReset(); PrincipalCollectionEnumerator containmentEnumerator = new PrincipalCollectionEnumerator( _resultSet, this, _removedValuesCompleted, _removedValuesPending, _insertedValuesCompleted, _insertedValuesPending); while (containmentEnumerator.MoveNext()) { Principal p = containmentEnumerator.Current; if (p.Equals(principal)) return true; } } finally { if (bookmark != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "ContainsEnumTest: restoring from bookmark"); _resultSet.RestoreBookmark(bookmark); } } } return false; } [System.Security.SecuritySafeCritical] private bool ContainsNativeTest(Principal principal) { CheckDisposed(); if (principal == null) throw new ArgumentNullException("principal"); // If they explicitly inserted it, then we certainly contain it if (_insertedValuesCompleted.Contains(principal) || _insertedValuesPending.Contains(principal)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "ContainsNativeTest: found insert"); return true; } // If they removed it, we don't contain it, regardless of the group membership on the store if (_removedValuesCompleted.Contains(principal) || _removedValuesPending.Contains(principal)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "ContainsNativeTest: found remove"); return false; } // The list was cleared at some point and the principal has not been reinsterted yet if (_clearPending || _clearCompleted) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "ContainsNativeTest: Clear pending"); return false; } // Otherwise, check the store if (_owningGroup.unpersisted == false && principal.unpersisted == false) return _owningGroup.GetStoreCtxToUse().IsMemberOfInStore(_owningGroup, principal); // We (or the principal) must not be persisted, so there's no store membership to check. // Out of things to check. We must not contain it. GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "ContainsNativeTest: no store to check"); return false; } [System.Security.SecurityCritical] public bool Contains(UserPrincipal user) { return Contains((Principal)user); } [System.Security.SecurityCritical] public bool Contains(GroupPrincipal group) { return Contains((Principal)group); } [System.Security.SecurityCritical] public bool Contains(ComputerPrincipal computer) { return Contains((Principal)computer); } [System.Security.SecurityCritical] public bool Contains(Principal principal) { StoreCtx storeCtxToUse = _owningGroup.GetStoreCtxToUse(); // If the store has a shortcut for testing membership, use it. // Otherwise we enumerate all members and look for a match. if ((storeCtxToUse != null) && (storeCtxToUse.SupportsNativeMembershipTest)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Contains: using native test (store ctx is null = {0})", (storeCtxToUse == null)); return ContainsNativeTest(principal); } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Contains: using enum test"); return ContainsEnumTest(principal); } } [System.Security.SecurityCritical] public bool Contains(PrincipalContext context, IdentityType identityType, string identityValue) { CheckDisposed(); if (context == null) throw new ArgumentNullException("context"); if (identityValue == null) throw new ArgumentNullException("identityValue"); bool found = false; Principal principal = Principal.FindByIdentity(context, identityType, identityValue); if (principal != null) found = Contains(principal); return found; } // // Internal constructor // // Constructs a fresh PrincipalCollection based on the supplied ResultSet. // The ResultSet may not be null (use an EmptySet instead). [System.Security.SecurityCritical] internal PrincipalCollection(BookmarkableResultSet results, GroupPrincipal owningGroup) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Ctor"); Debug.Assert(results != null); _resultSet = results; _owningGroup = owningGroup; } // // Internal "disposer" // // Ideally, we'd like to implement IDisposable, since we need to dispose of the ResultSet. // But IDisposable would have to be a public interface, and we don't want the apps calling Dispose() // on us, only the Principal that owns us. So we implement an "internal" form of Dispose(). internal void Dispose() { if (!_disposed) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Dispose: disposing"); lock (_resultSet) { if (_resultSet != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Dispose: disposing resultSet"); _resultSet.Dispose(); } } _disposed = true; } } // // Private implementation // // The group we're a PrincipalCollection of [System.Security.SecuritySafeCritical] private GroupPrincipal _owningGroup; // // SYNCHRONIZATION // Access to: // resultSet // must be synchronized, since multiple enumerators could be iterating over us at once. // Synchronize by locking on resultSet. // Represents the Principals retrieved from the store for this collection private BookmarkableResultSet _resultSet; // Contains Principals inserted into this collection for which the insertion has not been persisted to the store private List<Principal> _insertedValuesCompleted = new List<Principal>(); private List<Principal> _insertedValuesPending = new List<Principal>(); // Contains Principals removed from this collection for which the removal has not been persisted // to the store private List<Principal> _removedValuesCompleted = new List<Principal>(); private List<Principal> _removedValuesPending = new List<Principal>(); // Has this collection been cleared? private bool _clearPending = false; private bool _clearCompleted = false; internal bool ClearCompleted { get { return _clearCompleted; } } // Used so our enumerator can detect changes to the collection and throw an exception private DateTime _lastChange = DateTime.UtcNow; internal DateTime LastChange { get { return _lastChange; } } internal void MarkChange() { _lastChange = DateTime.UtcNow; } // To support disposal private bool _disposed = false; private void CheckDisposed() { if (_disposed) throw new ObjectDisposedException("PrincipalCollection"); } // // Load/Store Implementation // internal List<Principal> Inserted { get { return _insertedValuesPending; } } internal List<Principal> Removed { get { return _removedValuesPending; } } internal bool Cleared { get { return _clearPending; } } // Return true if the membership has changed (i.e., either insertedValuesPending or removedValuesPending is // non-empty) internal bool Changed { get { return ((_insertedValuesPending.Count > 0) || (_removedValuesPending.Count > 0) || (_clearPending)); } } // Resets the change-tracking of the membership to 'unchanged', by moving all pending operations to completed status. internal void ResetTracking() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "ResetTracking"); foreach (Principal p in _removedValuesPending) { Debug.Assert(!_removedValuesCompleted.Contains(p)); _removedValuesCompleted.Add(p); } _removedValuesPending.Clear(); foreach (Principal p in _insertedValuesPending) { Debug.Assert(!_insertedValuesCompleted.Contains(p)); _insertedValuesCompleted.Add(p); } _insertedValuesPending.Clear(); if (_clearPending) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "ResetTracking: clearing"); _clearCompleted = true; _clearPending = false; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Octokit.Internal; using Xunit; namespace Octokit.Tests.Http { public class RedirectHandlerTests { [Fact] public async Task OkStatusShouldPassThrough() { var invoker = CreateInvoker(new HttpResponseMessage(HttpStatusCode.OK)); var httpRequestMessage = CreateRequest(HttpMethod.Get); var response = await invoker.SendAsync(httpRequestMessage, new CancellationToken()); Assert.Equal(response.StatusCode, HttpStatusCode.OK); Assert.Same(response.RequestMessage, httpRequestMessage); } [Theory] [InlineData(HttpStatusCode.MovedPermanently)] // 301 [InlineData(HttpStatusCode.Found)] // 302 [InlineData(HttpStatusCode.TemporaryRedirect)] // 307 public async Task ShouldRedirectSameMethod(HttpStatusCode statusCode) { var redirectResponse = new HttpResponseMessage(statusCode); redirectResponse.Headers.Location = new Uri("http://example.org/bar"); var invoker = CreateInvoker(redirectResponse, new HttpResponseMessage(HttpStatusCode.OK)); var httpRequestMessage = CreateRequest(HttpMethod.Post); var response = await invoker.SendAsync(httpRequestMessage, new CancellationToken()); Assert.Equal(response.RequestMessage.Method, httpRequestMessage.Method); Assert.NotSame(response.RequestMessage, httpRequestMessage); } [Fact] public async Task Status303ShouldRedirectChangeMethod() { var redirectResponse = new HttpResponseMessage(HttpStatusCode.SeeOther); redirectResponse.Headers.Location = new Uri("http://example.org/bar"); var invoker = CreateInvoker(redirectResponse, new HttpResponseMessage(HttpStatusCode.OK)); var httpRequestMessage = CreateRequest(HttpMethod.Post); var response = await invoker.SendAsync(httpRequestMessage, new CancellationToken()); Assert.Equal(HttpMethod.Get, response.RequestMessage.Method); Assert.NotSame(response.RequestMessage, httpRequestMessage); } [Fact] public async Task RedirectWithSameHostShouldKeepAuthHeader() { var redirectResponse = new HttpResponseMessage(HttpStatusCode.Redirect); redirectResponse.Headers.Location = new Uri("http://example.org/bar"); var invoker = CreateInvoker(redirectResponse, new HttpResponseMessage(HttpStatusCode.OK)); var httpRequestMessage = CreateRequest(HttpMethod.Get); httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue("fooAuth", "aparam"); var response = await invoker.SendAsync(httpRequestMessage, new CancellationToken()); Assert.NotSame(response.RequestMessage, httpRequestMessage); Assert.Equal("fooAuth", response.RequestMessage.Headers.Authorization.Scheme); } [Theory] [InlineData(HttpStatusCode.MovedPermanently)] // 301 [InlineData(HttpStatusCode.Found)] // 302 [InlineData(HttpStatusCode.SeeOther)] // 303 [InlineData(HttpStatusCode.TemporaryRedirect)] // 307 public async Task RedirectWithDifferentHostShouldLoseAuthHeader(HttpStatusCode statusCode) { var redirectResponse = new HttpResponseMessage(statusCode); redirectResponse.Headers.Location = new Uri("http://example.net/bar"); var invoker = CreateInvoker(redirectResponse, new HttpResponseMessage(HttpStatusCode.OK)); var httpRequestMessage = CreateRequest(HttpMethod.Get); httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue("fooAuth", "aparam"); var response = await invoker.SendAsync(httpRequestMessage, new CancellationToken()); Assert.NotSame(response.RequestMessage, httpRequestMessage); Assert.Null(response.RequestMessage.Headers.Authorization); } [Theory] [InlineData(HttpStatusCode.MovedPermanently)] // 301 [InlineData(HttpStatusCode.Found)] // 302 [InlineData(HttpStatusCode.TemporaryRedirect)] // 307 public async Task Status301ShouldRedirectPOSTWithBody(HttpStatusCode statusCode) { var redirectResponse = new HttpResponseMessage(statusCode); redirectResponse.Headers.Location = new Uri("http://example.org/bar"); var invoker = CreateInvoker(redirectResponse, new HttpResponseMessage(HttpStatusCode.OK)); var httpRequestMessage = CreateRequest(HttpMethod.Post); httpRequestMessage.Content = new StringContent("Hello World"); var response = await invoker.SendAsync(httpRequestMessage, new CancellationToken()); Assert.Equal(response.RequestMessage.Method, httpRequestMessage.Method); Assert.NotSame(response.RequestMessage, httpRequestMessage); Assert.Equal("Hello World", await response.RequestMessage.Content.ReadAsStringAsync()); } // POST see other with content [Fact] public async Task Status303ShouldRedirectToGETWithoutBody() { var redirectResponse = new HttpResponseMessage(HttpStatusCode.SeeOther); redirectResponse.Headers.Location = new Uri("http://example.org/bar"); var invoker = CreateInvoker(redirectResponse, new HttpResponseMessage(HttpStatusCode.OK)); var httpRequestMessage = CreateRequest(HttpMethod.Post); httpRequestMessage.Content = new StringContent("Hello World"); var response = await invoker.SendAsync(httpRequestMessage, new CancellationToken()); Assert.Equal(HttpMethod.Get, response.RequestMessage.Method); Assert.NotSame(response.RequestMessage, httpRequestMessage); Assert.Null(response.RequestMessage.Content); } [Fact] public async Task Exceed3RedirectsShouldReturn() { var redirectResponse = new HttpResponseMessage(HttpStatusCode.Found); redirectResponse.Headers.Location = new Uri("http://example.org/bar"); var redirectResponse2 = new HttpResponseMessage(HttpStatusCode.Found); redirectResponse2.Headers.Location = new Uri("http://example.org/foo"); var invoker = CreateInvoker(redirectResponse, redirectResponse2); var httpRequestMessage = CreateRequest(HttpMethod.Get); Assert.ThrowsAsync<InvalidOperationException>( () => invoker.SendAsync(httpRequestMessage, new CancellationToken())); } static HttpRequestMessage CreateRequest(HttpMethod method) { var httpRequestMessage = new HttpRequestMessage(); httpRequestMessage.RequestUri = new Uri("http://example.org/foo"); httpRequestMessage.Method = method; return httpRequestMessage; } static HttpMessageInvoker CreateInvoker(HttpResponseMessage httpResponseMessage1, HttpResponseMessage httpResponseMessage2 = null) { var redirectHandler = new RedirectHandler() { InnerHandler = new MockRedirectHandler(httpResponseMessage1, httpResponseMessage2) }; var invoker = new HttpMessageInvoker(redirectHandler); return invoker; } } public class MockRedirectHandler : HttpMessageHandler { readonly HttpResponseMessage _response1; readonly HttpResponseMessage _response2; private bool _Response1Sent = false; public MockRedirectHandler(HttpResponseMessage response1, HttpResponseMessage response2 = null) { _response1 = response1; _response2 = response2; } protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (!_Response1Sent) { _Response1Sent = true; _response1.RequestMessage = request; return _response1; } else { _response2.RequestMessage = request; return _response2; } } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Diagnostics; namespace fyiReporting.RDL { /// <summary> /// The PageTree object contains references to all the pages used within the Pdf. /// All individual pages are referenced through the kids string /// </summary> internal class PdfPageTree:PdfBase { private string pageTree; private string kids; private int MaxPages; internal PdfPageTree(PdfAnchor pa):base(pa) { kids="[ "; MaxPages=0; } /// <summary> /// Add a page to the Page Tree. ObjNum is the object number of the page to be added. /// pageNum is the page number of the page. /// </summary> /// <param name="objNum"></param> internal void AddPage(int objNum) { Debug.Assert(objNum >= 0 && objNum <= this.Current); MaxPages++; string refPage=objNum+" 0 R "; kids=kids+refPage; } /// <summary> /// returns the Page Tree Dictionary /// </summary> /// <returns></returns> internal byte[] GetPageTree(long filePos,out int size) { pageTree=string.Format("\r\n{0} 0 obj<</Count {1}/Kids {2}]>> endobj\t", this.objectNum,MaxPages,kids); return this.GetUTF8Bytes(pageTree,filePos,out size); } } /// <summary> /// This class represents individual pages within the pdf. /// The contents of the page belong to this class /// </summary> internal class PdfPage:PdfBase { private string page; private string pageSize; private string fontRef; private string imageRef; private string patternRef; private string colorSpaceRef; private string resourceDict,contents; private string annotsDict; internal PdfPage(PdfAnchor pa):base(pa) { resourceDict=null; contents=null; pageSize=null; fontRef=null; imageRef=null; annotsDict=null; colorSpaceRef=null; patternRef=null; } /// <summary> /// Create The Pdf page /// </summary> internal void CreatePage(int refParent,PdfPageSize pSize) { pageSize=string.Format("[0 0 {0} {1}]",pSize.xWidth,pSize.yHeight); page=string.Format("\r\n{0} 0 obj<</Type /Page/Parent {1} 0 R/Rotate 0/MediaBox {2}/CropBox {2}", this.objectNum,refParent,pageSize); } internal void AddHyperlink(float x, float y, float height, float width, string url) { if (annotsDict == null) annotsDict = "\r/Annots ["; annotsDict += string.Format(@"<</Type /Annot /Subtype /Link /Rect [{0} {1} {2} {3}] /Border [0 0 0] /A <</S /URI /URI ({4})>>>>", x, y, x+width, y-height, url); } internal void AddToolTip(float x, float y, float height, float width, string tooltip) { if (annotsDict == null) annotsDict = "\r/Annots ["; annotsDict += string.Format(@"<</Type /Annot /Rect [{0} {1} {2} {3}] /Border [0 0 0] /IC [1.0 1.0 0.666656] /CA 0.00500488 /C [1.0 0.0 0.0] /Name/Comment /T(Value) /Contents({4}) /F 288 /Subtype/Square>>", /*/A <</S /URI /URI ({4})>>*/ x, y, x + width, y - height, tooltip); } /// <summary> /// Add Pattern Resources to the pdf page /// </summary> internal void AddResource(PdfPattern patterns,int contentRef) { foreach (PdfPatternEntry pat in patterns.Patterns.Values) { patternRef+=string.Format("/{0} {1} 0 R",pat.pattern,pat.objectNum); } if(contentRef>0) { contents=string.Format("/Contents {0} 0 R",contentRef); } } /// <summary> /// Add Font Resources to the pdf page /// </summary> internal void AddResource(PdfFonts fonts,int contentRef) { foreach (PdfFontEntry font in fonts.Fonts.Values) { fontRef+=string.Format("/{0} {1} 0 R",font.font,font.objectNum); } if(contentRef>0) { contents=string.Format("/Contents {0} 0 R",contentRef); } } internal void AddResource(PatternObj po,int contentRef) { colorSpaceRef=string.Format("/CS1 {0} 0 R",po.objectNum); } /// <summary> /// Add Image Resources to the pdf page /// </summary> internal void AddResource(PdfImageEntry ie,int contentRef) { if (imageRef == null || imageRef.IndexOf("/"+ie.name) < 0) // only need it once per page // imageRef+=string.Format("/XObject << /{0} {1} 0 R >>",ie.name,ie.objectNum); imageRef+=string.Format("/{0} {1} 0 R ",ie.name,ie.objectNum); if(contentRef>0) { contents=string.Format("/Contents {0} 0 R",contentRef); } } /// <summary> /// Get the Page Dictionary to be written to the file /// </summary> /// <returns></returns> internal byte[] GetPageDict(long filePos,out int size) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); //will need to add pattern here sb.AppendFormat("/Resources<<\r\n/Font<<{0}>>",fontRef); if (patternRef != null) sb.AppendFormat("\r\n/Pattern <<{0}>>",patternRef); if (colorSpaceRef != null) sb.AppendFormat("\r\n/ColorSpace <<{0}>>",colorSpaceRef); sb.Append("\r\n/ProcSet[/PDF/Text"); if (imageRef == null) sb.Append("]>>"); else sb.AppendFormat("\r\n/ImageB]/XObject <<{0}>>>>",imageRef); resourceDict = sb.ToString(); //if (imageRef == null) // resourceDict=string.Format("/Resources<</Font<<{0}>>/ProcSet[/PDF/Text]>>",fontRef); //else // resourceDict=string.Format("/Resources<</Font<<{0}>>/ProcSet[/PDF/Text/ImageB]/XObject <<{1}>>>>",fontRef, imageRef); if (annotsDict != null) page += (annotsDict+"]\r"); page+=resourceDict+"\r\n"+contents+">>\r\nendobj\r\n"; return this.GetUTF8Bytes(page,filePos,out size); } } /// <summary> /// Specify the page size in 1/72 inches units. /// </summary> internal struct PdfPageSize { internal int xWidth; internal int yHeight; internal int leftMargin; internal int rightMargin; internal int topMargin; internal int bottomMargin; internal PdfPageSize(int width,int height) { xWidth=width; yHeight=height; leftMargin=0; rightMargin=0; topMargin=0; bottomMargin=0; } internal void SetMargins(int L,int T,int R,int B) { leftMargin=L; rightMargin=R; topMargin=T; bottomMargin=B; } } }
#if !SILVERLIGHT using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NServiceKit.Messaging { /// <summary>A transient message service base.</summary> public abstract class TransientMessageServiceBase : IMessageService, IMessageHandlerDisposer { private bool isRunning; /// <summary>Will be a total of 3 attempts.</summary> public const int DefaultRetryCount = 2; /// <summary>Gets the number of retries.</summary> /// /// <value>The number of retries.</value> public int RetryCount { get; protected set; } /// <summary>Gets the request time out.</summary> /// /// <value>The request time out.</value> public TimeSpan? RequestTimeOut { get; protected set; } /// <summary>Gets the size of the pool.</summary> /// /// <value>The size of the pool.</value> public int PoolSize { get; protected set; } //use later /// <summary>Factory to create consumers and producers that work with this service.</summary> /// /// <value>The message factory.</value> public abstract IMessageFactory MessageFactory { get; } /// <summary>Initializes a new instance of the NServiceKit.Messaging.TransientMessageServiceBase class.</summary> protected TransientMessageServiceBase() : this(DefaultRetryCount, null) { } /// <summary>Initializes a new instance of the NServiceKit.Messaging.TransientMessageServiceBase class.</summary> /// /// <param name="retryAttempts"> The retry attempts.</param> /// <param name="requestTimeOut">The request time out.</param> protected TransientMessageServiceBase(int retryAttempts, TimeSpan? requestTimeOut) { this.RetryCount = retryAttempts; this.RequestTimeOut = requestTimeOut; } private readonly Dictionary<Type, IMessageHandlerFactory> handlerMap = new Dictionary<Type, IMessageHandlerFactory>(); private IMessageHandler[] messageHandlers; /// <summary>Registers the handler.</summary> /// /// <typeparam name="T">Generic type parameter.</typeparam> /// <param name="processMessageFn">The process message function.</param> public void RegisterHandler<T>(Func<IMessage<T>, object> processMessageFn) { RegisterHandler(processMessageFn, null); } /// <summary>Registers the handler.</summary> /// /// <exception cref="ArgumentException">Thrown when one or more arguments have unsupported or illegal values.</exception> /// /// <typeparam name="T">Generic type parameter.</typeparam> /// <param name="processMessageFn"> The process message function.</param> /// <param name="processExceptionEx">The process exception ex.</param> public void RegisterHandler<T>(Func<IMessage<T>, object> processMessageFn, Action<IMessage<T>, Exception> processExceptionEx) { if (handlerMap.ContainsKey(typeof(T))) { throw new ArgumentException("Message handler has already been registered for type: " + typeof(T).Name); } handlerMap[typeof(T)] = CreateMessageHandlerFactory(processMessageFn, processExceptionEx); } /// <summary>Get Total Current Stats for all Message Handlers.</summary> /// /// <returns>The statistics.</returns> public IMessageHandlerStats GetStats() { var total = new MessageHandlerStats("All Handlers"); messageHandlers.ToList().ForEach(x => total.Add(x.GetStats())); return total; } /// <summary>Get a list of all message types registered on this MQ Host.</summary> /// /// <value>A list of types of the registered.</value> public List<Type> RegisteredTypes { get { return handlerMap.Keys.ToList(); } } /// <summary>Get the status of the service. Potential Statuses: Disposed, Stopped, Stopping, Starting, Started.</summary> /// /// <returns>The status.</returns> public string GetStatus() { return isRunning ? "Started" : "Stopped"; } /// <summary>Get a Stats dump.</summary> /// /// <returns>The statistics description.</returns> public string GetStatsDescription() { var sb = new StringBuilder("#MQ HOST STATS:\n"); sb.AppendLine("==============="); foreach (var messageHandler in messageHandlers) { sb.AppendLine(messageHandler.GetStats().ToString()); sb.AppendLine("---------------"); } return sb.ToString(); } /// <summary>Creates message handler factory.</summary> /// /// <typeparam name="T">Generic type parameter.</typeparam> /// <param name="processMessageFn"> The process message function.</param> /// <param name="processExceptionEx">The process exception ex.</param> /// /// <returns>The new message handler factory.</returns> protected IMessageHandlerFactory CreateMessageHandlerFactory<T>( Func<IMessage<T>, object> processMessageFn, Action<IMessage<T>, Exception> processExceptionEx) { return new MessageHandlerFactory<T>(this, processMessageFn, processExceptionEx) { RetryCount = RetryCount, }; } /// <summary>Start the MQ Host if not already started.</summary> public virtual void Start() { if (isRunning) return; isRunning = true; this.messageHandlers = this.handlerMap.Values.ToList().ConvertAll( x => x.CreateMessageHandler()).ToArray(); using (var mqClient = MessageFactory.CreateMessageQueueClient()) { foreach (var handler in messageHandlers) { handler.Process(mqClient); } } this.Stop(); } /// <summary>Stop the MQ Host if not already stopped.</summary> public virtual void Stop() { isRunning = false; messageHandlers = null; } /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary> public virtual void Dispose() { Stop(); } /// <summary>Handler, called when the dispose message.</summary> /// /// <param name="messageHandler">The message handler.</param> public virtual void DisposeMessageHandler(IMessageHandler messageHandler) { lock (messageHandlers) { if (!isRunning) return; var allHandlersAreDisposed = true; for (var i = 0; i < messageHandlers.Length; i++) { if (messageHandlers[i] == messageHandler) { messageHandlers[i] = null; } allHandlersAreDisposed = allHandlersAreDisposed && messageHandlers[i] == null; } if (allHandlersAreDisposed) { Stop(); } } } } } #endif
using Aspose.Slides.Export; using Aspose.Slides.Web.API.Clients.Enums; using Aspose.Slides.Web.Core.Enums; using Aspose.Slides.Web.Core.Helpers; using Aspose.Slides.Web.Core.Infrastructure; using Aspose.Slides.Web.Interfaces.Services; using Microsoft.Extensions.Logging; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; namespace Aspose.Slides.Web.Core.Services.Conversion { /// <summary> /// Implementation of slides conversion logic. /// </summary> internal sealed class ConversionService : SlidesServiceBase, IConversionService { private readonly IGifEncoder _gifEncoder; /// <summary> /// Ctor /// </summary> /// <param name="logger"></param> /// <param name="gifEncoder"></param> /// <param name="licenseProvider"></param> public ConversionService(ILogger<ConversionService> logger, IGifEncoder gifEncoder, ILicenseProvider licenseProvider) : base(logger) { _gifEncoder = gifEncoder; licenseProvider.SetAsposeLicense(AsposeProducts.Slides); licenseProvider.SetAsposeLicense(AsposeProducts.Words); } /// <summary> /// Converts source file into target format, saves resulted file to out file. /// Returns null in case of multiple files (all saved into outFolder). /// </summary> /// <param name="sourceFiles">Source slides files to proceed.</param> /// <param name="outFolder">Output folder.</param> /// <param name="format">Output format.</param> /// <param name="cancellationToken">A cancellation token to observe while waiting for the task to complete.</param> /// <returns>Result file paths.</returns> public IEnumerable<string> Conversion( IList<string> sourceFiles, string outFolder, SlidesConversionFormats format, CancellationToken cancellationToken = default ) { var outFiles = new ConcurrentBag<string>(); void conversion(int index) { cancellationToken.ThrowIfCancellationRequested(); var sourceFile = sourceFiles[index]; var fileName = Path.GetFileNameWithoutExtension(sourceFile); var outOneFile = Path.Combine(outFolder, $"{fileName}.{format}"); using var presentation = new Presentation(sourceFile); switch (format) { case SlidesConversionFormats.odp: case SlidesConversionFormats.otp: case SlidesConversionFormats.pptx: case SlidesConversionFormats.pptm: case SlidesConversionFormats.potx: case SlidesConversionFormats.ppt: case SlidesConversionFormats.pps: case SlidesConversionFormats.ppsm: case SlidesConversionFormats.pot: case SlidesConversionFormats.potm: case SlidesConversionFormats.pdf: case SlidesConversionFormats.xps: case SlidesConversionFormats.ppsx: case SlidesConversionFormats.tiff: case SlidesConversionFormats.html: case SlidesConversionFormats.swf: { var slidesFormat = format.ToString().ParseEnum<SaveFormat>(); cancellationToken.ThrowIfCancellationRequested(); presentation.Save(outOneFile, slidesFormat); outFiles.Add(outOneFile); break; } case SlidesConversionFormats.txt: { var lines = new List<string>(); foreach (var slide in presentation.Slides) { foreach (var shp in slide.Shapes) { if (shp is AutoShape ashp) lines.Add(ashp.TextFrame.Text); cancellationToken.ThrowIfCancellationRequested(); } var notes = slide.NotesSlideManager.NotesSlide?.NotesTextFrame?.Text; if (!string.IsNullOrEmpty(notes)) lines.Add(notes); cancellationToken.ThrowIfCancellationRequested(); } cancellationToken.ThrowIfCancellationRequested(); System.IO.File.WriteAllLines(outOneFile, lines); outFiles.Add(outOneFile); break; } case SlidesConversionFormats.doc: case SlidesConversionFormats.docx: { using (var stream = new MemoryStream()) { cancellationToken.ThrowIfCancellationRequested(); presentation.Save(stream, SaveFormat.Html); stream.Flush(); stream.Seek(0, SeekOrigin.Begin); var doc = new Words.Document(stream); cancellationToken.ThrowIfCancellationRequested(); switch (format) { case SlidesConversionFormats.doc: doc.Save(outOneFile, Words.SaveFormat.Doc); break; case SlidesConversionFormats.docx: doc.Save(outOneFile, Words.SaveFormat.Docx); break; default: throw new ArgumentException($"Unknown format {format}"); } } outFiles.Add(outOneFile); break; } case SlidesConversionFormats.bmp: case SlidesConversionFormats.jpeg: case SlidesConversionFormats.png: case SlidesConversionFormats.emf: case SlidesConversionFormats.wmf: case SlidesConversionFormats.exif: case SlidesConversionFormats.ico: { for (var i = 0; i < presentation.Slides.Count; i++) { var slide = presentation.Slides[i]; var outFile = Path.Combine(outFolder, $"{i}.{format}"); using (var bitmap = slide.GetThumbnail(1, 1))// (new Size((int)size.Width, (int)size.Height))) { cancellationToken.ThrowIfCancellationRequested(); bitmap.Save(outFile, format.GetImageFormat()); } outFiles.Add(outFile); cancellationToken.ThrowIfCancellationRequested(); } break; } case SlidesConversionFormats.svg: { var svgOptions = new SVGOptions { PicturesCompression = PicturesCompression.DocumentResolution }; for (var i = 0; i < presentation.Slides.Count; i++) { var slide = presentation.Slides[i]; var outFile = Path.Combine(outFolder, $"{i}.{format}"); using (var stream = new FileStream(outFile, FileMode.CreateNew)) { cancellationToken.ThrowIfCancellationRequested(); slide.WriteAsSvg(stream, svgOptions); } outFiles.Add(outFile); cancellationToken.ThrowIfCancellationRequested(); } break; } case SlidesConversionFormats.gif: { _gifEncoder.Encode(presentation, outOneFile, cancellationToken); outFiles.Add(outOneFile); break; } default: throw new ArgumentException($"Unknown format {format}"); } } try { Parallel.For(0, sourceFiles.Count, conversion); } catch (AggregateException ae) { foreach (var e in ae.InnerExceptions) { throw e; } } return outFiles; } /// <summary> /// Asynchronously converts source file into target format, saves resulted file to out file. /// </summary> /// <param name="sourceFiles">Source slides files to proceed.</param> /// <param name="outFolder">Output folder.</param> /// <param name="format">Output format.</param> /// <param name="cancellationToken">A cancellation token to observe while waiting for the task to complete.</param> /// <returns>Result file paths.</returns> public async Task<IEnumerable<string>> ConversionAsync( IList<string> sourceFiles, string outFolder, SlidesConversionFormats format, CancellationToken cancellationToken = default ) => await Task.Run(() => Conversion(sourceFiles, outFolder, format, cancellationToken)); } }
// 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. #define CONTRACTS_FULL using System; using System.Diagnostics.Contracts; using Microsoft.Research.ClousotRegression; namespace MichaelRepros { public class MichaelRepro0 { static int m; [ClousotRegressionTest("postonly")] public void f0() { m = 0; } [ClousotRegressionTest("postonly")] public void f12() { m = 12; } [ClousotRegressionTest("postonly")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 14, MethodILOffset = 0)] public void Testf0() { f0(); Contract.Assert(m == 0); } [ClousotRegressionTest("postonly")] [RegressionOutcome(Outcome = ProofOutcome.False, Message = @"assert is false", PrimaryILOffset = 18, MethodILOffset = 0)] public void Testf0_False() { f0(); Contract.Assert(m == 999); } [ClousotRegressionTest("postonly")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 15, MethodILOffset = 0)] public void Testf12() { f12(); Contract.Assert(m == 12); } } unsafe public class MichaelRepro1 { //[ClousotRegressionTest("postonly")] public void SetToNull(out int* ptr) { ptr = null; } //[ClousotRegressionTest("postonly")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 16, MethodILOffset = 0)] public void TestSetToNull() { int* p = null; SetToNull(out p); Contract.Assert(p == null); } } public class MichaelRepro2 { public bool b; // this.b == true [ClousotRegressionTest("postonly")] public MichaelRepro2() { this.b = true; } // ok (nothing) [ClousotRegressionTest("postonly")] public MichaelRepro2(int x) { if (x > 10) this.b = true; else this.b = false; } // this.b == b [ClousotRegressionTest("postonly")] public MichaelRepro2(bool b) { this.b = b; } // nothing... Because of the control flow [ClousotRegressionTest("postonly")] public MichaelRepro2(bool b1, bool b2) { this.b = b1 && b2; } // return == true [ClousotRegressionTest("postonly")] public bool AlwaysTrue() { return true; } // return == false [ClousotRegressionTest("postonly")] public bool AlwaysFalse() { return false; } [ClousotRegressionTest("postonly")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 12, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"assert unproven", PrimaryILOffset = 31, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 52, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"assert unproven", PrimaryILOffset = 74, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 93, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 108, MethodILOffset = 0)] public void Test() { var m1 = new MichaelRepro2(); Contract.Assert(m1.b == true); // true var m2 = new MichaelRepro2(29); Contract.Assert(m2.b); // true, but we cannot prove it var m3 = new MichaelRepro2(false); Contract.Assert(!m3.b); // true var m4 = new MichaelRepro2(true, false); Contract.Assert(!m4.b); // true, but we cannot prove it var m5 = new MichaelRepro2(); Contract.Assert(m5.AlwaysTrue()); // true; Contract.Assert(!m5.AlwaysFalse()); // true } } public class MichaelRepro3 { public enum SomeEnum { A = 2, B, C } [ClousotRegressionTest("postonly")] public SomeEnum ReturnEnum(int x) { if (x == 2) return SomeEnum.A; else return SomeEnum.B; } // ok [ClousotRegressionTest("postonly")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 22, MethodILOffset = 0)] public void Test() { var x = new MichaelRepro3(); var r = x.ReturnEnum(12); Contract.Assert(r != SomeEnum.C); } } public class MichaelRepro4 { public string Value; public MichaelRepro4 mRep; [ClousotRegressionTest("postonly")] public MichaelRepro4(string val, MichaelRepro4 rep) { this.Value = val; this.mRep = rep; } [ClousotRegressionTest("postonly")] public MichaelRepro4() : this(null, null) { } [ClousotRegressionTest("postonly")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 15, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.False, Message = @"assert is false", PrimaryILOffset = 32, MethodILOffset = 0)] public void Test() { var obj = new MichaelRepro4(); Contract.Assert(obj.Value == null); // true Contract.Assert(obj.mRep != null); // false } } public class MichaelRepro5 { public bool mBool; public bool mIndic; [ClousotRegressionTest("postonly")] public MichaelRepro5() { // Ensures: this.mIndic == true if (!mBool) mIndic = true; // Unreachable! } [ClousotRegressionTest("postonly")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 12, MethodILOffset = 0)] public void Test() { var m1 = new MichaelRepro5(); Contract.Assert(m1.mIndic == true); } } } namespace MafRepros { public class FilterNonNull { string s; [ContractInvariantMethod] void ObjectInvariant() { Contract.Invariant(s != null); } [ClousotRegressionTest("postonly")] public string S { set { this.s = value; } get { return this.s; } } [ClousotRegressionTest("postonly")] [RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"assert unproven",PrimaryILOffset=25,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"invariant unproven: s != null",PrimaryILOffset=12,MethodILOffset=41)] public FilterNonNull(string s) { this.S = s; Contract.Assert(this.s != null); // should be top! this.S = "ciao"; } } } namespace ForumRepros { public static class UrlValidator { /// <summary> /// Validates an optional deviceclass. /// </summary> /// <returns><c>null</c> if no deviceclass is specified, otherwise the deviceclass.</returns> /// <exception cref="WebFaultException{String}">Bad request.</exception> [ClousotRegressionTest] public static byte? ValidateDeviceClass(string deviceclass) { var result = ValidateDeviceClassInternal(deviceclass); byte dummy; //Contract.Assert(byte.TryParse(deviceclass, out dummy)); return result; } /// <summary>Validates the deviceclass.</summary> /// <param name="deviceClass">The deviceclass.</param> /// <returns>The validated deviceclass.</returns> /// <exception cref="WebFaultException{String}">Bad request.</exception> [ClousotRegressionTest] public static byte ValidateDeviceClassInternal(string deviceClass) { byte dc; if (!byte.TryParse(deviceClass, out dc)) { throw new Exception(); } return dc; } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; using System.Configuration; using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace Northwind.CSLA.Library { public delegate void EmployeeInfoEvent(object sender); /// <summary> /// EmployeeInfo Generated by MyGeneration using the CSLA Object Mapping template /// </summary> [Serializable()] [TypeConverter(typeof(EmployeeInfoConverter))] public partial class EmployeeInfo : ReadOnlyBase<EmployeeInfo>, IDisposable { public event EmployeeInfoEvent Changed; private void OnChange() { if (Changed != null) Changed(this); } #region Collection protected static List<EmployeeInfo> _AllList = new List<EmployeeInfo>(); private static Dictionary<string, EmployeeInfo> _AllByPrimaryKey = new Dictionary<string, EmployeeInfo>(); private static void ConvertListToDictionary() { List<EmployeeInfo> remove = new List<EmployeeInfo>(); foreach (EmployeeInfo tmp in _AllList) { _AllByPrimaryKey[tmp.EmployeeID.ToString()]=tmp; // Primary Key remove.Add(tmp); } foreach (EmployeeInfo tmp in remove) _AllList.Remove(tmp); } internal static void AddList(EmployeeInfoList lst) { foreach (EmployeeInfo item in lst) _AllList.Add(item); } public static EmployeeInfo GetExistingByPrimaryKey(int employeeID) { ConvertListToDictionary(); string key = employeeID.ToString(); if (_AllByPrimaryKey.ContainsKey(key)) return _AllByPrimaryKey[key]; return null; } #endregion #region Business Methods private string _ErrorMessage = string.Empty; public string ErrorMessage { get { return _ErrorMessage; } } protected Employee _Editable; private IVEHasBrokenRules HasBrokenRules { get { IVEHasBrokenRules hasBrokenRules = null; if (_Editable != null) hasBrokenRules = _Editable.HasBrokenRules; return hasBrokenRules; } } private int _EmployeeID; [System.ComponentModel.DataObjectField(true, true)] public int EmployeeID { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _EmployeeID; } } private string _LastName = string.Empty; public string LastName { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _LastName; } } private string _FirstName = string.Empty; public string FirstName { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _FirstName; } } private string _Title = string.Empty; public string Title { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _Title; } } private string _TitleOfCourtesy = string.Empty; public string TitleOfCourtesy { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _TitleOfCourtesy; } } private string _BirthDate = string.Empty; public string BirthDate { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _BirthDate; } } private string _HireDate = string.Empty; public string HireDate { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _HireDate; } } private string _Address = string.Empty; public string Address { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _Address; } } private string _City = string.Empty; public string City { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _City; } } private string _Region = string.Empty; public string Region { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _Region; } } private string _PostalCode = string.Empty; public string PostalCode { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _PostalCode; } } private string _Country = string.Empty; public string Country { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _Country; } } private string _HomePhone = string.Empty; public string HomePhone { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _HomePhone; } } private string _Extension = string.Empty; public string Extension { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _Extension; } } private byte[] _Photo; public byte[] Photo { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _Photo; } } private string _Notes = string.Empty; public string Notes { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _Notes; } } private int? _ReportsTo; public int? ReportsTo { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); if (_MyParent != null) _ReportsTo = _MyParent.EmployeeID; return _ReportsTo; } } private EmployeeInfo _MyParent; public EmployeeInfo MyParent { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); if (_MyParent == null && _ReportsTo != null) _MyParent = EmployeeInfo.Get((int)_ReportsTo); return _MyParent; } } private string _PhotoPath = string.Empty; public string PhotoPath { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _PhotoPath; } } private int _ChildEmployeeCount = 0; /// <summary> /// Count of ChildEmployees for this Employee /// </summary> public int ChildEmployeeCount { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _ChildEmployeeCount; } } private EmployeeInfoList _ChildEmployees = null; [TypeConverter(typeof(EmployeeInfoListConverter))] public EmployeeInfoList ChildEmployees { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); if (_ChildEmployeeCount > 0 && _ChildEmployees == null) _ChildEmployees = EmployeeInfoList.GetChildren(_EmployeeID); return _ChildEmployees; } } private int _EmployeeEmployeeTerritoryCount = 0; /// <summary> /// Count of EmployeeEmployeeTerritories for this Employee /// </summary> public int EmployeeEmployeeTerritoryCount { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _EmployeeEmployeeTerritoryCount; } } private EmployeeTerritoryInfoList _EmployeeEmployeeTerritories = null; [TypeConverter(typeof(EmployeeTerritoryInfoListConverter))] public EmployeeTerritoryInfoList EmployeeEmployeeTerritories { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); if (_EmployeeEmployeeTerritoryCount > 0 && _EmployeeEmployeeTerritories == null) _EmployeeEmployeeTerritories = EmployeeTerritoryInfoList.GetByEmployeeID(_EmployeeID); return _EmployeeEmployeeTerritories; } } private int _EmployeeOrderCount = 0; /// <summary> /// Count of EmployeeOrders for this Employee /// </summary> public int EmployeeOrderCount { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _EmployeeOrderCount; } } private OrderInfoList _EmployeeOrders = null; [TypeConverter(typeof(OrderInfoListConverter))] public OrderInfoList EmployeeOrders { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); if (_EmployeeOrderCount > 0 && _EmployeeOrders == null) _EmployeeOrders = OrderInfoList.GetByEmployeeID(_EmployeeID); return _EmployeeOrders; } } // TODO: Replace base EmployeeInfo.ToString function as necessary /// <summary> /// Overrides Base ToString /// </summary> /// <returns>A string representation of current EmployeeInfo</returns> //public override string ToString() //{ // return base.ToString(); //} // TODO: Check EmployeeInfo.GetIdValue to assure that the ID returned is unique /// <summary> /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// </summary> /// <returns>A Unique ID for the current EmployeeInfo</returns> protected override object GetIdValue() { return _EmployeeID; } #endregion #region Factory Methods private EmployeeInfo() {/* require use of factory methods */ _AllList.Add(this); } public void Dispose() { _AllList.Remove(this); _AllByPrimaryKey.Remove(EmployeeID.ToString()); } public virtual Employee Get() { return _Editable = Employee.Get(_EmployeeID); } public static void Refresh(Employee tmp) { EmployeeInfo tmpInfo = GetExistingByPrimaryKey(tmp.EmployeeID); if (tmpInfo == null) return; tmpInfo.RefreshFields(tmp); } private void RefreshFields(Employee tmp) { _LastName = tmp.LastName; _FirstName = tmp.FirstName; _Title = tmp.Title; _TitleOfCourtesy = tmp.TitleOfCourtesy; _BirthDate = tmp.BirthDate; _HireDate = tmp.HireDate; _Address = tmp.Address; _City = tmp.City; _Region = tmp.Region; _PostalCode = tmp.PostalCode; _Country = tmp.Country; _HomePhone = tmp.HomePhone; _Extension = tmp.Extension; _Photo = tmp.Photo; _Notes = tmp.Notes; _ReportsTo = tmp.ReportsTo; _PhotoPath = tmp.PhotoPath; _EmployeeInfoExtension.Refresh(this); _MyParent = null; OnChange();// raise an event } public static EmployeeInfo Get(int employeeID) { //if (!CanGetObject()) // throw new System.Security.SecurityException("User not authorized to view a Employee"); try { EmployeeInfo tmp = GetExistingByPrimaryKey(employeeID); if (tmp == null) { tmp = DataPortal.Fetch<EmployeeInfo>(new PKCriteria(employeeID)); _AllList.Add(tmp); } if (tmp.ErrorMessage == "No Record Found") tmp = null; return tmp; } catch (Exception ex) { throw new DbCslaException("Error on EmployeeInfo.Get", ex); } } #endregion #region Data Access Portal internal EmployeeInfo(SafeDataReader dr) { Database.LogInfo("EmployeeInfo.Constructor", GetHashCode()); try { ReadData(dr); } catch (Exception ex) { Database.LogException("EmployeeInfo.Constructor", ex); throw new DbCslaException("EmployeeInfo.Constructor", ex); } } [Serializable()] protected class PKCriteria { private int _EmployeeID; public int EmployeeID { get { return _EmployeeID; } } public PKCriteria(int employeeID) { _EmployeeID = employeeID; } } private void ReadData(SafeDataReader dr) { Database.LogInfo("EmployeeInfo.ReadData", GetHashCode()); try { _EmployeeID = dr.GetInt32("EmployeeID"); _LastName = dr.GetString("LastName"); _FirstName = dr.GetString("FirstName"); _Title = dr.GetString("Title"); _TitleOfCourtesy = dr.GetString("TitleOfCourtesy"); _BirthDate = dr.GetSmartDate("BirthDate").Text; _HireDate = dr.GetSmartDate("HireDate").Text; _Address = dr.GetString("Address"); _City = dr.GetString("City"); _Region = dr.GetString("Region"); _PostalCode = dr.GetString("PostalCode"); _Country = dr.GetString("Country"); _HomePhone = dr.GetString("HomePhone"); _Extension = dr.GetString("Extension"); _Photo = (byte[])dr.GetValue("Photo"); _Notes = dr.GetString("Notes"); _ReportsTo = (int?)dr.GetValue("ReportsTo"); _PhotoPath = dr.GetString("PhotoPath"); _ChildEmployeeCount = dr.GetInt32("ChildCount"); _EmployeeEmployeeTerritoryCount = dr.GetInt32("EmployeeTerritoryCount"); _EmployeeOrderCount = dr.GetInt32("OrderCount"); } catch (Exception ex) { Database.LogException("EmployeeInfo.ReadData", ex); _ErrorMessage = ex.Message; throw new DbCslaException("EmployeeInfo.ReadData", ex); } } private void DataPortal_Fetch(PKCriteria criteria) { Database.LogInfo("EmployeeInfo.DataPortal_Fetch", GetHashCode()); try { using (SqlConnection cn = Database.Northwind_SqlConnection) { ApplicationContext.LocalContext["cn"] = cn; using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "getEmployee"; cm.Parameters.AddWithValue("@EmployeeID", criteria.EmployeeID); using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { if (!dr.Read()) { _ErrorMessage = "No Record Found"; return; } ReadData(dr); } } // removing of item only needed for local data portal if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Client) ApplicationContext.LocalContext.Remove("cn"); } } catch (Exception ex) { Database.LogException("EmployeeInfo.DataPortal_Fetch", ex); _ErrorMessage = ex.Message; throw new DbCslaException("EmployeeInfo.DataPortal_Fetch", ex); } } #endregion // Standard Refresh #region extension EmployeeInfoExtension _EmployeeInfoExtension = new EmployeeInfoExtension(); [Serializable()] partial class EmployeeInfoExtension : extensionBase {} [Serializable()] class extensionBase { // Default Refresh public virtual void Refresh(EmployeeInfo tmp) { } } #endregion } // Class #region Converter internal class EmployeeInfoConverter : ExpandableObjectConverter { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { if (destType == typeof(string) && value is EmployeeInfo) { // Return the ToString value return ((EmployeeInfo)value).ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.Windows; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Microsoft.Practices.Prism.Regions; using Microsoft.Practices.Prism.Regions.Behaviors; using Microsoft.Practices.Prism.Composition.Tests.Mocks; namespace Microsoft.Practices.Prism.Composition.Tests.Regions.Behaviors { [TestClass] public class RegionActiveAwareBehaviorFixture { [TestMethod] public void SetsIsActivePropertyOnIActiveAwareObjects() { var region = new MockPresentationRegion(); region.RegionManager = new MockRegionManager(); var behavior = new RegionActiveAwareBehavior { Region = region }; behavior.Attach(); var collection = region.MockActiveViews.Items; ActiveAwareFrameworkElement activeAwareObject = new ActiveAwareFrameworkElement(); Assert.IsFalse(activeAwareObject.IsActive); collection.Add(activeAwareObject); Assert.IsTrue(activeAwareObject.IsActive); collection.Remove(activeAwareObject); Assert.IsFalse(activeAwareObject.IsActive); } [TestMethod] public void SetsIsActivePropertyOnIActiveAwareDataContexts() { var region = new MockPresentationRegion(); var behavior = new RegionActiveAwareBehavior { Region = region }; behavior.Attach(); var collection = region.MockActiveViews.Items; ActiveAwareFrameworkElement activeAwareObject = new ActiveAwareFrameworkElement(); var frameworkElementMock = new Mock<FrameworkElement>(); var frameworkElement = frameworkElementMock.Object; frameworkElement.DataContext = activeAwareObject; Assert.IsFalse(activeAwareObject.IsActive); collection.Add(frameworkElement); Assert.IsTrue(activeAwareObject.IsActive); collection.Remove(frameworkElement); Assert.IsFalse(activeAwareObject.IsActive); } [TestMethod] public void SetsIsActivePropertyOnBothIActiveAwareViewAndDataContext() { var region = new MockPresentationRegion(); var behavior = new RegionActiveAwareBehavior { Region = region }; behavior.Attach(); var collection = region.MockActiveViews.Items; var activeAwareMock = new Mock<IActiveAware>(); activeAwareMock.SetupProperty(o => o.IsActive); var activeAwareObject = activeAwareMock.Object; var frameworkElementMock = new Mock<FrameworkElement>(); frameworkElementMock.As<IActiveAware>().SetupProperty(o => o.IsActive); var frameworkElement = frameworkElementMock.Object; frameworkElement.DataContext = activeAwareObject; Assert.IsFalse(((IActiveAware)frameworkElement).IsActive); Assert.IsFalse(activeAwareObject.IsActive); collection.Add(frameworkElement); Assert.IsTrue(((IActiveAware)frameworkElement).IsActive); Assert.IsTrue(activeAwareObject.IsActive); collection.Remove(frameworkElement); Assert.IsFalse(((IActiveAware)frameworkElement).IsActive); Assert.IsFalse(activeAwareObject.IsActive); } [TestMethod] public void DetachStopsListeningForChanges() { var region = new MockPresentationRegion(); var behavior = new RegionActiveAwareBehavior { Region = region }; var collection = region.MockActiveViews.Items; behavior.Attach(); behavior.Detach(); ActiveAwareFrameworkElement activeAwareObject = new ActiveAwareFrameworkElement(); collection.Add(activeAwareObject); Assert.IsFalse(activeAwareObject.IsActive); } [TestMethod] public void DoesNotThrowWhenAddingNonActiveAwareObjects() { var region = new MockPresentationRegion(); var behavior = new RegionActiveAwareBehavior { Region = region }; behavior.Attach(); var collection = region.MockActiveViews.Items; collection.Add(new object()); } [TestMethod] public void DoesNotThrowWhenAddingNonActiveAwareDataContexts() { var region = new MockPresentationRegion(); var behavior = new RegionActiveAwareBehavior { Region = region }; behavior.Attach(); var collection = region.MockActiveViews.Items; var frameworkElementMock = new Mock<FrameworkElement>(); var frameworkElement = frameworkElementMock.Object; frameworkElement.DataContext = new object(); collection.Add(frameworkElement); } [TestMethod] public void WhenParentViewGetsActivatedOrDeactivated_ThenChildViewIsNotUpdated() { var scopedRegionManager = new RegionManager(); var scopedRegion = new Region { Name = "MyScopedRegion", RegionManager = scopedRegionManager }; scopedRegionManager.Regions.Add(scopedRegion); var behaviorForScopedRegion = new RegionActiveAwareBehavior { Region = scopedRegion }; behaviorForScopedRegion.Attach(); var childActiveAwareView = new ActiveAwareFrameworkElement(); var region = new MockPresentationRegion(); var behavior = new RegionActiveAwareBehavior { Region = region }; behavior.Attach(); var view = new MockFrameworkElement(); region.Add(view); RegionManager.SetRegionManager(view, scopedRegionManager); region.Activate(view); scopedRegion.Add(childActiveAwareView); scopedRegion.Activate(childActiveAwareView); Assert.IsTrue(childActiveAwareView.IsActive); region.Deactivate(view); Assert.IsTrue(childActiveAwareView.IsActive); } [TestMethod] public void WhenParentViewGetsActivatedOrDeactivated_ThenSyncedChildViewIsUpdated() { var scopedRegionManager = new RegionManager(); var scopedRegion = new Region { Name = "MyScopedRegion", RegionManager = scopedRegionManager }; scopedRegionManager.Regions.Add(scopedRegion); var behaviorForScopedRegion = new RegionActiveAwareBehavior { Region = scopedRegion }; behaviorForScopedRegion.Attach(); var childActiveAwareView = new SyncedActiveAwareObject(); var region = new MockPresentationRegion(); var behavior = new RegionActiveAwareBehavior { Region = region }; behavior.Attach(); var view = new MockFrameworkElement(); region.Add(view); RegionManager.SetRegionManager(view, scopedRegionManager); region.Activate(view); scopedRegion.Add(childActiveAwareView); scopedRegion.Activate(childActiveAwareView); Assert.IsTrue(childActiveAwareView.IsActive); region.Deactivate(view); Assert.IsFalse(childActiveAwareView.IsActive); } [TestMethod] public void WhenParentViewGetsActivatedOrDeactivated_ThenSyncedChildViewWithAttributeInVMIsUpdated() { var scopedRegionManager = new RegionManager(); var scopedRegion = new Region { Name = "MyScopedRegion", RegionManager = scopedRegionManager }; scopedRegionManager.Regions.Add(scopedRegion); var behaviorForScopedRegion = new RegionActiveAwareBehavior { Region = scopedRegion }; behaviorForScopedRegion.Attach(); var childActiveAwareView = new ActiveAwareFrameworkElement(); childActiveAwareView.DataContext = new SyncedActiveAwareObjectViewModel(); var region = new MockPresentationRegion(); var behavior = new RegionActiveAwareBehavior { Region = region }; behavior.Attach(); var view = new MockFrameworkElement(); region.Add(view); RegionManager.SetRegionManager(view, scopedRegionManager); region.Activate(view); scopedRegion.Add(childActiveAwareView); scopedRegion.Activate(childActiveAwareView); Assert.IsTrue(childActiveAwareView.IsActive); region.Deactivate(view); Assert.IsFalse(childActiveAwareView.IsActive); } [TestMethod] public void WhenParentViewGetsActivatedOrDeactivated_ThenSyncedChildViewModelThatIsNotAFrameworkElementIsNotUpdated() { var scopedRegionManager = new RegionManager(); var scopedRegion = new Region { Name = "MyScopedRegion", RegionManager = scopedRegionManager }; scopedRegionManager.Regions.Add(scopedRegion); var behaviorForScopedRegion = new RegionActiveAwareBehavior { Region = scopedRegion }; behaviorForScopedRegion.Attach(); var childActiveAwareView = new ActiveAwareObject(); var region = new MockPresentationRegion(); var behavior = new RegionActiveAwareBehavior { Region = region }; behavior.Attach(); var view = new MockFrameworkElement(); region.Add(view); RegionManager.SetRegionManager(view, scopedRegionManager); region.Activate(view); scopedRegion.Add(childActiveAwareView); scopedRegion.Activate(childActiveAwareView); Assert.IsTrue(childActiveAwareView.IsActive); region.Deactivate(view); Assert.IsTrue(childActiveAwareView.IsActive); } [TestMethod] public void WhenParentViewGetsActivatedOrDeactivated_ThenSyncedChildViewNotInActiveViewsIsNotUpdated() { var scopedRegionManager = new RegionManager(); var scopedRegion = new Region { Name="MyScopedRegion", RegionManager = scopedRegionManager }; scopedRegionManager.Regions.Add(scopedRegion); var behaviorForScopedRegion = new RegionActiveAwareBehavior { Region = scopedRegion }; behaviorForScopedRegion.Attach(); var childActiveAwareView = new SyncedActiveAwareObject(); var region = new MockPresentationRegion(); var behavior = new RegionActiveAwareBehavior { Region = region }; behavior.Attach(); var view = new MockFrameworkElement(); region.Add(view); RegionManager.SetRegionManager(view, scopedRegionManager); region.Activate(view); scopedRegion.Add(childActiveAwareView); scopedRegion.Deactivate(childActiveAwareView); Assert.IsFalse(childActiveAwareView.IsActive); region.Deactivate(view); Assert.IsFalse(childActiveAwareView.IsActive); region.Activate(view); Assert.IsFalse(childActiveAwareView.IsActive); } [TestMethod] public void WhenParentViewWithoutScopedRegionGetsActivatedOrDeactivated_ThenSyncedChildViewIsNotUpdated() { var commonRegionManager = new RegionManager(); var nonScopedRegion = new Region { Name="MyRegion", RegionManager = commonRegionManager }; commonRegionManager.Regions.Add(nonScopedRegion); var behaviorForScopedRegion = new RegionActiveAwareBehavior { Region = nonScopedRegion }; behaviorForScopedRegion.Attach(); var childActiveAwareView = new SyncedActiveAwareObject(); var region = new MockPresentationRegion { RegionManager = commonRegionManager }; var behavior = new RegionActiveAwareBehavior { Region = region }; behavior.Attach(); var view = new MockFrameworkElement(); region.Add(view); RegionManager.SetRegionManager(view, commonRegionManager); region.Activate(view); nonScopedRegion.Add(childActiveAwareView); nonScopedRegion.Activate(childActiveAwareView); Assert.IsTrue(childActiveAwareView.IsActive); region.Deactivate(view); Assert.IsTrue(childActiveAwareView.IsActive); } class ActiveAwareObject : IActiveAware { public bool IsActive { get; set; } public event EventHandler IsActiveChanged; } class ActiveAwareFrameworkElement : FrameworkElement, IActiveAware { public bool IsActive { get; set; } public event EventHandler IsActiveChanged; } [SyncActiveState] class SyncedActiveAwareObject : IActiveAware { public bool IsActive { get; set; } public event EventHandler IsActiveChanged; } [SyncActiveState] class SyncedActiveAwareObjectViewModel : IActiveAware { public bool IsActive { get; set; } public event EventHandler IsActiveChanged; } } }
using System; using System.Diagnostics; using System.IO; using System.Net.Sockets; using NUnit.Framework; using InTheHand.Net.Sockets; using System.Threading; using InTheHand.SystemCore; namespace InTheHand.Net.Tests.Widcomm { [TestFixture] public class WidcommCommsReadTimeoutTests : WidcommCommsTimeoutTests { public WidcommCommsReadTimeoutTests() : base(StreamOpTest.Read) { } // EoF in Read, 10057 in Write?? protected override IAsyncResult BeginTimedRead_APreviousOpTimedOut(Stream stream) { return base.BeginTimedRead_NoError(stream); } } [TestFixture] public class WidcommCommsWriteTimeoutTests : WidcommCommsTimeoutTests { public WidcommCommsWriteTimeoutTests() : base(StreamOpTest.Write) { } // EoF in Read, 10057 in Write?? protected override IAsyncResult BeginTimedRead_APreviousOpTimedOut(Stream stream) { return base.BeginTimedRead_(stream, true, WSAENOTCONN); } } public abstract class WidcommCommsTimeoutTests : NetworkStreamTimeoutTests { public WidcommCommsTimeoutTests(StreamOpTest testType) : base(testType) { } //---- internal void Create_ConnectedBluetoothClient(out TestRfCommIf rfcommIf, out TestRfcommPort port, out BluetoothClient cli, out Stream strm2) { WidcommBluetoothClientCommsTest.Create_ConnectedBluetoothClient( out rfcommIf, out port, out cli, out strm2); } protected override void Create(out Stream peer, out ISocketPortBuffers socketBuffer) { TestRfCommIf iface; BluetoothClient cli; Stream tmpStrm2; TestRfcommPort port; WidcommBluetoothClientCommsTest.Create_ConnectedBluetoothClient(out iface, out port, out cli, out tmpStrm2); peer = cli.GetStream(); socketBuffer = new WidcommPortBuffers(port); // Start of with no capacity for write. socketBuffer.AllowWrite(0); } class WidcommPortBuffers : ISocketPortBuffers { TestRfcommPort _port; public WidcommPortBuffers(TestRfcommPort port) { _port = port; } void ISocketPortBuffers.NewReceive(byte[] data) { _port.NewReceive(data); } void ISocketPortBuffers.AllowWrite(byte[] data) { ((ISocketPortBuffers)this).AllowWrite(checked((ushort)data.Length)); } void ISocketPortBuffers.AllowWrite(ushort len) { _port.SetWriteResult(len); // In case there's any writers already pending we need to release them. _port.NewEvent(InTheHand.Net.Bluetooth.Widcomm.PORT_EV.TXEMPTY); } void IDisposable.Dispose() { ushort? remaining = _port.GetWriteCapacity(); Assert.AreEqual(0, remaining, "remaining"); } } } public abstract class NetworkStreamTimeoutTests { public enum StreamOpTest { Read, Write } public const int WSAETIMEDOUT = 10060; public const int WSAENOTCONN = 10057; public const int WSAEWOULDBLOCK = 10035; // const int FudgeShorter = 3; const int FudgeLonger = 20; // static byte[] buf1 = new byte[1]; // Converter<Stream, int> _theStreamOperation; Converter<Stream, IAsyncResult> _theBeginVersionOfTheStreamOperation; delegate void Action<T1, T2>(T1 p1, T2 p2); Action<ISocketPortBuffers, byte[]> _theReleaseOperation; System.Reflection.PropertyInfo _setTimeoutPi; //-------- public NetworkStreamTimeoutTests(StreamOpTest testType) { if (testType == StreamOpTest.Write) { _theStreamOperation = TheWriteOperationUnderTest; _theBeginVersionOfTheStreamOperation = TheBeginVersionOfTheWriteOperation; _theReleaseOperation = ReleaseWriteOperation; _setTimeoutPi = typeof(Stream).GetProperty("WriteTimeout"); } else { _theStreamOperation = TheReadOperationUnderTest; _theBeginVersionOfTheStreamOperation = TheBeginVersionOfTheReadOperation; _theReleaseOperation = ReleaseReadOperation; _setTimeoutPi = typeof(Stream).GetProperty("ReadTimeout"); } } //-------- void SetTimeoutValue(Stream strm, int timeout) { _setTimeoutPi.SetValue(strm, timeout, null); } int GetTimeoutValue(Stream strm) { object v = _setTimeoutPi.GetValue(strm, null); int value = (int)v; return value; } //-- protected static int TheReadOperationUnderTest(Stream strm) { int readLen = strm.Read(buf1, 0, buf1.Length); return readLen; } protected static IAsyncResult TheBeginVersionOfTheReadOperation(Stream strm) { IAsyncResult ar = strm.BeginRead(buf1, 0, buf1.Length, null, null); return ar; } protected static void ReleaseReadOperation(ISocketPortBuffers port, byte[] data) { port.NewReceive(data); } //-- protected static int TheWriteOperationUnderTest(Stream strm) { strm.Write(buf1, 0, buf1.Length); return 1; } protected static IAsyncResult TheBeginVersionOfTheWriteOperation(Stream strm) { IAsyncResult ar = strm.BeginWrite(buf1, 0, buf1.Length, null, null); return ar; } protected static void ReleaseWriteOperation(ISocketPortBuffers port, byte[] data) { port.AllowWrite(data); } //-------- protected void Create(out Stream peer) { ISocketPortBuffers port; Create(out peer, out port); } abstract protected void Create(out Stream peer, out ISocketPortBuffers socketBuffer); /// <summary> /// So we can have the RfcommPort/Socket receive more data (TODO , and allow write of some data). /// </summary> public interface ISocketPortBuffers : IDisposable { void NewReceive(byte[] data); void AllowWrite(ushort len); void AllowWrite(byte[] data); } //-------- const int FiftyMsec = 50; const int TwoHundredMsec = 200; private void Read_FiveTimesOne_NoneTimeout(Stream peer) { Stopwatch timer = new Stopwatch(); int readLen; for (int i = 0; i < 5; ++i) { timer.Reset(); timer.Start(); try { readLen = _theStreamOperation(peer); timer.Stop(); Assert.AreEqual(1, readLen, "readLen"); } catch (IOException ioex) { timer.Stop(); Assert.Fail("should NOT have thrown -- #" + i); SocketException sex = (SocketException)ioex.InnerException; //no NETCF: Assert.AreEqual(SocketError.TimedOut, sex.SocketErrorCode); Assert.AreEqual(WSAETIMEDOUT, sex.ErrorCode, "ErrorCode -- #" + i); } timer.Stop(); Between(timer, 0, FiftyMsec / 2, "Between -- #" + i); }//for } private void Read_WillTimeout(Stream peer, int expectedTimeout) { int readLen; Stopwatch timer = new Stopwatch(); // Assert.IsTrue(peer.CanRead, "canread 0"); Assert.IsTrue(peer.CanWrite, "canwrite 0"); // timer.Reset(); timer.Start(); try { readLen = _theStreamOperation(peer); timer.Stop(); Assert.Fail("should have thrown"); } catch (IOException ioex) { timer.Stop(); SocketException sex = (SocketException)ioex.InnerException; //no NETCF: Assert.AreEqual(SocketError.TimedOut, sex.SocketErrorCode); Assert.AreEqual(WSAETIMEDOUT, sex.ErrorCode, "ErrorCode"); } Between(timer, expectedTimeout - FudgeShorter, FudgeLonger + expectedTimeout, "Between"); // SetTimeoutValue(peer, -1); // readLen = -1; timer.Reset(); timer.Start(); //try { readLen = peer.Read(buf1, 0, buf1.Length); timer.Stop(); Assert.AreEqual(0, readLen); //} catch (IOException ioex) { // SOCKETS throws a WSAEWOULDBLOCK here! // timer.Stop(); // SocketException sex = (SocketException)ioex.InnerException; // //no NETCF: Assert.AreEqual(SocketError.TimedOut, sex.SocketErrorCode); // Assert.AreEqual(WSAEWOULDBLOCK, sex.ErrorCode, "ErrorCode"); //} Assert.Less(timer.ElapsedMilliseconds, 20.0); Assert.IsTrue(peer.CanRead, "canread aR"); Assert.IsTrue(peer.CanWrite, "canwrite aR"); // timer.Reset(); timer.Start(); try { peer.Write(buf1, 0, buf1.Length); timer.Stop(); Assert.Fail("should have thrown"); } catch (IOException ioex) { timer.Stop(); SocketException sex = (SocketException)ioex.InnerException; //no NETCF: Assert.AreEqual(SocketError.TimedOut, sex.SocketErrorCode); Assert.AreEqual(WSAENOTCONN, sex.ErrorCode, "ErrorCode"); } Assert.Less(timer.ElapsedMilliseconds, 20.0); Assert.IsFalse(peer.CanRead, "canread aW"); Assert.IsFalse(peer.CanWrite, "canwrite aW"); // readLen = -1; timer.Reset(); timer.Start(); try { readLen = peer.Read(buf1, 0, buf1.Length); timer.Stop(); Assert.AreEqual(0, readLen); Assert.Fail("should have thrown"); } catch (IOException ioex) { timer.Stop(); SocketException sex = (SocketException)ioex.InnerException; //no NETCF: Assert.AreEqual(SocketError.TimedOut, sex.SocketErrorCode); Assert.AreEqual(WSAENOTCONN, sex.ErrorCode, "ErrorCode"); } Assert.Less(timer.ElapsedMilliseconds, 20.0); Assert.IsFalse(peer.CanRead, "canread aR2"); Assert.IsFalse(peer.CanWrite, "canwrite aR2"); } private void Read_FiveTimesOne_AllTimeoutXX(Stream peer, int expectedTimeout) { int readLen; Stopwatch timer = new Stopwatch(); // for (int i = 0; i < 5; ++i) { timer.Reset(); timer.Start(); try { readLen = _theStreamOperation(peer); timer.Stop(); #if PLAY_CLOSED_AFTER_FIRST_TIMEOUT if (readLen == 0) { break; /*for*/ } #endif Assert.Fail("should have thrown -- #" + i); } catch (IOException ioex) { timer.Stop(); SocketException sex = (SocketException)ioex.InnerException; //no NETCF: Assert.AreEqual(SocketError.TimedOut, sex.SocketErrorCode); Assert.AreEqual(WSAETIMEDOUT, sex.ErrorCode, "ErrorCode -- #" + i); } #if PLAY_CLOSED_AFTER_FIRST_TIMEOUT //!! Assert.Less(i, 2); //!! #endif Between(timer, expectedTimeout - FudgeShorter, FudgeLonger + expectedTimeout, "Between -- #" + i); }//for } [Test] public void Read_Timeout50() { Stream peer; ISocketPortBuffers port; Create(out peer, out port); SetTimeoutValue(peer, FiftyMsec); // Read_WillTimeout(peer, FiftyMsec); peer.Close(); port.Dispose(); } [Test, Category("Slow")] public void Read_Timeout200() { Stream peer; ISocketPortBuffers port; Create(out peer, out port); SetTimeoutValue(peer, TwoHundredMsec); // Read_WillTimeout(peer, TwoHundredMsec); peer.Close(); // port.Dispose(); } [Test] public void Read_DataWasThere() { ISocketPortBuffers port; Stream peer; Create(out peer, out port); Assert.AreEqual(System.Threading.Timeout.Infinite, GetTimeoutValue(peer)); //Assert.AreEqual(System.Threading.Timeout.Infinite, peer.WriteTimeout); SetTimeoutValue(peer, FiftyMsec); Assert.AreEqual(FiftyMsec, GetTimeoutValue(peer)); //Assert.AreEqual(System.Threading.Timeout.Infinite, peer.WriteTimeout); // _theReleaseOperation(port, new byte[5]); // Read_FiveTimesOne_NoneTimeout(peer); // Read_WillTimeout(peer, FiftyMsec); // peer.Close(); port.Dispose(); } [Test] public void Read_DataArrivesBeforeExpiry() { ISocketPortBuffers port; Stream peer; Create(out peer, out port); SetTimeoutValue(peer, FiftyMsec); // IAsyncResult arBR = BeginTimedRead_NoError(peer); // Thread.Sleep(30); _theReleaseOperation(port, new byte[1]); Thread.Sleep(20); Assert.IsTrue(arBR.IsCompleted, "b"); int time = EndTimedRead(arBR); Between(time, 30 - FudgeShorter, 50, "TR"); // port.Dispose(); } [Test] public void Read_BlockedByEarlierAsyncOp() { ISocketPortBuffers port; Stream peer; Create(out peer, out port); SetTimeoutValue(peer, FiftyMsec); // // Block the blocking read timeout IAsyncResult ar = _theBeginVersionOfTheStreamOperation(peer); // //int x = peer.ReadByte(); IAsyncResult arBR = BeginTimedRead_Timesout(peer); Thread.Sleep(200); Assert.IsFalse(arBR.IsCompleted, "First async read unexpectedly IS completed"); // _theReleaseOperation(port, new byte[1]); Thread.Sleep(60); Assert.IsTrue(ar.IsCompleted, "First async read not completed"); Assert.IsTrue(arBR.IsCompleted, "Second Read not completed"); int time = EndTimedRead(arBR); Between(time, 200, 200 + 2 * FiftyMsec, "time of Read"); // port.Dispose(); } //-- // Both start at exactly(!) the same time so both should timeout // at the same time and thus both want to complete themselves... // But the first completes all of the ops and so the second can't // complete itself! So originally bang(!!!) with: // "System.InvalidOperationException : Queue empty." [Test] public void TwoWaiting_SameTimeout__hopefully() { ISocketPortBuffers port; Stream peer; Create(out peer, out port); SetTimeoutValue(peer, FiftyMsec); // IAsyncResult arBrAa = BeginTimedRead_Timesout(peer); IAsyncResult arBrBb = BeginTimedRead_APreviousOpTimedOut(peer); // Thread.Sleep(200); Assert.IsTrue(arBrAa.IsCompleted, "aa"); Assert.IsTrue(arBrBb.IsCompleted, "bb"); try { int timeAa = EndTimedRead(arBrAa); } catch (IOException ioex) { AssertTimeoutException(ioex, "aa"); } try { int timeBb = EndTimedRead(arBrBb); // REALLY (for Read) should check the return value is zero (EOF)!! // // Or do we really want to the code to complete all the // operations with TimedOut?.... // Answer: Probably not see the case below: // MultipleOpsWaiting_SecondNotTimesout } catch (IOException ioex) { AssertTimeoutException(ioex, "bb"); } // port.Dispose(); } [Test] public void TwoWaiting_SecondNotTimesout() { ISocketPortBuffers port; Stream peer; Create(out peer, out port); SetTimeoutValue(peer, FiftyMsec); // IAsyncResult arBrAa = BeginTimedRead_Timesout(peer); // So now the second don't timeout and thus is safely completed // by the first and no contention over the completion of it. Thread.Sleep(100); IAsyncResult arBrBb = BeginTimedRead_APreviousOpTimedOut(peer); // Thread.Sleep(500); Assert.IsTrue(arBrAa.IsCompleted, "aa"); Assert.IsTrue(arBrBb.IsCompleted, "bb"); try { int timeAa = EndTimedRead(arBrAa); } catch (IOException ioex) { AssertTimeoutException(ioex, "aa"); } try { int timeBb = EndTimedRead(arBrBb); // REALLY (for Read) should check the return value is zero (EOF)!! // // Or do we really want to the code to complete all the // operations with TimedOut?.... } catch (IOException ioex) { AssertTimeoutException(ioex, "bb"); } //Between(time0, 30 - FudgeShorter, 50, "TR"); // port.Dispose(); } //=================================== //delegate TResult Func<T1, T2, TResult>(T1 p1, T2 p2); protected IAsyncResult BeginTimedRead_(Stream stream, bool expectedToThrow, int? expectedError) { Trace.Assert(expectedError.HasValue == expectedToThrow); Func<Stream, bool, int?, int> dlgt = TimedRead_Runner; Func<int> dlgt0 = delegate { return dlgt(stream, expectedToThrow, expectedError); }; return Delegate2.BeginInvoke(dlgt0, null, dlgt0); } protected IAsyncResult BeginTimedRead_Timesout(Stream stream) { return BeginTimedRead_(stream, true, WSAETIMEDOUT); } protected IAsyncResult BeginTimedRead_NoError(Stream stream) { return BeginTimedRead_(stream, false, null); } // EoF in Read, 10057 in Write?? protected abstract IAsyncResult BeginTimedRead_APreviousOpTimedOut(Stream stream); int EndTimedRead(object ar) { #if false IAsyncResult ar2 = (IAsyncResult)ar; Func<Stream, bool, int> dlgt = (Func<Stream, bool, int>)ar2.AsyncState; int period = dlgt.EndInvoke(ar2); return period; #else IAsyncResult ar2 = (IAsyncResult)ar; //Func<Stream, bool, int> dlgt = (Func<Stream, bool, int>)ar2.AsyncState; //Func<int> dlgt0 = null; Func<int> dlgt0 = (Func<int>)ar2.AsyncState; int period = Delegate2.EndInvoke(dlgt0, ar2); return period; #endif } int TimedRead_Runner(Stream stream, bool expectedToThrow, int? expectedError) { Trace.Assert(expectedError.HasValue == expectedToThrow); Stopwatch timer = new Stopwatch(); try { timer.Start(); int x = _theStreamOperation(stream); timer.Stop(); if (expectedToThrow) { Assert.Fail("should have thrown -- #" + "TimedRead"); } } catch (IOException ioex) { timer.Stop(); if (!expectedToThrow) { Assert.Fail("should NOT have thrown -- #" + "TimedRead"); } SocketException sex = (SocketException)ioex.InnerException; //no NETCF: Assert.AreEqual(SocketError.TimedOut, sex.SocketErrorCode); Assert.AreEqual(expectedError, sex.ErrorCode, "ErrorCode -- #" + "TimedRead"); } return checked((int)timer.ElapsedMilliseconds); } private void AssertTimeoutException(IOException ioex, string name) { SocketException sex = (SocketException)ioex.InnerException; //no NETCF: Assert.AreEqual(SocketError.TimedOut, sex.SocketErrorCode); Assert.AreEqual(WSAETIMEDOUT, sex.ErrorCode, "ErrorCode -- #" + "TimedRead -- " + name); } //-------- public void Between(Stopwatch timer, int min, int max, string message) { Between(checked((int)timer.ElapsedMilliseconds), min, max, message); } public virtual void Between(int value, int min, int max, string message) { Assert.Greater(value, min - 1, "min -- " + message); Assert.Less(value, max + 1, "max -- " + message); } #if NETCF public class Stopwatch { int _start; int _elapsed; public Stopwatch() { } public void Start() { _start = Environment.TickCount; } public void Stop() { int stop = Environment.TickCount; int curElapsed = stop -_start; _elapsed += curElapsed; } public void Reset() { _elapsed = 0; _start = 0; //???? } public long ElapsedMilliseconds { get { return _elapsed; } } } #endif } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Vector.cs" company="Exit Games GmbH"> // Copyright (c) Exit Games GmbH. All rights reserved. // </copyright> // <summary> // Represents a 3D coordinate in the <see cref="IWorld">world</see>. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Photon.SocketServer.Mmo { using System; /// <summary> /// Represents a 3D coordinate in the <see cref = "IWorld">world</see>. /// </summary> public struct Vector : IEquatable<Vector> { #region Properties /// <summary> /// Gets or sets the X value. /// </summary> public int X { get; set; } /// <summary> /// Gets or sets Y value. /// </summary> public int Y { get; set; } /// <summary> /// Gets or sets Z value. /// </summary> public int Z { get; set; } #endregion #region Operators /// <summary> /// Adds on Vector to the other. /// </summary> /// <param name = "a"> /// The a. /// </param> /// <param name = "b"> /// The b. /// </param> /// <returns> /// The sum /// </returns> public static Vector operator +(Vector a, Vector b) { return new Vector { X = a.X + b.X, Y = a.Y + b.Y, Z = a.Z + b.Z }; } /// <summary> /// Devides each value of the vector by a value. /// </summary> /// <param name = "a"> /// The a. /// </param> /// <param name = "b"> /// The b. /// </param> /// <returns> /// A new vector /// </returns> public static Vector operator /(Vector a, int b) { return new Vector { X = a.X / b, Y = a.Y / b, Z = a.Z / b }; } /// <summary> /// Compares to vectors. /// </summary> /// <param name = "coordinate1"> /// The coordinate 1. /// </param> /// <param name = "coordinate2"> /// The coordinate 2. /// </param> /// <returns> /// true if x,y and z of both coordinates are equal /// </returns> public static bool operator ==(Vector coordinate1, Vector coordinate2) { return coordinate1.Equals(coordinate2); } /// <summary> /// Compares to Vectors. /// </summary> /// <param name = "coordinate1"> /// The coordinate 1. /// </param> /// <param name = "coordinate2"> /// The coordinate 2. /// </param> /// <returns> /// true if X, Y or Z of the coorindates are different. /// </returns> public static bool operator !=(Vector coordinate1, Vector coordinate2) { return coordinate1.Equals(coordinate2) == false; } /// <summary> /// Multiples each value of the vector with a value. /// </summary> /// <param name = "a"> /// The a. /// </param> /// <param name = "b"> /// The b. /// </param> /// <returns> /// A new vector /// </returns> public static Vector operator *(Vector a, int b) { return new Vector { X = a.X * b, Y = a.Y * b, Z = a.Z * b }; } /// <summary> /// Substracts one Vector from the other. /// </summary> /// <param name = "a"> /// The a. /// </param> /// <param name = "b"> /// The b. /// </param> /// <returns> /// A new vector /// </returns> public static Vector operator -(Vector a, Vector b) { return new Vector { X = a.X - b.X, Y = a.Y - b.Y, Z = a.Z - b.Z }; } /// <summary> /// Negates a vector /// </summary> /// <param name = "a"> /// The a. /// </param> /// <returns> /// A new Vector /// </returns> public static Vector operator -(Vector a) { return new Vector { X = -a.X, Y = -a.Y, Z = -a.Z }; } #endregion #region Public Methods /// <summary> /// Gets the max values from the input vectors. /// </summary> /// <param name = "value1"> /// The value 1. /// </param> /// <param name = "value2"> /// The value 2. /// </param> /// <returns> /// A new vector. /// </returns> public static Vector Max(Vector value1, Vector value2) { return new Vector { X = Math.Max(value1.X, value2.X), Y = Math.Max(value1.Y, value2.Y), Z = Math.Max(value1.Z, value2.Z) }; } /// <summary> /// Gets the min values from the input vectors. /// </summary> /// <param name = "value1"> /// The value 1. /// </param> /// <param name = "value2"> /// The value 2. /// </param> /// <returns> /// A new vector. /// </returns> public static Vector Min(Vector value1, Vector value2) { return new Vector { X = Math.Min(value1.X, value2.X), Y = Math.Min(value1.Y, value2.Y), Z = Math.Min(value1.Z, value2.Z) }; } /// <summary> /// Compares the Vector to an object. /// </summary> /// <param name = "obj"> /// The object to compare. /// </param> /// <returns> /// true if obj is equal to current instance. /// </returns> public override bool Equals(object obj) { if (obj is Vector) { var other = (Vector)obj; return this.Equals(other); } return false; } /// <summary> /// Calculates the distance to another Vector. /// </summary> /// <param name = "vector"> /// The vector. /// </param> /// <returns> /// The distance. /// </returns> public double GetDistance(Vector vector) { return Math.Sqrt(Math.Pow(vector.X - this.X, 2) + Math.Pow(vector.Y - this.Y, 2) + Math.Pow(vector.Z - this.Z, 2)); } /// <summary> /// Get the hash code. /// </summary> /// <returns> /// XOR from X, Y and Z. /// </returns> public override int GetHashCode() { int result = this.X.GetHashCode(); result ^= this.Y.GetHashCode(); result ^= this.Z.GetHashCode(); return result; } /// <summary> /// Gets Magnitude. /// </summary> /// <returns> /// The magnitude. /// </returns> public double GetMagnitude() { return Math.Sqrt((this.X * this.X) + (this.Y * this.Y) + (this.Z * this.Z)); } /// <summary> /// Build a string showing X, Y and Z. /// </summary> /// <returns> /// string represenation of this vector. /// </returns> public override string ToString() { return string.Format("{0}({1},{2},{3})", base.ToString(), this.X, this.Y, this.Z); } #endregion #region Implemented Interfaces #region IEquatable<Vector> /// <summary> /// Compares X, Y and Z to another vector. /// </summary> /// <param name = "other"> /// The other vector. /// </param> /// <returns> /// True if X, Y and Z equal in both vectors. /// </returns> public bool Equals(Vector other) { return this.X.Equals(other.X) && this.Y.Equals(other.Y) && this.Z.Equals(other.Z); } #endregion #endregion } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace Elasticsearch.Net.Integration.Yaml.ClusterState2 { public partial class ClusterState2YamlTests { public class ClusterState220FilteringYamlBase : YamlTestsBase { public ClusterState220FilteringYamlBase() : base() { //do index _body = new { text= "The quick brown fox is brown." }; this.Do(()=> _client.Index("testidx", "testtype", "testing_document", _body)); //do indices.refresh this.Do(()=> _client.IndicesRefreshForAll()); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class FilteringTheClusterStateByBlocksShouldReturnTheBlocksFieldEvenIfTheResponseIsEmpty2Tests : ClusterState220FilteringYamlBase { [Test] public void FilteringTheClusterStateByBlocksShouldReturnTheBlocksFieldEvenIfTheResponseIsEmpty2Test() { //do cluster.state this.Do(()=> _client.ClusterState("blocks")); //is_true _response.blocks; this.IsTrue(_response.blocks); //is_false _response.nodes; this.IsFalse(_response.nodes); //is_false _response.metadata; this.IsFalse(_response.metadata); //is_false _response.routing_table; this.IsFalse(_response.routing_table); //is_false _response.routing_nodes; this.IsFalse(_response.routing_nodes); //is_false _response.allocations; this.IsFalse(_response.allocations); //length _response.blocks: 0; this.IsLength(_response.blocks, 0); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class FilteringTheClusterStateByBlocksShouldReturnTheBlocks3Tests : ClusterState220FilteringYamlBase { [Test] public void FilteringTheClusterStateByBlocksShouldReturnTheBlocks3Test() { //do indices.put_settings _body = new Dictionary<string, object> { { @"index.blocks.read_only", @"true" } }; this.Do(()=> _client.IndicesPutSettings("testidx", _body)); //do cluster.state this.Do(()=> _client.ClusterState("blocks")); //is_true _response.blocks; this.IsTrue(_response.blocks); //is_false _response.nodes; this.IsFalse(_response.nodes); //is_false _response.metadata; this.IsFalse(_response.metadata); //is_false _response.routing_table; this.IsFalse(_response.routing_table); //is_false _response.routing_nodes; this.IsFalse(_response.routing_nodes); //is_false _response.allocations; this.IsFalse(_response.allocations); //length _response.blocks: 1; this.IsLength(_response.blocks, 1); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class FilteringTheClusterStateByNodesOnlyShouldWork4Tests : ClusterState220FilteringYamlBase { [Test] public void FilteringTheClusterStateByNodesOnlyShouldWork4Test() { //do cluster.state this.Do(()=> _client.ClusterState("nodes")); //is_false _response.blocks; this.IsFalse(_response.blocks); //is_true _response.nodes; this.IsTrue(_response.nodes); //is_false _response.metadata; this.IsFalse(_response.metadata); //is_false _response.routing_table; this.IsFalse(_response.routing_table); //is_false _response.routing_nodes; this.IsFalse(_response.routing_nodes); //is_false _response.allocations; this.IsFalse(_response.allocations); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class FilteringTheClusterStateByMetadataOnlyShouldWork5Tests : ClusterState220FilteringYamlBase { [Test] public void FilteringTheClusterStateByMetadataOnlyShouldWork5Test() { //do cluster.state this.Do(()=> _client.ClusterState("metadata")); //is_false _response.blocks; this.IsFalse(_response.blocks); //is_false _response.nodes; this.IsFalse(_response.nodes); //is_true _response.metadata; this.IsTrue(_response.metadata); //is_false _response.routing_table; this.IsFalse(_response.routing_table); //is_false _response.routing_nodes; this.IsFalse(_response.routing_nodes); //is_false _response.allocations; this.IsFalse(_response.allocations); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class FilteringTheClusterStateByRoutingTableOnlyShouldWork6Tests : ClusterState220FilteringYamlBase { [Test] public void FilteringTheClusterStateByRoutingTableOnlyShouldWork6Test() { //do cluster.state this.Do(()=> _client.ClusterState("routing_table")); //is_false _response.blocks; this.IsFalse(_response.blocks); //is_false _response.nodes; this.IsFalse(_response.nodes); //is_false _response.metadata; this.IsFalse(_response.metadata); //is_true _response.routing_table; this.IsTrue(_response.routing_table); //is_true _response.routing_nodes; this.IsTrue(_response.routing_nodes); //is_true _response.allocations; this.IsTrue(_response.allocations); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class FilteringTheClusterStateForSpecificIndexTemplatesShouldWork7Tests : ClusterState220FilteringYamlBase { [Test] public void FilteringTheClusterStateForSpecificIndexTemplatesShouldWork7Test() { //do indices.put_template _body = new { template= "test-*", settings= new { number_of_shards= "1" } }; this.Do(()=> _client.IndicesPutTemplateForAll("test1", _body)); //do indices.put_template _body = new { template= "test-*", settings= new { number_of_shards= "2" } }; this.Do(()=> _client.IndicesPutTemplateForAll("test2", _body)); //do indices.put_template _body = new { template= "foo-*", settings= new { number_of_shards= "3" } }; this.Do(()=> _client.IndicesPutTemplateForAll("foo", _body)); //do cluster.state this.Do(()=> _client.ClusterState("metadata", nv=>nv .AddQueryString("index_templates", new [] { @"test1", @"test2" }) )); //is_false _response.blocks; this.IsFalse(_response.blocks); //is_false _response.nodes; this.IsFalse(_response.nodes); //is_true _response.metadata; this.IsTrue(_response.metadata); //is_false _response.routing_table; this.IsFalse(_response.routing_table); //is_false _response.routing_nodes; this.IsFalse(_response.routing_nodes); //is_false _response.allocations; this.IsFalse(_response.allocations); //is_true _response.metadata.templates.test1; this.IsTrue(_response.metadata.templates.test1); //is_true _response.metadata.templates.test2; this.IsTrue(_response.metadata.templates.test2); //is_false _response.metadata.templates.foo; this.IsFalse(_response.metadata.templates.foo); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class FilteringTheClusterStateByIndicesShouldWorkInRoutingTableAndMetadata8Tests : ClusterState220FilteringYamlBase { [Test] public void FilteringTheClusterStateByIndicesShouldWorkInRoutingTableAndMetadata8Test() { //do index _body = new { text= "The quick brown fox is brown." }; this.Do(()=> _client.Index("another", "type", "testing_document", _body)); //do indices.refresh this.Do(()=> _client.IndicesRefreshForAll()); //do cluster.state this.Do(()=> _client.ClusterState("routing_table,metadata", "testidx")); //is_false _response.metadata.indices.another; this.IsFalse(_response.metadata.indices.another); //is_false _response.routing_table.indices.another; this.IsFalse(_response.routing_table.indices.another); //is_true _response.metadata.indices.testidx; this.IsTrue(_response.metadata.indices.testidx); //is_true _response.routing_table.indices.testidx; this.IsTrue(_response.routing_table.indices.testidx); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class FilteringTheClusterStateUsingAllForIndicesAndMetricsShouldWork9Tests : ClusterState220FilteringYamlBase { [Test] public void FilteringTheClusterStateUsingAllForIndicesAndMetricsShouldWork9Test() { //do cluster.state this.Do(()=> _client.ClusterState("_all", "_all")); //is_true _response.blocks; this.IsTrue(_response.blocks); //is_true _response.nodes; this.IsTrue(_response.nodes); //is_true _response.metadata; this.IsTrue(_response.metadata); //is_true _response.routing_table; this.IsTrue(_response.routing_table); //is_true _response.routing_nodes; this.IsTrue(_response.routing_nodes); //is_true _response.allocations; this.IsTrue(_response.allocations); } } } }
/******************************************************************************************************* This file was auto generated with the tool "WebIDLParser" Content was generated from IDL file: http://trac.webkit.org/browser/trunk/Source/WebCore/html/canvas/WebGLRenderingContext.idl PLEASE DO *NOT* MODIFY THIS FILE! This file will be overridden next generation. If you need changes: - All classes marked as "partial". Use the custom.cs in the root folder, to extend the classes. - or regenerate the project with the newest IDL files. - or modifiy the WebIDLParser tool itself. ******************************************************************************************************** Copyright (C) 2014 Sebastian Loncar, Web: http://loncar.de Copyright (C) 2009 Apple Inc. All Rights Reserved. MIT License: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *******************************************************************************************************/ using System; namespace SharpKit.Html { using SharpKit.JavaScript; using SharpKit.Html.fileapi; using SharpKit.Html.html.shadow; using SharpKit.Html.html.track; using SharpKit.Html.inspector; using SharpKit.Html.loader.appcache; using SharpKit.Html.battery; using SharpKit.Html.filesystem; using SharpKit.Html.gamepad; using SharpKit.Html.geolocation; using SharpKit.Html.indexeddb; using SharpKit.Html.intents; using SharpKit.Html.mediasource; using SharpKit.Html.mediastream; using SharpKit.Html.navigatorcontentutils; using SharpKit.Html.networkinfo; using SharpKit.Html.notifications; using SharpKit.Html.proximity; using SharpKit.Html.quota; using SharpKit.Html.speech; using SharpKit.Html.vibration; using SharpKit.Html.webaudio; using SharpKit.Html.webdatabase; using SharpKit.Html.plugins; using SharpKit.Html.storage; using SharpKit.Html.svg; using SharpKit.Html.workers; [JsType(JsMode.Prototype, Export = false, PropertiesAsFields = true, NativeCasts = true, Name = "WebGLRenderingContext")] public partial class WebGLRenderingContext : CanvasRenderingContext { public const int DEPTH_BUFFER_BIT = 0x00000100; public const int STENCIL_BUFFER_BIT = 0x00000400; public const int COLOR_BUFFER_BIT = 0x00004000; public const int POINTS = 0x0000; public const int LINES = 0x0001; public const int LINE_LOOP = 0x0002; public const int LINE_STRIP = 0x0003; public const int TRIANGLES = 0x0004; public const int TRIANGLE_STRIP = 0x0005; public const int TRIANGLE_FAN = 0x0006; public const int ZERO = 0; public const int ONE = 1; public const int SRC_COLOR = 0x0300; public const int ONE_MINUS_SRC_COLOR = 0x0301; public const int SRC_ALPHA = 0x0302; public const int ONE_MINUS_SRC_ALPHA = 0x0303; public const int DST_ALPHA = 0x0304; public const int ONE_MINUS_DST_ALPHA = 0x0305; public const int DST_COLOR = 0x0306; public const int ONE_MINUS_DST_COLOR = 0x0307; public const int SRC_ALPHA_SATURATE = 0x0308; public const int FUNC_ADD = 0x8006; public const int BLEND_EQUATION = 0x8009; public const int BLEND_EQUATION_RGB = 0x8009; public const int BLEND_EQUATION_ALPHA = 0x883D; public const int FUNC_SUBTRACT = 0x800A; public const int FUNC_REVERSE_SUBTRACT = 0x800B; public const int BLEND_DST_RGB = 0x80C8; public const int BLEND_SRC_RGB = 0x80C9; public const int BLEND_DST_ALPHA = 0x80CA; public const int BLEND_SRC_ALPHA = 0x80CB; public const int CONSTANT_COLOR = 0x8001; public const int ONE_MINUS_CONSTANT_COLOR = 0x8002; public const int CONSTANT_ALPHA = 0x8003; public const int ONE_MINUS_CONSTANT_ALPHA = 0x8004; public const int BLEND_COLOR = 0x8005; public const int ARRAY_BUFFER = 0x8892; public const int ELEMENT_ARRAY_BUFFER = 0x8893; public const int ARRAY_BUFFER_BINDING = 0x8894; public const int ELEMENT_ARRAY_BUFFER_BINDING = 0x8895; public const int STREAM_DRAW = 0x88E0; public const int STATIC_DRAW = 0x88E4; public const int DYNAMIC_DRAW = 0x88E8; public const int BUFFER_SIZE = 0x8764; public const int BUFFER_USAGE = 0x8765; public const int CURRENT_VERTEX_ATTRIB = 0x8626; public const int FRONT = 0x0404; public const int BACK = 0x0405; public const int FRONT_AND_BACK = 0x0408; public const int TEXTURE_2D = 0x0DE1; public const int CULL_FACE = 0x0B44; public const int BLEND = 0x0BE2; public const int DITHER = 0x0BD0; public const int STENCIL_TEST = 0x0B90; public const int DEPTH_TEST = 0x0B71; public const int SCISSOR_TEST = 0x0C11; public const int POLYGON_OFFSET_FILL = 0x8037; public const int SAMPLE_ALPHA_TO_COVERAGE = 0x809E; public const int SAMPLE_COVERAGE = 0x80A0; public const int NO_ERROR = 0; public const int INVALID_ENUM = 0x0500; public const int INVALID_VALUE = 0x0501; public const int INVALID_OPERATION = 0x0502; public const int OUT_OF_MEMORY = 0x0505; public const int CW = 0x0900; public const int CCW = 0x0901; public const int LINE_WIDTH = 0x0B21; public const int ALIASED_POINT_SIZE_RANGE = 0x846D; public const int ALIASED_LINE_WIDTH_RANGE = 0x846E; public const int CULL_FACE_MODE = 0x0B45; public const int FRONT_FACE = 0x0B46; public const int DEPTH_RANGE = 0x0B70; public const int DEPTH_WRITEMASK = 0x0B72; public const int DEPTH_CLEAR_VALUE = 0x0B73; public const int DEPTH_FUNC = 0x0B74; public const int STENCIL_CLEAR_VALUE = 0x0B91; public const int STENCIL_FUNC = 0x0B92; public const int STENCIL_FAIL = 0x0B94; public const int STENCIL_PASS_DEPTH_FAIL = 0x0B95; public const int STENCIL_PASS_DEPTH_PASS = 0x0B96; public const int STENCIL_REF = 0x0B97; public const int STENCIL_VALUE_MASK = 0x0B93; public const int STENCIL_WRITEMASK = 0x0B98; public const int STENCIL_BACK_FUNC = 0x8800; public const int STENCIL_BACK_FAIL = 0x8801; public const int STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802; public const int STENCIL_BACK_PASS_DEPTH_PASS = 0x8803; public const int STENCIL_BACK_REF = 0x8CA3; public const int STENCIL_BACK_VALUE_MASK = 0x8CA4; public const int STENCIL_BACK_WRITEMASK = 0x8CA5; public const int VIEWPORT = 0x0BA2; public const int SCISSOR_BOX = 0x0C10; public const int COLOR_CLEAR_VALUE = 0x0C22; public const int COLOR_WRITEMASK = 0x0C23; public const int UNPACK_ALIGNMENT = 0x0CF5; public const int PACK_ALIGNMENT = 0x0D05; public const int MAX_TEXTURE_SIZE = 0x0D33; public const int MAX_VIEWPORT_DIMS = 0x0D3A; public const int SUBPIXEL_BITS = 0x0D50; public const int RED_BITS = 0x0D52; public const int GREEN_BITS = 0x0D53; public const int BLUE_BITS = 0x0D54; public const int ALPHA_BITS = 0x0D55; public const int DEPTH_BITS = 0x0D56; public const int STENCIL_BITS = 0x0D57; public const int POLYGON_OFFSET_UNITS = 0x2A00; public const int POLYGON_OFFSET_FACTOR = 0x8038; public const int TEXTURE_BINDING_2D = 0x8069; public const int SAMPLE_BUFFERS = 0x80A8; public const int SAMPLES = 0x80A9; public const int SAMPLE_COVERAGE_VALUE = 0x80AA; public const int SAMPLE_COVERAGE_INVERT = 0x80AB; public const int COMPRESSED_TEXTURE_FORMATS = 0x86A3; public const int DONT_CARE = 0x1100; public const int FASTEST = 0x1101; public const int NICEST = 0x1102; public const int GENERATE_MIPMAP_HINT = 0x8192; public const int BYTE = 0x1400; public const int UNSIGNED_BYTE = 0x1401; public const int SHORT = 0x1402; public const int UNSIGNED_SHORT = 0x1403; public const int INT = 0x1404; public const int UNSIGNED_INT = 0x1405; public const int FLOAT = 0x1406; public const int DEPTH_COMPONENT = 0x1902; public const int ALPHA = 0x1906; public const int RGB = 0x1907; public const int RGBA = 0x1908; public const int LUMINANCE = 0x1909; public const int LUMINANCE_ALPHA = 0x190A; public const int UNSIGNED_SHORT_4_4_4_4 = 0x8033; public const int UNSIGNED_SHORT_5_5_5_1 = 0x8034; public const int UNSIGNED_SHORT_5_6_5 = 0x8363; public const int FRAGMENT_SHADER = 0x8B30; public const int VERTEX_SHADER = 0x8B31; public const int MAX_VERTEX_ATTRIBS = 0x8869; public const int MAX_VERTEX_UNIFORM_VECTORS = 0x8DFB; public const int MAX_VARYING_VECTORS = 0x8DFC; public const int MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8B4D; public const int MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8B4C; public const int MAX_TEXTURE_IMAGE_UNITS = 0x8872; public const int MAX_FRAGMENT_UNIFORM_VECTORS = 0x8DFD; public const int SHADER_TYPE = 0x8B4F; public const int DELETE_STATUS = 0x8B80; public const int LINK_STATUS = 0x8B82; public const int VALIDATE_STATUS = 0x8B83; public const int ATTACHED_SHADERS = 0x8B85; public const int ACTIVE_UNIFORMS = 0x8B86; public const int ACTIVE_ATTRIBUTES = 0x8B89; public const int SHADING_LANGUAGE_VERSION = 0x8B8C; public const int CURRENT_PROGRAM = 0x8B8D; public const int NEVER = 0x0200; public const int LESS = 0x0201; public const int EQUAL = 0x0202; public const int LEQUAL = 0x0203; public const int GREATER = 0x0204; public const int NOTEQUAL = 0x0205; public const int GEQUAL = 0x0206; public const int ALWAYS = 0x0207; public const int KEEP = 0x1E00; public const int REPLACE = 0x1E01; public const int INCR = 0x1E02; public const int DECR = 0x1E03; public const int INVERT = 0x150A; public const int INCR_WRAP = 0x8507; public const int DECR_WRAP = 0x8508; public const int VENDOR = 0x1F00; public const int RENDERER = 0x1F01; public const int VERSION = 0x1F02; public const int NEAREST = 0x2600; public const int LINEAR = 0x2601; public const int NEAREST_MIPMAP_NEAREST = 0x2700; public const int LINEAR_MIPMAP_NEAREST = 0x2701; public const int NEAREST_MIPMAP_LINEAR = 0x2702; public const int LINEAR_MIPMAP_LINEAR = 0x2703; public const int TEXTURE_MAG_FILTER = 0x2800; public const int TEXTURE_MIN_FILTER = 0x2801; public const int TEXTURE_WRAP_S = 0x2802; public const int TEXTURE_WRAP_T = 0x2803; public const int TEXTURE = 0x1702; public const int TEXTURE_CUBE_MAP = 0x8513; public const int TEXTURE_BINDING_CUBE_MAP = 0x8514; public const int TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515; public const int TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516; public const int TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517; public const int TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518; public const int TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519; public const int TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851A; public const int MAX_CUBE_MAP_TEXTURE_SIZE = 0x851C; public const int TEXTURE0 = 0x84C0; public const int TEXTURE1 = 0x84C1; public const int TEXTURE2 = 0x84C2; public const int TEXTURE3 = 0x84C3; public const int TEXTURE4 = 0x84C4; public const int TEXTURE5 = 0x84C5; public const int TEXTURE6 = 0x84C6; public const int TEXTURE7 = 0x84C7; public const int TEXTURE8 = 0x84C8; public const int TEXTURE9 = 0x84C9; public const int TEXTURE10 = 0x84CA; public const int TEXTURE11 = 0x84CB; public const int TEXTURE12 = 0x84CC; public const int TEXTURE13 = 0x84CD; public const int TEXTURE14 = 0x84CE; public const int TEXTURE15 = 0x84CF; public const int TEXTURE16 = 0x84D0; public const int TEXTURE17 = 0x84D1; public const int TEXTURE18 = 0x84D2; public const int TEXTURE19 = 0x84D3; public const int TEXTURE20 = 0x84D4; public const int TEXTURE21 = 0x84D5; public const int TEXTURE22 = 0x84D6; public const int TEXTURE23 = 0x84D7; public const int TEXTURE24 = 0x84D8; public const int TEXTURE25 = 0x84D9; public const int TEXTURE26 = 0x84DA; public const int TEXTURE27 = 0x84DB; public const int TEXTURE28 = 0x84DC; public const int TEXTURE29 = 0x84DD; public const int TEXTURE30 = 0x84DE; public const int TEXTURE31 = 0x84DF; public const int ACTIVE_TEXTURE = 0x84E0; public const int REPEAT = 0x2901; public const int CLAMP_TO_EDGE = 0x812F; public const int MIRRORED_REPEAT = 0x8370; public const int FLOAT_VEC2 = 0x8B50; public const int FLOAT_VEC3 = 0x8B51; public const int FLOAT_VEC4 = 0x8B52; public const int INT_VEC2 = 0x8B53; public const int INT_VEC3 = 0x8B54; public const int INT_VEC4 = 0x8B55; public const int BOOL = 0x8B56; public const int BOOL_VEC2 = 0x8B57; public const int BOOL_VEC3 = 0x8B58; public const int BOOL_VEC4 = 0x8B59; public const int FLOAT_MAT2 = 0x8B5A; public const int FLOAT_MAT3 = 0x8B5B; public const int FLOAT_MAT4 = 0x8B5C; public const int SAMPLER_2D = 0x8B5E; public const int SAMPLER_CUBE = 0x8B60; public const int VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622; public const int VERTEX_ATTRIB_ARRAY_SIZE = 0x8623; public const int VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624; public const int VERTEX_ATTRIB_ARRAY_TYPE = 0x8625; public const int VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886A; public const int VERTEX_ATTRIB_ARRAY_POINTER = 0x8645; public const int VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 0x889F; public const int COMPILE_STATUS = 0x8B81; public const int LOW_FLOAT = 0x8DF0; public const int MEDIUM_FLOAT = 0x8DF1; public const int HIGH_FLOAT = 0x8DF2; public const int LOW_INT = 0x8DF3; public const int MEDIUM_INT = 0x8DF4; public const int HIGH_INT = 0x8DF5; public const int FRAMEBUFFER = 0x8D40; public const int RENDERBUFFER = 0x8D41; public const int RGBA4 = 0x8056; public const int RGB5_A1 = 0x8057; public const int RGB565 = 0x8D62; public const int DEPTH_COMPONENT16 = 0x81A5; public const int STENCIL_INDEX = 0x1901; public const int STENCIL_INDEX8 = 0x8D48; public const int DEPTH_STENCIL = 0x84F9; public const int RENDERBUFFER_WIDTH = 0x8D42; public const int RENDERBUFFER_HEIGHT = 0x8D43; public const int RENDERBUFFER_INTERNAL_FORMAT = 0x8D44; public const int RENDERBUFFER_RED_SIZE = 0x8D50; public const int RENDERBUFFER_GREEN_SIZE = 0x8D51; public const int RENDERBUFFER_BLUE_SIZE = 0x8D52; public const int RENDERBUFFER_ALPHA_SIZE = 0x8D53; public const int RENDERBUFFER_DEPTH_SIZE = 0x8D54; public const int RENDERBUFFER_STENCIL_SIZE = 0x8D55; public const int FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8CD0; public const int FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8CD1; public const int FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 0x8CD2; public const int FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 0x8CD3; public const int COLOR_ATTACHMENT0 = 0x8CE0; public const int DEPTH_ATTACHMENT = 0x8D00; public const int STENCIL_ATTACHMENT = 0x8D20; public const int DEPTH_STENCIL_ATTACHMENT = 0x821A; public const int NONE = 0; public const int FRAMEBUFFER_COMPLETE = 0x8CD5; public const int FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8CD6; public const int FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8CD7; public const int FRAMEBUFFER_INCOMPLETE_DIMENSIONS = 0x8CD9; public const int FRAMEBUFFER_UNSUPPORTED = 0x8CDD; public const int FRAMEBUFFER_BINDING = 0x8CA6; public const int RENDERBUFFER_BINDING = 0x8CA7; public const int MAX_RENDERBUFFER_SIZE = 0x84E8; public const int INVALID_FRAMEBUFFER_OPERATION = 0x0506; public const int UNPACK_FLIP_Y_WEBGL = 0x9240; public const int UNPACK_PREMULTIPLY_ALPHA_WEBGL = 0x9241; public const int CONTEXT_LOST_WEBGL = 0x9242; public const int UNPACK_COLORSPACE_CONVERSION_WEBGL = 0x9243; public const int BROWSER_DEFAULT_WEBGL = 0x9244; public int drawingBufferWidth {get; set; } public int drawingBufferHeight {get; set; } public void activeTexture(int texture) {} public void attachShader(WebGLProgram program, WebGLShader shader) {} public void bindAttribLocation(WebGLProgram program, int index, string name) {} public void bindBuffer(int target, WebGLBuffer buffer) {} public void bindFramebuffer(int target, WebGLFramebuffer framebuffer) {} public void bindRenderbuffer(int target, WebGLRenderbuffer renderbuffer) {} public void bindTexture(int target, WebGLTexture texture) {} public void blendColor(double red, double green, double blue, double alpha) {} public void blendEquation(int mode) {} public void blendEquationSeparate(int modeRGB, int modeAlpha) {} public void blendFunc(int sfactor, int dfactor) {} public void blendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) {} public void bufferData(int target, ArrayBuffer data, int usage) {} public void bufferData(int target, ArrayBufferView data, int usage) {} public void bufferData(int target, int size, int usage) {} public void bufferSubData(int target, int offset, ArrayBuffer data) {} public void bufferSubData(int target, int offset, ArrayBufferView data) {} public int checkFramebufferStatus(int target) { return default(int); } public void clear(int mask) {} public void clearColor(double red, double green, double blue, double alpha) {} public void clearDepth(double depth) {} public void clearStencil(int s) {} public void colorMask(bool red, bool green, bool blue, bool alpha) {} public void compileShader(WebGLShader shader) {} public void compressedTexImage2D(int target, int level, int internalformat, int width, int height, int border, ArrayBufferView data) {} public void compressedTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, ArrayBufferView data) {} public void copyTexImage2D(int target, int level, int internalformat, int x, int y, int width, int height, int border) {} public void copyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, int width, int height) {} public WebGLBuffer createBuffer() { return default(WebGLBuffer); } public WebGLFramebuffer createFramebuffer() { return default(WebGLFramebuffer); } public WebGLProgram createProgram() { return default(WebGLProgram); } public WebGLRenderbuffer createRenderbuffer() { return default(WebGLRenderbuffer); } public WebGLShader createShader(int type) { return default(WebGLShader); } public WebGLTexture createTexture() { return default(WebGLTexture); } public void cullFace(int mode) {} public void deleteBuffer(WebGLBuffer buffer) {} public void deleteFramebuffer(WebGLFramebuffer framebuffer) {} public void deleteProgram(WebGLProgram program) {} public void deleteRenderbuffer(WebGLRenderbuffer renderbuffer) {} public void deleteShader(WebGLShader shader) {} public void deleteTexture(WebGLTexture texture) {} public void depthFunc(int func) {} public void depthMask(bool flag) {} public void depthRange(double zNear, double zFar) {} public void detachShader(WebGLProgram program, WebGLShader shader) {} public void disable(int cap) {} public void disableVertexAttribArray(int index) {} public void drawArrays(int mode, int first, int count) {} public void drawElements(int mode, int count, int type, int offset) {} public void enable(int cap) {} public void enableVertexAttribArray(int index) {} public void finish() {} public void flush() {} public void framebufferRenderbuffer(int target, int attachment, int renderbuffertarget, WebGLRenderbuffer renderbuffer) {} public void framebufferTexture2D(int target, int attachment, int textarget, WebGLTexture texture, int level) {} public void frontFace(int mode) {} public void generateMipmap(int target) {} public WebGLActiveInfo getActiveAttrib(WebGLProgram program, int index) { return default(WebGLActiveInfo); } public WebGLActiveInfo getActiveUniform(WebGLProgram program, int index) { return default(WebGLActiveInfo); } public void getAttachedShaders(WebGLProgram program) {} public int getAttribLocation(WebGLProgram program, string name) { return default(int); } public void getBufferParameter() {} public WebGLContextAttributes getContextAttributes() { return default(WebGLContextAttributes); } public int getError() { return default(int); } public object getExtension(string name) { return default(object); } public void getFramebufferAttachmentParameter() {} public void getParameter() {} public void getProgramParameter() {} public JsString getProgramInfoLog(WebGLProgram program) { return default(JsString); } public void getRenderbufferParameter() {} public void getShaderParameter() {} public JsString getShaderInfoLog(WebGLShader shader) { return default(JsString); } public WebGLShaderPrecisionFormat getShaderPrecisionFormat(int shadertype, int precisiontype) { return default(WebGLShaderPrecisionFormat); } public JsString getShaderSource(WebGLShader shader) { return default(JsString); } public JsString getSupportedExtensions() { return default(JsString); } public void getTexParameter() {} public void getUniform() {} public WebGLUniformLocation getUniformLocation(WebGLProgram program, string name) { return default(WebGLUniformLocation); } public void getVertexAttrib() {} public int getVertexAttribOffset(int index, int pname) { return default(int); } public void hint(int target, int mode) {} public bool isBuffer(WebGLBuffer buffer) { return default(bool); } public bool isContextLost() { return default(bool); } public bool isEnabled(int cap) { return default(bool); } public bool isFramebuffer(WebGLFramebuffer framebuffer) { return default(bool); } public bool isProgram(WebGLProgram program) { return default(bool); } public bool isRenderbuffer(WebGLRenderbuffer renderbuffer) { return default(bool); } public bool isShader(WebGLShader shader) { return default(bool); } public bool isTexture(WebGLTexture texture) { return default(bool); } public void lineWidth(double width) {} public void linkProgram(WebGLProgram program) {} public void pixelStorei(int pname, int param) {} public void polygonOffset(double factor, double units) {} public void readPixels(int x, int y, int width, int height, int format, int type, ArrayBufferView pixels) {} public void releaseShaderCompiler() {} public void renderbufferStorage(int target, int internalformat, int width, int height) {} public void sampleCoverage(double value, bool invert) {} public void scissor(int x, int y, int width, int height) {} public void shaderSource(WebGLShader shader, string @string) {} public void stencilFunc(int func, int @ref, int mask) {} public void stencilFuncSeparate(int face, int func, int @ref, int mask) {} public void stencilMask(int mask) {} public void stencilMaskSeparate(int face, int mask) {} public void stencilOp(int fail, int zfail, int zpass) {} public void stencilOpSeparate(int face, int fail, int zfail, int zpass) {} public void texParameterf(int target, int pname, double param) {} public void texParameteri(int target, int pname, int param) {} public void texImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, ArrayBufferView pixels) {} public void texImage2D(int target, int level, int internalformat, int format, int type, ImageData pixels) {} public void texImage2D(int target, int level, int internalformat, int format, int type, HtmlImageElement image) {} public void texImage2D(int target, int level, int internalformat, int format, int type, HtmlCanvasElement canvas) {} public void texSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, ArrayBufferView pixels) {} public void texSubImage2D(int target, int level, int xoffset, int yoffset, int format, int type, ImageData pixels) {} public void texSubImage2D(int target, int level, int xoffset, int yoffset, int format, int type, HtmlImageElement image) {} public void texSubImage2D(int target, int level, int xoffset, int yoffset, int format, int type, HtmlCanvasElement canvas) {} public void uniform1f(WebGLUniformLocation location, double x) {} public void uniform1fv(WebGLUniformLocation location, Float32Array v) {} public void uniform1i(WebGLUniformLocation location, int x) {} public void uniform1iv(WebGLUniformLocation location, Int32Array v) {} public void uniform2f(WebGLUniformLocation location, double x, double y) {} public void uniform2fv(WebGLUniformLocation location, Float32Array v) {} public void uniform2i(WebGLUniformLocation location, int x, int y) {} public void uniform2iv(WebGLUniformLocation location, Int32Array v) {} public void uniform3f(WebGLUniformLocation location, double x, double y, double z) {} public void uniform3fv(WebGLUniformLocation location, Float32Array v) {} public void uniform3i(WebGLUniformLocation location, int x, int y, int z) {} public void uniform3iv(WebGLUniformLocation location, Int32Array v) {} public void uniform4f(WebGLUniformLocation location, double x, double y, double z, double w) {} public void uniform4fv(WebGLUniformLocation location, Float32Array v) {} public void uniform4i(WebGLUniformLocation location, int x, int y, int z, int w) {} public void uniform4iv(WebGLUniformLocation location, Int32Array v) {} public void uniformMatrix2fv(WebGLUniformLocation location, bool transpose, Float32Array array) {} public void uniformMatrix3fv(WebGLUniformLocation location, bool transpose, Float32Array array) {} public void uniformMatrix4fv(WebGLUniformLocation location, bool transpose, Float32Array array) {} public void useProgram(WebGLProgram program) {} public void validateProgram(WebGLProgram program) {} public void vertexAttrib1f(int indx, double x) {} public void vertexAttrib1fv(int indx, Float32Array values) {} public void vertexAttrib2f(int indx, double x, double y) {} public void vertexAttrib2fv(int indx, Float32Array values) {} public void vertexAttrib3f(int indx, double x, double y, double z) {} public void vertexAttrib3fv(int indx, Float32Array values) {} public void vertexAttrib4f(int indx, double x, double y, double z, double w) {} public void vertexAttrib4fv(int indx, Float32Array values) {} public void vertexAttribPointer(int indx, int size, int type, bool normalized, int stride, int offset) {} public void viewport(int x, int y, int width, int height) {} } }