context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Threading; using OpenMetaverse; using OpenMetaverse.Packets; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Services.Interfaces; namespace OpenSim.Region.Framework.Scenes { public partial class Scene { /// <summary> /// Send chat to listeners. /// </summary> /// <param name='message'></param> /// <param name='type'>/param> /// <param name='channel'></param> /// <param name='fromPos'></param> /// <param name='fromName'></param> /// <param name='fromID'></param> /// <param name='targetID'></param> /// <param name='fromAgent'></param> /// <param name='broadcast'></param> protected void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName, UUID fromID, UUID targetID, bool fromAgent, bool broadcast) { OSChatMessage args = new OSChatMessage(); args.Message = Utils.BytesToString(message); args.Channel = channel; args.Type = type; args.Position = fromPos; args.SenderUUID = fromID; args.Scene = this; if (fromAgent) { ScenePresence user = GetScenePresence(fromID); if (user != null) args.Sender = user.ControllingClient; } else { SceneObjectPart obj = GetSceneObjectPart(fromID); args.SenderObject = obj; } args.From = fromName; args.TargetUUID = targetID; // m_log.DebugFormat( // "[SCENE]: Sending message {0} on channel {1}, type {2} from {3}, broadcast {4}", // args.Message.Replace("\n", "\\n"), args.Channel, args.Type, fromName, broadcast); if (broadcast) EventManager.TriggerOnChatBroadcast(this, args); else EventManager.TriggerOnChatFromWorld(this, args); } protected void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName, UUID fromID, bool fromAgent, bool broadcast) { SimChat(message, type, channel, fromPos, fromName, fromID, UUID.Zero, fromAgent, broadcast); } /// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="type"></param> /// <param name="fromPos"></param> /// <param name="fromName"></param> /// <param name="fromAgentID"></param> public void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName, UUID fromID, bool fromAgent) { SimChat(message, type, channel, fromPos, fromName, fromID, fromAgent, false); } public void SimChat(string message, ChatTypeEnum type, Vector3 fromPos, string fromName, UUID fromID, bool fromAgent) { SimChat(Utils.StringToBytes(message), type, 0, fromPos, fromName, fromID, fromAgent); } public void SimChat(string message, string fromName) { SimChat(message, ChatTypeEnum.Broadcast, Vector3.Zero, fromName, UUID.Zero, false); } /// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="type"></param> /// <param name="fromPos"></param> /// <param name="fromName"></param> /// <param name="fromAgentID"></param> public void SimChatBroadcast(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName, UUID fromID, bool fromAgent) { SimChat(message, type, channel, fromPos, fromName, fromID, fromAgent, true); } /// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="type"></param> /// <param name="fromPos"></param> /// <param name="fromName"></param> /// <param name="fromAgentID"></param> /// <param name="targetID"></param> public void SimChatToAgent(UUID targetID, byte[] message, Vector3 fromPos, string fromName, UUID fromID, bool fromAgent) { SimChat(message, ChatTypeEnum.Say, 0, fromPos, fromName, fromID, targetID, fromAgent, false); } /// <summary> /// Invoked when the client requests a prim. /// </summary> /// <param name="primLocalID"></param> /// <param name="remoteClient"></param> public void RequestPrim(uint primLocalID, IClientAPI remoteClient) { SceneObjectGroup sog = GetGroupByPrim(primLocalID); if (sog != null) sog.SendFullUpdateToClient(remoteClient); } /// <summary> /// Invoked when the client selects a prim. /// </summary> /// <param name="primLocalID"></param> /// <param name="remoteClient"></param> public void SelectPrim(uint primLocalID, IClientAPI remoteClient) { SceneObjectPart part = GetSceneObjectPart(primLocalID); if (null == part) return; if (part.IsRoot) { SceneObjectGroup sog = part.ParentGroup; sog.SendPropertiesToClient(remoteClient); sog.IsSelected = true; // A prim is only tainted if it's allowed to be edited by the person clicking it. if (Permissions.CanEditObject(sog.UUID, remoteClient.AgentId) || Permissions.CanMoveObject(sog.UUID, remoteClient.AgentId)) { EventManager.TriggerParcelPrimCountTainted(); } } else { part.SendPropertiesToClient(remoteClient); } } /// <summary> /// Handle the update of an object's user group. /// </summary> /// <param name="remoteClient"></param> /// <param name="groupID"></param> /// <param name="objectLocalID"></param> /// <param name="Garbage"></param> private void HandleObjectGroupUpdate( IClientAPI remoteClient, UUID groupID, uint objectLocalID, UUID Garbage) { if (m_groupsModule == null) return; // XXX: Might be better to get rid of this special casing and have GetMembershipData return something // reasonable for a UUID.Zero group. if (groupID != UUID.Zero) { GroupMembershipData gmd = m_groupsModule.GetMembershipData(groupID, remoteClient.AgentId); if (gmd == null) { // m_log.WarnFormat( // "[GROUPS]: User {0} is not a member of group {1} so they can't update {2} to this group", // remoteClient.Name, GroupID, objectLocalID); return; } } SceneObjectGroup so = ((Scene)remoteClient.Scene).GetGroupByPrim(objectLocalID); if (so != null) { if (so.OwnerID == remoteClient.AgentId) { so.SetGroup(groupID, remoteClient); } } } /// <summary> /// Handle the deselection of a prim from the client. /// </summary> /// <param name="primLocalID"></param> /// <param name="remoteClient"></param> public void DeselectPrim(uint primLocalID, IClientAPI remoteClient) { SceneObjectPart part = GetSceneObjectPart(primLocalID); if (part == null) return; // A deselect packet contains all the local prims being deselected. However, since selection is still // group based we only want the root prim to trigger a full update - otherwise on objects with many prims // we end up sending many duplicate ObjectUpdates if (part.ParentGroup.RootPart.LocalId != part.LocalId) return; // This is wrong, wrong, wrong. Selection should not be // handled by group, but by prim. Legacy cruft. // TODO: Make selection flagging per prim! // part.ParentGroup.IsSelected = false; part.ParentGroup.ScheduleGroupForFullUpdate(); // If it's not an attachment, and we are allowed to move it, // then we might have done so. If we moved across a parcel // boundary, we will need to recount prims on the parcels. // For attachments, that makes no sense. // if (!part.ParentGroup.IsAttachment) { if (Permissions.CanEditObject( part.UUID, remoteClient.AgentId) || Permissions.CanMoveObject( part.UUID, remoteClient.AgentId)) EventManager.TriggerParcelPrimCountTainted(); } } public virtual void ProcessMoneyTransferRequest(UUID source, UUID destination, int amount, int transactiontype, string description) { EventManager.MoneyTransferArgs args = new EventManager.MoneyTransferArgs(source, destination, amount, transactiontype, description); EventManager.TriggerMoneyTransfer(this, args); } public virtual void ProcessParcelBuy(UUID agentId, UUID groupId, bool final, bool groupOwned, bool removeContribution, int parcelLocalID, int parcelArea, int parcelPrice, bool authenticated) { EventManager.LandBuyArgs args = new EventManager.LandBuyArgs(agentId, groupId, final, groupOwned, removeContribution, parcelLocalID, parcelArea, parcelPrice, authenticated); // First, allow all validators a stab at it m_eventManager.TriggerValidateLandBuy(this, args); // Then, check validation and transfer m_eventManager.TriggerLandBuy(this, args); } public virtual void ProcessObjectGrab(uint localID, Vector3 offsetPos, IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs) { SceneObjectPart part = GetSceneObjectPart(localID); if (part == null) return; SceneObjectGroup obj = part.ParentGroup; SurfaceTouchEventArgs surfaceArg = null; if (surfaceArgs != null && surfaceArgs.Count > 0) surfaceArg = surfaceArgs[0]; // Currently only grab/touch for the single prim // the client handles rez correctly obj.ObjectGrabHandler(localID, offsetPos, remoteClient); // If the touched prim handles touches, deliver it // If not, deliver to root prim if ((part.ScriptEvents & scriptEvents.touch_start) != 0) EventManager.TriggerObjectGrab(part.LocalId, 0, part.OffsetPosition, remoteClient, surfaceArg); // Deliver to the root prim if the touched prim doesn't handle touches // or if we're meant to pass on touches anyway. Don't send to root prim // if prim touched is the root prim as we just did it if (((part.ScriptEvents & scriptEvents.touch_start) == 0) || (part.PassTouches && (part.LocalId != obj.RootPart.LocalId))) { EventManager.TriggerObjectGrab(obj.RootPart.LocalId, part.LocalId, part.OffsetPosition, remoteClient, surfaceArg); } } public virtual void ProcessObjectGrabUpdate( UUID objectID, Vector3 offset, Vector3 pos, IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs) { SceneObjectPart part = GetSceneObjectPart(objectID); if (part == null) return; SceneObjectGroup obj = part.ParentGroup; SurfaceTouchEventArgs surfaceArg = null; if (surfaceArgs != null && surfaceArgs.Count > 0) surfaceArg = surfaceArgs[0]; // If the touched prim handles touches, deliver it // If not, deliver to root prim if ((part.ScriptEvents & scriptEvents.touch) != 0) EventManager.TriggerObjectGrabbing(part.LocalId, 0, part.OffsetPosition, remoteClient, surfaceArg); // Deliver to the root prim if the touched prim doesn't handle touches // or if we're meant to pass on touches anyway. Don't send to root prim // if prim touched is the root prim as we just did it if (((part.ScriptEvents & scriptEvents.touch) == 0) || (part.PassTouches && (part.LocalId != obj.RootPart.LocalId))) { EventManager.TriggerObjectGrabbing(obj.RootPart.LocalId, part.LocalId, part.OffsetPosition, remoteClient, surfaceArg); } } public virtual void ProcessObjectDeGrab(uint localID, IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs) { SceneObjectPart part = GetSceneObjectPart(localID); if (part == null) return; SceneObjectGroup obj = part.ParentGroup; SurfaceTouchEventArgs surfaceArg = null; if (surfaceArgs != null && surfaceArgs.Count > 0) surfaceArg = surfaceArgs[0]; // If the touched prim handles touches, deliver it // If not, deliver to root prim if ((part.ScriptEvents & scriptEvents.touch_end) != 0) EventManager.TriggerObjectDeGrab(part.LocalId, 0, remoteClient, surfaceArg); else EventManager.TriggerObjectDeGrab(obj.RootPart.LocalId, part.LocalId, remoteClient, surfaceArg); } public void ProcessScriptReset(IClientAPI remoteClient, UUID objectID, UUID itemID) { SceneObjectPart part=GetSceneObjectPart(objectID); if (part == null) return; if (Permissions.CanResetScript(objectID, itemID, remoteClient.AgentId)) { EventManager.TriggerScriptReset(part.LocalId, itemID); } } void ProcessViewerEffect(IClientAPI remoteClient, List<ViewerEffectEventHandlerArg> args) { // TODO: don't create new blocks if recycling an old packet bool discardableEffects = true; ViewerEffectPacket.EffectBlock[] effectBlockArray = new ViewerEffectPacket.EffectBlock[args.Count]; for (int i = 0; i < args.Count; i++) { ViewerEffectPacket.EffectBlock effect = new ViewerEffectPacket.EffectBlock(); effect.AgentID = args[i].AgentID; effect.Color = args[i].Color; effect.Duration = args[i].Duration; effect.ID = args[i].ID; effect.Type = args[i].Type; effect.TypeData = args[i].TypeData; effectBlockArray[i] = effect; if ((EffectType)effect.Type != EffectType.LookAt && (EffectType)effect.Type != EffectType.Beam) discardableEffects = false; //m_log.DebugFormat("[YYY]: VE {0} {1} {2}", effect.AgentID, effect.Duration, (EffectType)effect.Type); } ForEachScenePresence(sp => { if (sp.ControllingClient.AgentId != remoteClient.AgentId) { if (!discardableEffects || (discardableEffects && ShouldSendDiscardableEffect(remoteClient, sp))) { //m_log.DebugFormat("[YYY]: Sending to {0}", sp.UUID); sp.ControllingClient.SendViewerEffect(effectBlockArray); } //else // m_log.DebugFormat("[YYY]: Not sending to {0}", sp.UUID); } }); } private bool ShouldSendDiscardableEffect(IClientAPI thisClient, ScenePresence other) { return Vector3.Distance(other.CameraPosition, thisClient.SceneAgent.AbsolutePosition) < 10; } /// <summary> /// Tell the client about the various child items and folders contained in the requested folder. /// </summary> /// <param name="remoteClient"></param> /// <param name="folderID"></param> /// <param name="ownerID"></param> /// <param name="fetchFolders"></param> /// <param name="fetchItems"></param> /// <param name="sortOrder"></param> public void HandleFetchInventoryDescendents(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder) { // m_log.DebugFormat( // "[USER INVENTORY]: HandleFetchInventoryDescendents() for {0}, folder={1}, fetchFolders={2}, fetchItems={3}, sortOrder={4}", // remoteClient.Name, folderID, fetchFolders, fetchItems, sortOrder); if (folderID == UUID.Zero) return; // FIXME MAYBE: We're not handling sortOrder! // TODO: This code for looking in the folder for the library should be folded somewhere else // so that this class doesn't have to know the details (and so that multiple libraries, etc. // can be handled transparently). InventoryFolderImpl fold = null; if (LibraryService != null && LibraryService.LibraryRootFolder != null) { if ((fold = LibraryService.LibraryRootFolder.FindFolder(folderID)) != null) { remoteClient.SendInventoryFolderDetails( fold.Owner, folderID, fold.RequestListOfItems(), fold.RequestListOfFolders(), fold.Version, fetchFolders, fetchItems); return; } } // We're going to send the reply async, because there may be // an enormous quantity of packets -- basically the entire inventory! // We don't want to block the client thread while all that is happening. SendInventoryDelegate d = SendInventoryAsync; d.BeginInvoke(remoteClient, folderID, ownerID, fetchFolders, fetchItems, sortOrder, SendInventoryComplete, d); } delegate void SendInventoryDelegate(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder); void SendInventoryAsync(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder) { SendInventoryUpdate(remoteClient, new InventoryFolderBase(folderID), fetchFolders, fetchItems); } void SendInventoryComplete(IAsyncResult iar) { SendInventoryDelegate d = (SendInventoryDelegate)iar.AsyncState; d.EndInvoke(iar); } /// <summary> /// Handle an inventory folder creation request from the client. /// </summary> /// <param name="remoteClient"></param> /// <param name="folderID"></param> /// <param name="folderType"></param> /// <param name="folderName"></param> /// <param name="parentID"></param> public void HandleCreateInventoryFolder(IClientAPI remoteClient, UUID folderID, ushort folderType, string folderName, UUID parentID) { InventoryFolderBase folder = new InventoryFolderBase(folderID, folderName, remoteClient.AgentId, (short)folderType, parentID, 1); if (!InventoryService.AddFolder(folder)) { m_log.WarnFormat( "[AGENT INVENTORY]: Failed to create folder for user {0} {1}", remoteClient.Name, remoteClient.AgentId); } } /// <summary> /// Handle a client request to update the inventory folder /// </summary> /// /// FIXME: We call add new inventory folder because in the data layer, we happen to use an SQL REPLACE /// so this will work to rename an existing folder. Needless to say, to rely on this is very confusing, /// and needs to be changed. /// /// <param name="remoteClient"></param> /// <param name="folderID"></param> /// <param name="type"></param> /// <param name="name"></param> /// <param name="parentID"></param> public void HandleUpdateInventoryFolder(IClientAPI remoteClient, UUID folderID, ushort type, string name, UUID parentID) { // m_log.DebugFormat( // "[AGENT INVENTORY]: Updating inventory folder {0} {1} for {2} {3}", folderID, name, remoteClient.Name, remoteClient.AgentId); InventoryFolderBase folder = new InventoryFolderBase(folderID, remoteClient.AgentId); folder = InventoryService.GetFolder(folder); if (folder != null) { folder.Name = name; folder.Type = (short)type; folder.ParentID = parentID; if (!InventoryService.UpdateFolder(folder)) { m_log.ErrorFormat( "[AGENT INVENTORY]: Failed to update folder for user {0} {1}", remoteClient.Name, remoteClient.AgentId); } } } public void HandleMoveInventoryFolder(IClientAPI remoteClient, UUID folderID, UUID parentID) { InventoryFolderBase folder = new InventoryFolderBase(folderID, remoteClient.AgentId); folder = InventoryService.GetFolder(folder); if (folder != null) { folder.ParentID = parentID; if (!InventoryService.MoveFolder(folder)) m_log.WarnFormat("[AGENT INVENTORY]: could not move folder {0}", folderID); else m_log.DebugFormat("[AGENT INVENTORY]: folder {0} moved to parent {1}", folderID, parentID); } else { m_log.WarnFormat("[AGENT INVENTORY]: request to move folder {0} but folder not found", folderID); } } delegate void PurgeFolderDelegate(UUID userID, UUID folder); /// <summary> /// This should delete all the items and folders in the given directory. /// </summary> /// <param name="remoteClient"></param> /// <param name="folderID"></param> public void HandlePurgeInventoryDescendents(IClientAPI remoteClient, UUID folderID) { PurgeFolderDelegate d = PurgeFolderAsync; try { d.BeginInvoke(remoteClient.AgentId, folderID, PurgeFolderCompleted, d); } catch (Exception e) { m_log.WarnFormat("[AGENT INVENTORY]: Exception on purge folder for user {0}: {1}", remoteClient.AgentId, e.Message); } } private void PurgeFolderAsync(UUID userID, UUID folderID) { InventoryFolderBase folder = new InventoryFolderBase(folderID, userID); if (InventoryService.PurgeFolder(folder)) m_log.DebugFormat("[AGENT INVENTORY]: folder {0} purged successfully", folderID); else m_log.WarnFormat("[AGENT INVENTORY]: could not purge folder {0}", folderID); } private void PurgeFolderCompleted(IAsyncResult iar) { PurgeFolderDelegate d = (PurgeFolderDelegate)iar.AsyncState; d.EndInvoke(iar); } } }
// 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.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO.Enumeration; using System.Threading; using System.Threading.Tasks; namespace System.IO { /// <devdoc> /// Listens to the system directory change notifications and /// raises events when a directory or file within a directory changes. /// </devdoc> public partial class FileSystemWatcher : Component, ISupportInitialize { /// <devdoc> /// Private instance variables /// </devdoc> // Directory being monitored private string _directory; // The watch filter for the API call. private const NotifyFilters c_defaultNotifyFilters = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; private NotifyFilters _notifyFilters = c_defaultNotifyFilters; // Flag to watch subtree of this directory private bool _includeSubdirectories = false; // Flag to note whether we are attached to the thread pool and responding to changes private bool _enabled = false; // Are we in init? private bool _initializing = false; // Buffer size private uint _internalBufferSize = 8192; // Used for synchronization private bool _disposed; // Event handlers private FileSystemEventHandler _onChangedHandler = null; private FileSystemEventHandler _onCreatedHandler = null; private FileSystemEventHandler _onDeletedHandler = null; private RenamedEventHandler _onRenamedHandler = null; private ErrorEventHandler _onErrorHandler = null; // To validate the input for "path" private static readonly char[] s_wildcards = new char[] { '?', '*' }; private const int c_notifyFiltersValidMask = (int)(NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size); #if DEBUG static FileSystemWatcher() { int s_notifyFiltersValidMask = 0; foreach (int enumValue in Enum.GetValues(typeof(NotifyFilters))) s_notifyFiltersValidMask |= enumValue; Debug.Assert(c_notifyFiltersValidMask == s_notifyFiltersValidMask, "The NotifyFilters enum has changed. The c_notifyFiltersValidMask must be updated to reflect the values of the NotifyFilters enum."); } #endif /// <devdoc> /// Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class. /// </devdoc> public FileSystemWatcher() { _directory = string.Empty; } /// <devdoc> /// Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class, /// given the specified directory to monitor. /// </devdoc> public FileSystemWatcher(string path) { CheckPathValidity(path); _directory = path; } /// <devdoc> /// Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class, /// given the specified directory and type of files to monitor. /// </devdoc> public FileSystemWatcher(string path, string filter) { CheckPathValidity(path); _directory = path; Filter = filter ?? throw new ArgumentNullException(nameof(filter)); } /// <devdoc> /// Gets or sets the type of changes to watch for. /// </devdoc> public NotifyFilters NotifyFilter { get { return _notifyFilters; } set { if (((int)value & ~c_notifyFiltersValidMask) != 0) throw new ArgumentException(SR.Format(SR.InvalidEnumArgument, nameof(value), (int)value, nameof(NotifyFilters))); if (_notifyFilters != value) { _notifyFilters = value; Restart(); } } } public Collection<string> Filters { get; } = new NormalizedFilterCollection(); /// <devdoc> /// Gets or sets a value indicating whether the component is enabled. /// </devdoc> public bool EnableRaisingEvents { get { return _enabled; } set { if (_enabled == value) { return; } if (IsSuspended()) { _enabled = value; // Alert the Component to start watching for events when EndInit is called. } else { if (value) { StartRaisingEventsIfNotDisposed(); // will set _enabled to true once successfully started } else { StopRaisingEvents(); // will set _enabled to false } } } } /// <devdoc> /// Gets or sets the filter string, used to determine what files are monitored in a directory. /// </devdoc> public string Filter { get { return Filters.Count == 0 ? "*" : Filters[0]; } set { Filters.Clear(); Filters.Add(value); } } /// <devdoc> /// Gets or sets a value indicating whether subdirectories within the specified path should be monitored. /// </devdoc> public bool IncludeSubdirectories { get { return _includeSubdirectories; } set { if (_includeSubdirectories != value) { _includeSubdirectories = value; Restart(); } } } /// <devdoc> /// Gets or sets the size of the internal buffer. /// </devdoc> public int InternalBufferSize { get { return (int)_internalBufferSize; } set { if (_internalBufferSize != value) { if (value < 4096) { _internalBufferSize = 4096; } else { _internalBufferSize = (uint)value; } Restart(); } } } /// <summary>Allocates a buffer of the requested internal buffer size.</summary> /// <returns>The allocated buffer.</returns> private byte[] AllocateBuffer() { try { return new byte[_internalBufferSize]; } catch (OutOfMemoryException) { throw new OutOfMemoryException(SR.Format(SR.BufferSizeTooLarge, _internalBufferSize)); } } /// <devdoc> /// Gets or sets the path of the directory to watch. /// </devdoc> public string Path { get { return _directory; } set { value = (value == null) ? string.Empty : value; if (!string.Equals(_directory, value, PathInternal.StringComparison)) { if (value.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidDirName, value), nameof(Path)); if (!Directory.Exists(value)) throw new ArgumentException(SR.Format(SR.InvalidDirName_NotExists, value), nameof(Path)); _directory = value; Restart(); } } } /// <devdoc> /// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> is changed. /// </devdoc> public event FileSystemEventHandler Changed { add { _onChangedHandler += value; } remove { _onChangedHandler -= value; } } /// <devdoc> /// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> is created. /// </devdoc> public event FileSystemEventHandler Created { add { _onCreatedHandler += value; } remove { _onCreatedHandler -= value; } } /// <devdoc> /// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> is deleted. /// </devdoc> public event FileSystemEventHandler Deleted { add { _onDeletedHandler += value; } remove { _onDeletedHandler -= value; } } /// <devdoc> /// Occurs when the internal buffer overflows. /// </devdoc> public event ErrorEventHandler Error { add { _onErrorHandler += value; } remove { _onErrorHandler -= value; } } /// <devdoc> /// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> /// is renamed. /// </devdoc> public event RenamedEventHandler Renamed { add { _onRenamedHandler += value; } remove { _onRenamedHandler -= value; } } protected override void Dispose(bool disposing) { try { if (disposing) { //Stop raising events cleans up managed and //unmanaged resources. StopRaisingEvents(); // Clean up managed resources _onChangedHandler = null; _onCreatedHandler = null; _onDeletedHandler = null; _onRenamedHandler = null; _onErrorHandler = null; } else { FinalizeDispose(); } } finally { _disposed = true; base.Dispose(disposing); } } private static void CheckPathValidity(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); // Early check for directory parameter so that an exception can be thrown as early as possible. if (path.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidDirName, path), nameof(path)); if (!Directory.Exists(path)) throw new ArgumentException(SR.Format(SR.InvalidDirName_NotExists, path), nameof(path)); } /// <summary> /// Sees if the name given matches the name filter we have. /// </summary> private bool MatchPattern(ReadOnlySpan<char> relativePath) { ReadOnlySpan<char> name = IO.Path.GetFileName(relativePath); if (name.Length == 0) return false; if (Filters.Count == 0) return true; foreach (string filter in Filters) { if (FileSystemName.MatchesSimpleExpression(filter, name, ignoreCase: !PathInternal.IsCaseSensitive)) return true; } return false; } /// <summary> /// Raises the event to each handler in the list. /// </summary> private void NotifyInternalBufferOverflowEvent() { _onErrorHandler?.Invoke(this, new ErrorEventArgs( new InternalBufferOverflowException(SR.Format(SR.FSW_BufferOverflow, _directory)))); } /// <summary> /// Raises the event to each handler in the list. /// </summary> private void NotifyRenameEventArgs(WatcherChangeTypes action, ReadOnlySpan<char> name, ReadOnlySpan<char> oldName) { // filter if there's no handler or neither new name or old name match a specified pattern RenamedEventHandler handler = _onRenamedHandler; if (handler != null && (MatchPattern(name) || MatchPattern(oldName))) { handler(this, new RenamedEventArgs(action, _directory, name.IsEmpty ? null : name.ToString(), oldName.IsEmpty ? null : oldName.ToString())); } } private FileSystemEventHandler GetHandler(WatcherChangeTypes changeType) { switch (changeType) { case WatcherChangeTypes.Created: return _onCreatedHandler; case WatcherChangeTypes.Deleted: return _onDeletedHandler; case WatcherChangeTypes.Changed: return _onChangedHandler; } Debug.Fail("Unknown FileSystemEvent change type! Value: " + changeType); return null; } /// <summary> /// Raises the event to each handler in the list. /// </summary> private void NotifyFileSystemEventArgs(WatcherChangeTypes changeType, ReadOnlySpan<char> name) { FileSystemEventHandler handler = GetHandler(changeType); if (handler != null && MatchPattern(name.IsEmpty ? _directory : name)) { handler(this, new FileSystemEventArgs(changeType, _directory, name.IsEmpty ? null : name.ToString())); } } /// <summary> /// Raises the event to each handler in the list. /// </summary> private void NotifyFileSystemEventArgs(WatcherChangeTypes changeType, string name) { FileSystemEventHandler handler = GetHandler(changeType); if (handler != null && MatchPattern(string.IsNullOrEmpty(name) ? _directory : name)) { handler(this, new FileSystemEventArgs(changeType, _directory, name)); } } /// <devdoc> /// Raises the <see cref='System.IO.FileSystemWatcher.Changed'/> event. /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")] protected void OnChanged(FileSystemEventArgs e) { InvokeOn(e, _onChangedHandler); } /// <devdoc> /// Raises the <see cref='System.IO.FileSystemWatcher.Created'/> event. /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")] protected void OnCreated(FileSystemEventArgs e) { InvokeOn(e, _onCreatedHandler); } /// <devdoc> /// Raises the <see cref='System.IO.FileSystemWatcher.Deleted'/> event. /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")] protected void OnDeleted(FileSystemEventArgs e) { InvokeOn(e, _onDeletedHandler); } private void InvokeOn(FileSystemEventArgs e, FileSystemEventHandler handler) { if (handler != null) { ISynchronizeInvoke syncObj = SynchronizingObject; if (syncObj != null && syncObj.InvokeRequired) syncObj.BeginInvoke(handler, new object[] { this, e }); else handler(this, e); } } /// <devdoc> /// Raises the <see cref='System.IO.FileSystemWatcher.Error'/> event. /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")] protected void OnError(ErrorEventArgs e) { ErrorEventHandler handler = _onErrorHandler; if (handler != null) { ISynchronizeInvoke syncObj = SynchronizingObject; if (syncObj != null && syncObj.InvokeRequired) syncObj.BeginInvoke(handler, new object[] { this, e }); else handler(this, e); } } /// <devdoc> /// Raises the <see cref='System.IO.FileSystemWatcher.Renamed'/> event. /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")] protected void OnRenamed(RenamedEventArgs e) { RenamedEventHandler handler = _onRenamedHandler; if (handler != null) { ISynchronizeInvoke syncObj = SynchronizingObject; if (syncObj != null && syncObj.InvokeRequired) syncObj.BeginInvoke(handler, new object[] { this, e }); else handler(this, e); } } public WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType) => WaitForChanged(changeType, Timeout.Infinite); public WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout) { // The full framework implementation doesn't do any argument validation, so // none is done here, either. var tcs = new TaskCompletionSource<WaitForChangedResult>(); FileSystemEventHandler fseh = null; RenamedEventHandler reh = null; // Register the event handlers based on what events are desired. The full framework // doesn't register for the Error event, so this doesn't either. if ((changeType & (WatcherChangeTypes.Created | WatcherChangeTypes.Deleted | WatcherChangeTypes.Changed)) != 0) { fseh = (s, e) => { if ((e.ChangeType & changeType) != 0) { tcs.TrySetResult(new WaitForChangedResult(e.ChangeType, e.Name, oldName: null, timedOut: false)); } }; if ((changeType & WatcherChangeTypes.Created) != 0) Created += fseh; if ((changeType & WatcherChangeTypes.Deleted) != 0) Deleted += fseh; if ((changeType & WatcherChangeTypes.Changed) != 0) Changed += fseh; } if ((changeType & WatcherChangeTypes.Renamed) != 0) { reh = (s, e) => { if ((e.ChangeType & changeType) != 0) { tcs.TrySetResult(new WaitForChangedResult(e.ChangeType, e.Name, e.OldName, timedOut: false)); } }; Renamed += reh; } try { // Enable the FSW if it wasn't already. bool wasEnabled = EnableRaisingEvents; if (!wasEnabled) { EnableRaisingEvents = true; } // Block until an appropriate event arrives or until we timeout. Debug.Assert(EnableRaisingEvents, "Expected EnableRaisingEvents to be true"); tcs.Task.Wait(timeout); // Reset the enabled state to what it was. EnableRaisingEvents = wasEnabled; } finally { // Unregister the event handlers. if (reh != null) { Renamed -= reh; } if (fseh != null) { if ((changeType & WatcherChangeTypes.Changed) != 0) Changed -= fseh; if ((changeType & WatcherChangeTypes.Deleted) != 0) Deleted -= fseh; if ((changeType & WatcherChangeTypes.Created) != 0) Created -= fseh; } } // Return the results. return tcs.Task.IsCompletedSuccessfully ? tcs.Task.Result : WaitForChangedResult.TimedOutResult; } /// <devdoc> /// Stops and starts this object. /// </devdoc> /// <internalonly/> private void Restart() { if ((!IsSuspended()) && _enabled) { StopRaisingEvents(); StartRaisingEventsIfNotDisposed(); } } private void StartRaisingEventsIfNotDisposed() { //Cannot allocate the directoryHandle and the readBuffer if the object has been disposed; finalization has been suppressed. if (_disposed) throw new ObjectDisposedException(GetType().Name); StartRaisingEvents(); } public override ISite Site { get { return base.Site; } set { base.Site = value; // set EnableRaisingEvents to true at design time so the user // doesn't have to manually. if (Site != null && Site.DesignMode) EnableRaisingEvents = true; } } public ISynchronizeInvoke SynchronizingObject { get; set; } public void BeginInit() { bool oldEnabled = _enabled; StopRaisingEvents(); _enabled = oldEnabled; _initializing = true; } public void EndInit() { _initializing = false; // Start listening to events if _enabled was set to true at some point. if (_directory.Length != 0 && _enabled) StartRaisingEvents(); } private bool IsSuspended() { return _initializing || DesignMode; } private class NormalizedFilterCollection : Collection<string> { protected override void InsertItem(int index, string item) { base.InsertItem(index, string.IsNullOrEmpty(item) || item == "*.*" ? "*" : item); } protected override void SetItem(int index, string item) { base.SetItem(index, string.IsNullOrEmpty(item) || item == "*.*" ? "*" : item); } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Compute.V1.Snippets { using Google.Api.Gax; using System; using System.Linq; using System.Threading.Tasks; using lro = Google.LongRunning; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedRegionNotificationEndpointsClientSnippets { /// <summary>Snippet for Delete</summary> public void DeleteRequestObject() { // Snippet: Delete(DeleteRegionNotificationEndpointRequest, CallSettings) // Create client RegionNotificationEndpointsClient regionNotificationEndpointsClient = RegionNotificationEndpointsClient.Create(); // Initialize request argument(s) DeleteRegionNotificationEndpointRequest request = new DeleteRegionNotificationEndpointRequest { RequestId = "", Region = "", Project = "", NotificationEndpoint = "", }; // Make the request lro::Operation<Operation, Operation> response = regionNotificationEndpointsClient.Delete(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = regionNotificationEndpointsClient.PollOnceDelete(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteRequestObjectAsync() { // Snippet: DeleteAsync(DeleteRegionNotificationEndpointRequest, CallSettings) // Additional: DeleteAsync(DeleteRegionNotificationEndpointRequest, CancellationToken) // Create client RegionNotificationEndpointsClient regionNotificationEndpointsClient = await RegionNotificationEndpointsClient.CreateAsync(); // Initialize request argument(s) DeleteRegionNotificationEndpointRequest request = new DeleteRegionNotificationEndpointRequest { RequestId = "", Region = "", Project = "", NotificationEndpoint = "", }; // Make the request lro::Operation<Operation, Operation> response = await regionNotificationEndpointsClient.DeleteAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await regionNotificationEndpointsClient.PollOnceDeleteAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Delete</summary> public void Delete() { // Snippet: Delete(string, string, string, CallSettings) // Create client RegionNotificationEndpointsClient regionNotificationEndpointsClient = RegionNotificationEndpointsClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; string notificationEndpoint = ""; // Make the request lro::Operation<Operation, Operation> response = regionNotificationEndpointsClient.Delete(project, region, notificationEndpoint); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = regionNotificationEndpointsClient.PollOnceDelete(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteAsync() { // Snippet: DeleteAsync(string, string, string, CallSettings) // Additional: DeleteAsync(string, string, string, CancellationToken) // Create client RegionNotificationEndpointsClient regionNotificationEndpointsClient = await RegionNotificationEndpointsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; string notificationEndpoint = ""; // Make the request lro::Operation<Operation, Operation> response = await regionNotificationEndpointsClient.DeleteAsync(project, region, notificationEndpoint); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await regionNotificationEndpointsClient.PollOnceDeleteAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Get</summary> public void GetRequestObject() { // Snippet: Get(GetRegionNotificationEndpointRequest, CallSettings) // Create client RegionNotificationEndpointsClient regionNotificationEndpointsClient = RegionNotificationEndpointsClient.Create(); // Initialize request argument(s) GetRegionNotificationEndpointRequest request = new GetRegionNotificationEndpointRequest { Region = "", Project = "", NotificationEndpoint = "", }; // Make the request NotificationEndpoint response = regionNotificationEndpointsClient.Get(request); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetRequestObjectAsync() { // Snippet: GetAsync(GetRegionNotificationEndpointRequest, CallSettings) // Additional: GetAsync(GetRegionNotificationEndpointRequest, CancellationToken) // Create client RegionNotificationEndpointsClient regionNotificationEndpointsClient = await RegionNotificationEndpointsClient.CreateAsync(); // Initialize request argument(s) GetRegionNotificationEndpointRequest request = new GetRegionNotificationEndpointRequest { Region = "", Project = "", NotificationEndpoint = "", }; // Make the request NotificationEndpoint response = await regionNotificationEndpointsClient.GetAsync(request); // End snippet } /// <summary>Snippet for Get</summary> public void Get() { // Snippet: Get(string, string, string, CallSettings) // Create client RegionNotificationEndpointsClient regionNotificationEndpointsClient = RegionNotificationEndpointsClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; string notificationEndpoint = ""; // Make the request NotificationEndpoint response = regionNotificationEndpointsClient.Get(project, region, notificationEndpoint); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetAsync() { // Snippet: GetAsync(string, string, string, CallSettings) // Additional: GetAsync(string, string, string, CancellationToken) // Create client RegionNotificationEndpointsClient regionNotificationEndpointsClient = await RegionNotificationEndpointsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; string notificationEndpoint = ""; // Make the request NotificationEndpoint response = await regionNotificationEndpointsClient.GetAsync(project, region, notificationEndpoint); // End snippet } /// <summary>Snippet for Insert</summary> public void InsertRequestObject() { // Snippet: Insert(InsertRegionNotificationEndpointRequest, CallSettings) // Create client RegionNotificationEndpointsClient regionNotificationEndpointsClient = RegionNotificationEndpointsClient.Create(); // Initialize request argument(s) InsertRegionNotificationEndpointRequest request = new InsertRegionNotificationEndpointRequest { RequestId = "", Region = "", Project = "", NotificationEndpointResource = new NotificationEndpoint(), }; // Make the request lro::Operation<Operation, Operation> response = regionNotificationEndpointsClient.Insert(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = regionNotificationEndpointsClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InsertAsync</summary> public async Task InsertRequestObjectAsync() { // Snippet: InsertAsync(InsertRegionNotificationEndpointRequest, CallSettings) // Additional: InsertAsync(InsertRegionNotificationEndpointRequest, CancellationToken) // Create client RegionNotificationEndpointsClient regionNotificationEndpointsClient = await RegionNotificationEndpointsClient.CreateAsync(); // Initialize request argument(s) InsertRegionNotificationEndpointRequest request = new InsertRegionNotificationEndpointRequest { RequestId = "", Region = "", Project = "", NotificationEndpointResource = new NotificationEndpoint(), }; // Make the request lro::Operation<Operation, Operation> response = await regionNotificationEndpointsClient.InsertAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await regionNotificationEndpointsClient.PollOnceInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Insert</summary> public void Insert() { // Snippet: Insert(string, string, NotificationEndpoint, CallSettings) // Create client RegionNotificationEndpointsClient regionNotificationEndpointsClient = RegionNotificationEndpointsClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; NotificationEndpoint notificationEndpointResource = new NotificationEndpoint(); // Make the request lro::Operation<Operation, Operation> response = regionNotificationEndpointsClient.Insert(project, region, notificationEndpointResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = regionNotificationEndpointsClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InsertAsync</summary> public async Task InsertAsync() { // Snippet: InsertAsync(string, string, NotificationEndpoint, CallSettings) // Additional: InsertAsync(string, string, NotificationEndpoint, CancellationToken) // Create client RegionNotificationEndpointsClient regionNotificationEndpointsClient = await RegionNotificationEndpointsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; NotificationEndpoint notificationEndpointResource = new NotificationEndpoint(); // Make the request lro::Operation<Operation, Operation> response = await regionNotificationEndpointsClient.InsertAsync(project, region, notificationEndpointResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await regionNotificationEndpointsClient.PollOnceInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for List</summary> public void ListRequestObject() { // Snippet: List(ListRegionNotificationEndpointsRequest, CallSettings) // Create client RegionNotificationEndpointsClient regionNotificationEndpointsClient = RegionNotificationEndpointsClient.Create(); // Initialize request argument(s) ListRegionNotificationEndpointsRequest request = new ListRegionNotificationEndpointsRequest { Region = "", OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedEnumerable<NotificationEndpointList, NotificationEndpoint> response = regionNotificationEndpointsClient.List(request); // Iterate over all response items, lazily performing RPCs as required foreach (NotificationEndpoint item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (NotificationEndpointList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (NotificationEndpoint item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<NotificationEndpoint> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (NotificationEndpoint item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListRequestObjectAsync() { // Snippet: ListAsync(ListRegionNotificationEndpointsRequest, CallSettings) // Create client RegionNotificationEndpointsClient regionNotificationEndpointsClient = await RegionNotificationEndpointsClient.CreateAsync(); // Initialize request argument(s) ListRegionNotificationEndpointsRequest request = new ListRegionNotificationEndpointsRequest { Region = "", OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedAsyncEnumerable<NotificationEndpointList, NotificationEndpoint> response = regionNotificationEndpointsClient.ListAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((NotificationEndpoint item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((NotificationEndpointList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (NotificationEndpoint item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<NotificationEndpoint> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (NotificationEndpoint item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for List</summary> public void List() { // Snippet: List(string, string, string, int?, CallSettings) // Create client RegionNotificationEndpointsClient regionNotificationEndpointsClient = RegionNotificationEndpointsClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; // Make the request PagedEnumerable<NotificationEndpointList, NotificationEndpoint> response = regionNotificationEndpointsClient.List(project, region); // Iterate over all response items, lazily performing RPCs as required foreach (NotificationEndpoint item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (NotificationEndpointList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (NotificationEndpoint item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<NotificationEndpoint> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (NotificationEndpoint item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListAsync() { // Snippet: ListAsync(string, string, string, int?, CallSettings) // Create client RegionNotificationEndpointsClient regionNotificationEndpointsClient = await RegionNotificationEndpointsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; // Make the request PagedAsyncEnumerable<NotificationEndpointList, NotificationEndpoint> response = regionNotificationEndpointsClient.ListAsync(project, region); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((NotificationEndpoint item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((NotificationEndpointList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (NotificationEndpoint item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<NotificationEndpoint> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (NotificationEndpoint item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } } }
/* * DataGridTextBoxColumn.cs - Implementation of "System.Windows.Forms.DataGridTextBoxColumn" * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * Copyright (C) 2004 Free Software Foundation, Inc. * Copyright (C) 2005 Boris Manojlovic. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Windows.Forms { using System; using System.ComponentModel; using System.Drawing; public class DataGridTextBoxColumn : DataGridColumnStyle { [TODO] public DataGridTextBoxColumn() { throw new NotImplementedException(".ctor"); } [TODO] public DataGridTextBoxColumn(PropertyDescriptor prop) { throw new NotImplementedException(".ctor"); } [TODO] public DataGridTextBoxColumn(PropertyDescriptor prop, String format) { throw new NotImplementedException(".ctor"); } [TODO] public DataGridTextBoxColumn(PropertyDescriptor prop, String format, bool isDefault) { throw new NotImplementedException(".ctor"); } [TODO] public DataGridTextBoxColumn(PropertyDescriptor prop, bool isDefault) { throw new NotImplementedException(".ctor"); } [TODO] protected internal override void Abort(int rowNum) { throw new NotImplementedException("Abort"); } [TODO] protected internal override bool Commit(CurrencyManager dataSource, int rowNum) { throw new NotImplementedException("Commit"); } [TODO] protected internal override void ConcedeFocus() { throw new NotImplementedException("ConcedeFocus"); } [TODO] protected internal override void Edit(CurrencyManager source, int rowNum, Rectangle bounds, bool readOnly, String instantText, bool cellIsVisible) { throw new NotImplementedException("Edit"); } [TODO] protected void EndEdit() { throw new NotImplementedException("EndEdit"); } [TODO] protected internal override void EnterNullValue() { throw new NotImplementedException("EnterNullValue"); } [TODO] protected internal override int GetMinimumHeight() { throw new NotImplementedException("GetMinimumHeight"); } [TODO] protected internal override int GetPreferredHeight(Graphics g, System.Object value) { throw new NotImplementedException("GetPreferredHeight"); } [TODO] protected internal override System.Drawing.Size GetPreferredSize(Graphics g, Object value) { throw new NotImplementedException("GetPreferredSize"); } [TODO] protected void HideEditBox() { throw new NotImplementedException("HideEditBox"); } [TODO] protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum) { throw new NotImplementedException("Paint"); } [TODO] protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, bool alignToRight) { throw new NotImplementedException("Paint"); } [TODO] protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, Brush backBrush, Brush foreBrush, bool alignToRight) { throw new NotImplementedException("Paint"); } [TODO] protected void PaintText(Graphics g, Rectangle bounds, String text, bool alignToRight) { throw new NotImplementedException("PaintText"); } [TODO] protected void PaintText(Graphics g,Rectangle textBounds, String text, Brush backBrush, Brush foreBrush, bool alignToRight) { throw new NotImplementedException("PaintText"); } [TODO] protected internal override void ReleaseHostedControl() { throw new NotImplementedException("ReleaseHostedControl"); } [TODO] protected override void SetDataGridInColumn(DataGrid value) { throw new NotImplementedException("SetDataGridInColumn"); } [TODO] protected internal override void UpdateUI(CurrencyManager source, int rowNum,String instantText) { throw new NotImplementedException("UpdateUI"); } [TODO] public String Format { get { throw new NotImplementedException("Format"); } set { throw new NotImplementedException("Format"); } } [TODO] public System.IFormatProvider FormatInfo { get { throw new NotImplementedException("FormatInfo"); } set { throw new NotImplementedException("FormatInfo"); } } [TODO] public override PropertyDescriptor PropertyDescriptor { set { throw new NotImplementedException("PropertyDescriptor"); } } [TODO] public override bool ReadOnly { get { throw new NotImplementedException("ReadOnly"); } set { throw new NotImplementedException("ReadOnly"); } } [TODO] public virtual System.Windows.Forms.TextBox TextBox { get { throw new NotImplementedException("TextBox"); } } } }//namespace
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using osu.Framework; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Beatmaps; using osu.Game.Beatmaps.Drawables; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osu.Game.Online.Multiplayer; using osu.Game.Screens.Multi.Components; using osuTK; using osuTK.Graphics; namespace osu.Game.Screens.Multi.Lounge.Components { public class DrawableRoom : OsuClickableContainer, IStateful<SelectionState>, IFilterable { public const float SELECTION_BORDER_WIDTH = 4; private const float corner_radius = 5; private const float transition_duration = 60; private const float content_padding = 10; private const float height = 110; private const float side_strip_width = 5; private const float cover_width = 145; public event Action<SelectionState> StateChanged; private readonly Box selectionBox; private CachedModelDependencyContainer<Room> dependencies; [Resolved] private BeatmapManager beatmaps { get; set; } public readonly Room Room; private SelectionState state; public SelectionState State { get => state; set { if (value == state) return; state = value; if (state == SelectionState.Selected) selectionBox.FadeIn(transition_duration); else selectionBox.FadeOut(transition_duration); StateChanged?.Invoke(State); } } public IEnumerable<string> FilterTerms => new[] { Room.Name.Value }; private bool matchingFilter; public bool MatchingFilter { get => matchingFilter; set { matchingFilter = value; this.FadeTo(MatchingFilter ? 1 : 0, 200); } } public bool FilteringActive { get; set; } public DrawableRoom(Room room) { Room = room; RelativeSizeAxes = Axes.X; Height = height + SELECTION_BORDER_WIDTH * 2; CornerRadius = corner_radius + SELECTION_BORDER_WIDTH / 2; Masking = true; // create selectionBox here so State can be set before being loaded selectionBox = new Box { RelativeSizeAxes = Axes.Both, Alpha = 0f, }; } [BackgroundDependencyLoader] private void load(OsuColour colours) { Children = new Drawable[] { new StatusColouredContainer(transition_duration) { RelativeSizeAxes = Axes.Both, Child = selectionBox }, new Container { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding(SELECTION_BORDER_WIDTH), Child = new Container { RelativeSizeAxes = Axes.Both, Masking = true, CornerRadius = corner_radius, EdgeEffect = new EdgeEffectParameters { Type = EdgeEffectType.Shadow, Colour = Color4.Black.Opacity(40), Radius = 5, }, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = OsuColour.FromHex(@"212121"), }, new StatusColouredContainer(transition_duration) { RelativeSizeAxes = Axes.Y, Width = side_strip_width, Child = new Box { RelativeSizeAxes = Axes.Both } }, new Container { RelativeSizeAxes = Axes.Y, Width = cover_width, Masking = true, Margin = new MarginPadding { Left = side_strip_width }, Child = new MultiplayerBackgroundSprite(BeatmapSetCoverType.List) { RelativeSizeAxes = Axes.Both } }, new Container { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Vertical = content_padding, Left = side_strip_width + cover_width + content_padding, Right = content_padding, }, Children = new Drawable[] { new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, Spacing = new Vector2(5f), Children = new Drawable[] { new RoomName { Font = OsuFont.GetFont(size: 18) }, new ParticipantInfo(), }, }, new FillFlowContainer { Anchor = Anchor.BottomLeft, Origin = Anchor.BottomLeft, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, Spacing = new Vector2(0, 5), Children = new Drawable[] { new RoomStatusInfo(), new BeatmapTitle { TextSize = 14 }, }, }, new ModeTypeInfo { Anchor = Anchor.BottomRight, Origin = Anchor.BottomRight, }, }, }, }, }, }, }; } protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) { dependencies = new CachedModelDependencyContainer<Room>(base.CreateChildDependencies(parent)); dependencies.Model.Value = Room; return dependencies; } protected override void LoadComplete() { base.LoadComplete(); this.FadeInFromZero(transition_duration); } private class RoomName : OsuSpriteText { [Resolved(typeof(Room), nameof(Online.Multiplayer.Room.Name))] private Bindable<string> name { get; set; } [BackgroundDependencyLoader] private void load() { Current = name; } } } }
// // 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.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using Cassandra.Compression; using Cassandra.Metrics; using Cassandra.Observers.Abstractions; using Cassandra.Requests; using Cassandra.Responses; using Cassandra.Serialization; using Cassandra.Tasks; using Microsoft.IO; namespace Cassandra.Connections { /// <inheritdoc /> internal class Connection : IConnection { private const int WriteStateInit = 0; private const int WriteStateRunning = 1; private const int WriteStateClosed = 2; private const string StreamReadTag = nameof(Connection) + "/Read"; private const string StreamWriteTag = nameof(Connection) + "/Write"; private static readonly Logger Logger = new Logger(typeof(Connection)); private readonly IStartupRequestFactory _startupRequestFactory; private readonly ITcpSocket _tcpSocket; private long _disposed; private volatile bool _isClosed; private readonly Timer _idleTimer; private long _timedOutOperations; /// <summary> /// Stores the available stream ids. /// </summary> private ConcurrentStack<short> _freeOperations; /// <summary> Contains the requests that were sent through the wire and that hasn't been received yet.</summary> private ConcurrentDictionary<short, OperationState> _pendingOperations; /// <summary> It contains the requests that have a streamid and are waiting to be written</summary> private ConcurrentQueue<OperationState> _writeQueue; private volatile string _keyspace; private TaskCompletionSource<bool> _keyspaceSwitchTcs; /// <summary> /// Small buffer (less than 8 bytes) that is used when the next received message is smaller than 8 bytes, /// and it is not possible to read the header. /// </summary> private byte[] _minHeaderBuffer; private ISerializer _serializer; private int _frameHeaderSize; private MemoryStream _readStream; private FrameHeader _receivingHeader; private int _writeState = Connection.WriteStateInit; private int _inFlight; private readonly IConnectionObserver _connectionObserver; private readonly bool _timerEnabled; private readonly int _heartBeatInterval; /// <summary> /// The event that represents a event RESPONSE from a Cassandra node /// </summary> public event CassandraEventHandler CassandraEventResponse; /// <summary> /// Event raised when there is an error when executing the request to prevent idle disconnects /// </summary> public event Action<Exception> OnIdleRequestException; /// <summary> /// Event that gets raised when a write has been completed. Testing purposes only. /// </summary> public event Action WriteCompleted; /// <summary> /// Event that gets raised the connection is being closed. /// </summary> public event Action<IConnection> Closing; private const string IdleQuery = "SELECT key from system.local"; private const long CoalescingThreshold = 8000; public ISerializer Serializer => Volatile.Read(ref _serializer); public IFrameCompressor Compressor { get; set; } public IConnectionEndPoint EndPoint => _tcpSocket.EndPoint; public IPEndPoint LocalAddress => _tcpSocket.GetLocalIpEndPoint(); public int WriteQueueLength => _writeQueue.Count; public int PendingOperationsMapLength => _pendingOperations.Count; /// <summary> /// Determines the amount of operations that are not finished. /// </summary> public virtual int InFlight => Volatile.Read(ref _inFlight); /// <summary> /// Determines if there isn't any operations pending to be written or inflight. /// </summary> public virtual bool HasPendingOperations { get { return InFlight > 0 || !_writeQueue.IsEmpty; } } /// <summary> /// Gets the amount of operations that timed out and didn't get a response /// </summary> public virtual int TimedOutOperations { get { return (int)Interlocked.Read(ref _timedOutOperations); } } /// <summary> /// Determine if the Connection has been explicitly disposed /// </summary> public bool IsDisposed { get { return Interlocked.Read(ref _disposed) > 0L; } } /// <summary> /// Gets the current keyspace. /// </summary> public string Keyspace { get { return _keyspace; } } public ProtocolOptions Options => Configuration.ProtocolOptions; public Configuration Configuration { get; set; } internal Connection( ISerializer serializer, IConnectionEndPoint endPoint, Configuration configuration, IStartupRequestFactory startupRequestFactory, IConnectionObserver connectionObserver) { _serializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); Configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); _startupRequestFactory = startupRequestFactory ?? throw new ArgumentNullException(nameof(startupRequestFactory)); _heartBeatInterval = configuration.GetHeartBeatInterval() ?? 0; _tcpSocket = new TcpSocket(endPoint, configuration.SocketOptions, configuration.ProtocolOptions.SslOptions); _idleTimer = new Timer(IdleTimeoutHandler, null, Timeout.Infinite, Timeout.Infinite); _connectionObserver = connectionObserver; _timerEnabled = configuration.MetricsEnabled && configuration.MetricsOptions.EnabledNodeMetrics.Contains(NodeMetric.Timers.CqlMessages); _freeOperations = new ConcurrentStack<short>(Enumerable.Range(0, GetMaxConcurrentRequests(Serializer)).Select(s => (short)s).Reverse()); _pendingOperations = new ConcurrentDictionary<short, OperationState>(); _writeQueue = new ConcurrentQueue<OperationState>(); if (Options.CustomCompressor != null) { Compressor = Options.CustomCompressor; } else if (Options.Compression == CompressionType.LZ4) { Compressor = new LZ4Compressor(); } else if (Options.Compression == CompressionType.Snappy) { Compressor = new SnappyCompressor(); } } private void IncrementInFlight() { Interlocked.Increment(ref _inFlight); } private void DecrementInFlight() { Interlocked.Decrement(ref _inFlight); } /// <summary> /// Gets the amount of concurrent requests depending on the protocol version /// </summary> public int GetMaxConcurrentRequests(ISerializer serializer) { if (!serializer.ProtocolVersion.Uses2BytesStreamIds()) { return 128; } //Protocol 3 supports up to 32K concurrent request without waiting a response //Allowing larger amounts of concurrent requests will cause large memory consumption //Limit to 2K per connection sounds reasonable. return 2048; } /// <summary> /// Starts the authentication flow /// </summary> /// <param name="name">Authenticator name from server.</param> /// <exception cref="AuthenticationException" /> private async Task<Response> StartAuthenticationFlow(string name) { //Determine which authentication flow to use. //Check if its using a C* 1.2 with authentication patched version (like DSE 3.1) var protocolVersion = Serializer.ProtocolVersion; var isPatchedVersion = protocolVersion == ProtocolVersion.V1 && !(Configuration.AuthProvider is NoneAuthProvider) && Configuration.AuthInfoProvider == null; if (protocolVersion == ProtocolVersion.V1 && !isPatchedVersion) { //Use protocol v1 authentication flow if (Configuration.AuthInfoProvider == null) { throw new AuthenticationException( $"Host {EndPoint.EndpointFriendlyName} requires authentication, but no credentials provided in Cluster configuration", EndPoint.GetHostIpEndPointWithFallback()); } var credentialsProvider = Configuration.AuthInfoProvider; var credentials = credentialsProvider.GetAuthInfos(EndPoint.GetHostIpEndPointWithFallback()); var request = new CredentialsRequest(credentials); var response = await Send(request).ConfigureAwait(false); if (!(response is ReadyResponse)) { //If Cassandra replied with a auth response error //The task already is faulted and the exception was already thrown. throw new ProtocolErrorException("Expected SASL response, obtained " + response.GetType().Name); } return response; } //Use protocol v2+ authentication flow if (Configuration.AuthProvider is IAuthProviderNamed) { //Provide name when required ((IAuthProviderNamed)Configuration.AuthProvider).SetName(name); } //NewAuthenticator will throw AuthenticationException when NoneAuthProvider var authenticator = Configuration.AuthProvider.NewAuthenticator(EndPoint.GetHostIpEndPointWithFallback()); var initialResponse = authenticator.InitialResponse() ?? new byte[0]; return await Authenticate(initialResponse, authenticator).ConfigureAwait(false); } /// <exception cref="AuthenticationException" /> private async Task<Response> Authenticate(byte[] token, IAuthenticator authenticator) { var request = new AuthResponseRequest(token); var response = await Send(request).ConfigureAwait(false); if (response is AuthSuccessResponse) { // It is now authenticated, dispose Authenticator if it implements IDisposable() // ReSharper disable once SuspiciousTypeConversion.Global var disposableAuthenticator = authenticator as IDisposable; if (disposableAuthenticator != null) { disposableAuthenticator.Dispose(); } return response; } if (response is AuthChallengeResponse) { token = authenticator.EvaluateChallenge(((AuthChallengeResponse)response).Token); if (token == null) { // If we get a null response, then authentication has completed // return without sending a further response back to the server. return response; } return await Authenticate(token, authenticator).ConfigureAwait(false); } throw new ProtocolErrorException("Expected SASL response, obtained " + response.GetType().Name); } private void CloseInternal(Exception ex, SocketError? socketError, bool dispose) { _isClosed = true; var wasClosed = Interlocked.Exchange(ref _writeState, Connection.WriteStateClosed) == Connection.WriteStateClosed; if (!wasClosed) { Closing?.Invoke(this); Connection.Logger.Info("Cancelling in Connection #{0} to {1}, {2} pending operations and write queue {3}", GetHashCode(), EndPoint.EndpointFriendlyName, InFlight, _writeQueue.Count); if (socketError != null) { Connection.Logger.Verbose("The socket status received was {0}", socketError.Value); } if (ex != null) { Connection.Logger.Verbose("The exception received was {0}", ex.ToString()); } } if (!_writeQueue.IsEmpty || !_pendingOperations.IsEmpty) { if (ex == null || ex is ObjectDisposedException) { ex = socketError != null ? new SocketException((int)socketError.Value) : new SocketException((int)SocketError.NotConnected); } // Dequeue all the items in the write queue var ops = new LinkedList<OperationState>(); OperationState state; while (_writeQueue.TryDequeue(out state)) { ops.AddLast(state); } // Remove every pending operation while (!_pendingOperations.IsEmpty) { Interlocked.MemoryBarrier(); // Remove using a snapshot of the keys var keys = _pendingOperations.Keys.ToArray(); foreach (var key in keys) { if (_pendingOperations.TryRemove(key, out state)) { ops.AddLast(state); } } } Interlocked.MemoryBarrier(); OperationState.CallbackMultiple(ops, RequestError.CreateClientError(ex, false), GetTimestamp()); } Interlocked.Exchange(ref _inFlight, 0); if (dispose) { InternalDispose(); } } private void OnSocketError(Exception ex, SocketError? socketError) { CloseInternal(ex, socketError, false); } public virtual void Dispose() { CloseInternal(null, null, true); } /// <inheritdoc /> public void Close() { CloseInternal(null, null, false); } private void InternalDispose() { if (Interlocked.Increment(ref _disposed) != 1) { //Only dispose once return; } Connection.Logger.Verbose("Disposing Connection #{0} to {1}.", GetHashCode(), EndPoint.EndpointFriendlyName); _idleTimer.Dispose(); _tcpSocket.Dispose(); var readStream = Interlocked.Exchange(ref _readStream, null); if (readStream != null) { readStream.Dispose(); } } private void EventHandler(IRequestError error, Response response, long timestamp) { if (!(response is EventResponse)) { Connection.Logger.Error("Unexpected response type for event: " + response.GetType().Name); return; } CassandraEventResponse?.Invoke(this, ((EventResponse)response).CassandraEventArgs); } /// <summary> /// Gets executed once the idle timeout has passed /// </summary> private void IdleTimeoutHandler(object state) { //Ensure there are no more idle timeouts until the query finished sending if (_isClosed) { if (!IsDisposed) { //If it was not manually disposed Connection.Logger.Info("Can not issue an heartbeat request as connection is closed"); OnIdleRequestException?.Invoke(new SocketException((int)SocketError.NotConnected)); } return; } Connection.Logger.Verbose("Connection #{0} to {1} idling, issuing a Request to prevent idle disconnects", GetHashCode(), EndPoint.EndpointFriendlyName); var request = new OptionsRequest(); Send(request, (error, response) => { if (error?.Exception == null) { //The send succeeded //There is a valid response but we don't care about the response return; } Connection.Logger.Warning("Received heartbeat request exception " + error.Exception.ToString()); if (error.Exception is SocketException) { OnIdleRequestException?.Invoke(error.Exception); } }); } /// <summary> /// Initializes the connection. /// </summary> /// <exception cref="SocketException">Throws a SocketException when the connection could not be established with the host</exception> /// <exception cref="AuthenticationException" /> /// <exception cref="UnsupportedProtocolVersionException"></exception> public async Task<Response> Open() { try { Connection.Logger.Verbose("Attempting to open Connection #{0} to {1}", GetHashCode(), EndPoint.EndpointFriendlyName); var response = await DoOpen().ConfigureAwait(false); Connection.Logger.Verbose("Opened Connection #{0} to {1} with local endpoint {2}.", GetHashCode(), EndPoint.EndpointFriendlyName, _tcpSocket.GetLocalIpEndPoint()?.ToString()); return response; } catch (Exception exception) { _connectionObserver.OnErrorOnOpen(exception); throw; } } /// <summary> /// Initializes the connection. /// </summary> /// <exception cref="SocketException">Throws a SocketException when the connection could not be established with the host</exception> /// <exception cref="AuthenticationException" /> /// <exception cref="UnsupportedProtocolVersionException"></exception> public async Task<Response> DoOpen() { //Init TcpSocket _tcpSocket.Error += OnSocketError; _tcpSocket.Closing += Dispose; //Read and write event handlers are going to be invoked using IO Threads _tcpSocket.Read += ReadHandler; _tcpSocket.WriteCompleted += WriteCompletedHandler; var protocolVersion = Serializer.ProtocolVersion; await _tcpSocket.Connect().ConfigureAwait(false); Response response; try { response = await Startup().ConfigureAwait(false); } catch (ProtocolErrorException ex) { // As we are starting up, check for protocol version errors. // There is no other way than checking the error message from Cassandra if (ex.Message.Contains("Invalid or unsupported protocol version")) { throw new UnsupportedProtocolVersionException(protocolVersion, Serializer.ProtocolVersion, ex); } throw; } if (response is AuthenticateResponse) { return await StartAuthenticationFlow(((AuthenticateResponse)response).Authenticator) .ConfigureAwait(false); } if (response is ReadyResponse) { return response; } throw new DriverInternalError("Expected READY or AUTHENTICATE, obtained " + response.GetType().Name); } private void ReadHandler(byte[] buffer, int bytesReceived) { if (_isClosed) { //All pending operations have been canceled, there is no point in reading from the wire. return; } _connectionObserver.OnBytesReceived(bytesReceived); //We are currently using an IO Thread //Parse the data received var streamIdAvailable = ReadParse(buffer, bytesReceived); if (!streamIdAvailable) { return; } //Process a next item in the queue if possible. //Maybe there are there items in the write queue that were waiting on a fresh streamId RunWriteQueue(); } /// <summary> /// Deserializes each frame header and copies the body bytes into a single buffer. /// </summary> /// <returns>True if a full operation (streamId) has been processed.</returns> internal bool ReadParse(byte[] buffer, int length) { if (length <= 0) { return false; } // Check if protocol version has already been determined (first message) ProtocolVersion protocolVersion; var headerLength = Volatile.Read(ref _frameHeaderSize); var serializer = Volatile.Read(ref _serializer); if (headerLength == 0) { // The server replies the first message with the max protocol version supported protocolVersion = FrameHeader.GetProtocolVersion(buffer); serializer = serializer.CloneWithProtocolVersion(protocolVersion); headerLength = protocolVersion.GetHeaderSize(); Volatile.Write(ref _serializer, serializer); Volatile.Write(ref _frameHeaderSize, headerLength); _frameHeaderSize = headerLength; } else { protocolVersion = serializer.ProtocolVersion; } // Use _readStream to buffer between messages, when the body is not contained in a single read call var stream = Interlocked.Exchange(ref _readStream, null); var previousHeader = Interlocked.Exchange(ref _receivingHeader, null); if (previousHeader != null && stream == null) { // This connection has been disposed return false; } var operationCallbacks = new LinkedList<Action<MemoryStream, long>>(); var offset = 0; while (offset < length) { FrameHeader header; int remainingBodyLength; // check if header has not been read yet if (previousHeader == null) { header = ReadHeader(buffer, ref offset, length, headerLength, protocolVersion); if (header == null) { // There aren't enough bytes to read the header break; } Connection.Logger.Verbose("Received #{0} from {1}", header.StreamId, EndPoint.EndpointFriendlyName); remainingBodyLength = header.BodyLength; } else { header = previousHeader; previousHeader = null; remainingBodyLength = header.BodyLength - (int)stream.Length; } if (remainingBodyLength > length - offset) { // The buffer does not contains the body for the current frame, store it for later StoreReadState(header, stream, buffer, offset, length, operationCallbacks.Count > 0); break; } // Get read stream stream = stream ?? Configuration.BufferPool.GetStream(Connection.StreamReadTag); // Get callback and operation state Action<IRequestError, Response, long> callback; ResultMetadata resultMetadata = null; if (header.Opcode == EventResponse.OpCode) { callback = EventHandler; } else { var state = RemoveFromPending(header.StreamId); // State can be null when the Connection is being closed concurrently // The original callback is being called with an error, use a Noop here if (state == null) { callback = OperationState.Noop; } else { callback = state.SetCompleted(); resultMetadata = state.ResultMetadata; } } // Write to read stream stream.Write(buffer, offset, remainingBodyLength); // Add callback with deserialize from stream operationCallbacks.AddLast(CreateResponseAction(resultMetadata, serializer, header, callback)); offset += remainingBodyLength; } // Invoke callbacks with read stream return Connection.InvokeReadCallbacks(stream, operationCallbacks, GetTimestamp()); } /// <summary> /// Reads the header from the buffer, using previous /// </summary> private FrameHeader ReadHeader(byte[] buffer, ref int offset, int length, int headerLength, ProtocolVersion version) { if (offset == 0) { var previousHeaderBuffer = Interlocked.Exchange(ref _minHeaderBuffer, null); if (previousHeaderBuffer != null) { if (previousHeaderBuffer.Length + length < headerLength) { // Unlikely scenario where there were a few bytes for a header buffer and the new bytes are // not enough to complete the header Volatile.Write(ref _minHeaderBuffer, Utils.JoinBuffers(previousHeaderBuffer, 0, previousHeaderBuffer.Length, buffer, 0, length)); return null; } offset += headerLength - previousHeaderBuffer.Length; // Use the previous and the current buffer to build the header return FrameHeader.ParseResponseHeader(version, previousHeaderBuffer, buffer); } } if (length - offset < headerLength) { // There aren't enough bytes in the current buffer to read the header, store it for later Volatile.Write(ref _minHeaderBuffer, Utils.SliceBuffer(buffer, offset, length - offset)); return null; } // The header is contained in the current buffer var header = FrameHeader.ParseResponseHeader(version, buffer, offset); offset += headerLength; return header; } /// <summary> /// Saves the current read state (header and body stream) for the next read event. /// </summary> private void StoreReadState(FrameHeader header, MemoryStream stream, byte[] buffer, int offset, int length, bool hasReadFromStream) { MemoryStream nextMessageStream; if (!hasReadFromStream && stream != null) { // There hasn't been any operations completed with this buffer, reuse the current stream nextMessageStream = stream; } else { // Allocate a new stream for store in it nextMessageStream = Configuration.BufferPool.GetStream(Connection.StreamReadTag); } nextMessageStream.Write(buffer, offset, length - offset); Volatile.Write(ref _readStream, nextMessageStream); Volatile.Write(ref _receivingHeader, header); if (_isClosed) { // Connection was disposed since we started to store the buffer, try to dispose the stream Interlocked.Exchange(ref _readStream, null)?.Dispose(); } } /// <summary> /// Returns an action that capture the parameters closure /// </summary> private Action<MemoryStream, long> CreateResponseAction( ResultMetadata resultMetadata, ISerializer serializer, FrameHeader header, Action<IRequestError, Response, long> callback) { var compressor = Compressor; void DeserializeResponseStream(MemoryStream stream, long timestamp) { Response response = null; IRequestError error = null; var nextPosition = stream.Position + header.BodyLength; try { Stream plainTextStream = stream; if (header.Flags.HasFlag(HeaderFlags.Compression)) { plainTextStream = compressor.Decompress(new WrappedStream(stream, header.BodyLength)); plainTextStream.Position = 0; } response = FrameParser.Parse(new Frame(header, plainTextStream, serializer, resultMetadata)); } catch (Exception caughtException) { error = RequestError.CreateClientError(caughtException, false); } if (response is ErrorResponse errorResponse) { error = RequestError.CreateServerError(errorResponse); response = null; } //We must advance the position of the stream manually in case it was not correctly parsed stream.Position = nextPosition; callback(error, response, timestamp); } return DeserializeResponseStream; } /// <summary> /// Invokes the callbacks using the default TaskScheduler. /// </summary> /// <returns>Returns true if one or more callback has been invoked.</returns> private static bool InvokeReadCallbacks(MemoryStream stream, ICollection<Action<MemoryStream, long>> operationCallbacks, long timestamp) { if (operationCallbacks.Count == 0) { //Not enough data to read a frame return false; } //Invoke all callbacks using the default TaskScheduler Task.Factory.StartNew(() => { stream.Position = 0; foreach (var cb in operationCallbacks) { cb(stream, timestamp); } stream.Dispose(); }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); return true; } /// <summary> /// Sends a protocol STARTUP message /// </summary> private Task<Response> Startup() { var request = _startupRequestFactory.CreateStartupRequest(Options); // Use the Connect timeout for the startup request timeout return Send(request, Configuration.SocketOptions.ConnectTimeoutMillis); } /// <inheritdoc /> public Task<Response> Send(IRequest request, int timeoutMillis) { var tcs = new TaskCompletionSource<Response>(); Send(request, tcs.TrySetRequestError, timeoutMillis); return tcs.Task; } /// <inheritdoc /> public Task<Response> Send(IRequest request) { return Send(request, Configuration.DefaultRequestOptions.ReadTimeoutMillis); } /// <inheritdoc /> public OperationState Send(IRequest request, Action<IRequestError, Response> callback, int timeoutMillis) { if (_isClosed) { // Avoid calling back before returning Task.Factory.StartNew(() => callback(RequestError.CreateClientError(new SocketException((int)SocketError.NotConnected), true), null), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); return null; } IncrementInFlight(); var state = new OperationState( callback, request, timeoutMillis, _connectionObserver.CreateOperationObserver() ); if (state.TimeoutMillis > 0) { // timer can be disposed while connection cancellation hasn't been invoked yet try { var requestTimeout = Configuration.Timer.NewTimeout(OnTimeout, state, state.TimeoutMillis); state.SetTimeout(requestTimeout); } catch (Exception ex) { // Avoid calling back before returning Task.Factory.StartNew(() => callback(RequestError.CreateClientError(ex, true), null), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); return null; } } _writeQueue.Enqueue(state); RunWriteQueue(); return state; } /// <inheritdoc /> public OperationState Send(IRequest request, Action<IRequestError, Response> callback) { return Send(request, callback, Configuration.DefaultRequestOptions.ReadTimeoutMillis); } private void RunWriteQueue() { var previousState = Interlocked.CompareExchange(ref _writeState, Connection.WriteStateRunning, Connection.WriteStateInit); if (previousState == Connection.WriteStateRunning) { // There is another thread writing to the wire return; } if (previousState == Connection.WriteStateClosed) { // Probably there is an item in the write queue, we should cancel pending // Avoid canceling in the user thread Task.Factory.StartNew(Dispose, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); return; } // Start a new task using the TaskScheduler for writing to avoid using the User thread Task.Factory.StartNew(RunWriteQueueAction, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); } private long GetTimestamp() { return _timerEnabled ? Stopwatch.GetTimestamp() : 0L; } private void RunWriteQueueAction() { //Dequeue all items until threshold is passed long totalLength = 0; RecyclableMemoryStream stream = null; var timestamp = GetTimestamp(); while (totalLength < Connection.CoalescingThreshold) { OperationState state = null; while (_writeQueue.TryDequeue(out var tempState)) { if (tempState.CanBeWritten()) { state = tempState; break; } DecrementInFlight(); } if (state == null) { //No more items in the write queue break; } if (!_freeOperations.TryPop(out short streamId)) { //Queue it up for later. _writeQueue.Enqueue(state); //When receiving the next complete message, we can process it. Connection.Logger.Info("Enqueued, no streamIds available. If this message is recurrent consider configuring more connections per host or lower the pressure"); break; } Connection.Logger.Verbose("Sending #{0} for {1} to {2}", streamId, state.Request.GetType().Name, EndPoint.EndpointFriendlyName); if (_isClosed) { DecrementInFlight(); state.InvokeCallback(RequestError.CreateClientError(new SocketException((int)SocketError.NotConnected), true), timestamp); break; } _pendingOperations.AddOrUpdate(streamId, state, (k, oldValue) => state); var startLength = stream?.Length ?? 0; try { //lazy initialize the stream stream = stream ?? (RecyclableMemoryStream)Configuration.BufferPool.GetStream(Connection.StreamWriteTag); var frameLength = state.WriteFrame(streamId, stream, Serializer, timestamp); _connectionObserver.OnBytesSent(frameLength); totalLength += frameLength; } catch (Exception ex) { //There was an error while serializing or begin sending Connection.Logger.Error(ex); //The request was not written, clear it from pending operations RemoveFromPending(streamId); //Callback with the Exception state.InvokeCallback(RequestError.CreateClientError(ex, true), timestamp); //Reset the stream to before we started writing this frame stream?.SetLength(startLength); break; } } if (totalLength == 0L) { // Nothing to write, set the queue as not running Interlocked.CompareExchange(ref _writeState, Connection.WriteStateInit, Connection.WriteStateRunning); // Until now, we were preventing other threads to running the queue. // Check if we can now write: // a read could have finished (freeing streamIds) or new request could have been added to the queue if (!_freeOperations.IsEmpty && !_writeQueue.IsEmpty) { //The write queue is not empty //An item was added to the queue but we were running: try to launch a new queue RunWriteQueue(); } if (stream != null) { //The stream instance could be created if there was an exception while generating the frame stream.Dispose(); } return; } //Write and close the stream when flushed // ReSharper disable once PossibleNullReferenceException : if totalLength > 0 the stream is initialized _tcpSocket.Write(stream, () => stream.Dispose()); } /// <summary> /// Removes an operation from pending and frees the stream id /// </summary> /// <param name="streamId"></param> protected internal virtual OperationState RemoveFromPending(short streamId) { if (_pendingOperations.TryRemove(streamId, out var state)) { DecrementInFlight(); } //Set the streamId as available _freeOperations.Push(streamId); return state; } /// <summary> /// Sets the keyspace of the connection. /// If the keyspace is different from the current value, it sends a Query request to change it /// </summary> public async Task<bool> SetKeyspace(string value) { if (string.IsNullOrEmpty(value)) { return true; } while (_keyspace != value) { var switchTcs = Volatile.Read(ref _keyspaceSwitchTcs); if (switchTcs != null) { // Is already switching await switchTcs.Task.ConfigureAwait(false); continue; } var tcs = new TaskCompletionSource<bool>(); switchTcs = Interlocked.CompareExchange(ref _keyspaceSwitchTcs, tcs, null); if (switchTcs != null) { // Is already switching await switchTcs.Task.ConfigureAwait(false); continue; } Exception sendException = null; // CAS operation won, this is the only thread changing the keyspace // but another thread might have changed it in the meantime if (_keyspace != value) { Connection.Logger.Info("Connection to host {0} switching to keyspace {1}", EndPoint.EndpointFriendlyName, value); var request = new QueryRequest(Serializer, $"USE \"{value}\"", QueryProtocolOptions.Default, false, null); try { await Send(request).ConfigureAwait(false); _keyspace = value; } catch (Exception ex) { sendException = ex; } } // Set the reference to null before setting the result Interlocked.Exchange(ref _keyspaceSwitchTcs, null); tcs.TrySet(sendException, true); return await tcs.Task.ConfigureAwait(false); } return true; } private void OnTimeout(object stateObj) { var state = (OperationState)stateObj; var ex = new OperationTimedOutException(EndPoint, state.TimeoutMillis); //Invoke if it hasn't been invoked yet //Once the response is obtained, we decrement the timed out counter var timedout = state.MarkAsTimedOut(ex, () => Interlocked.Decrement(ref _timedOutOperations), GetTimestamp()); if (!timedout) { //The response was obtained since the timer elapsed, move on return; } //Increase timed-out counter Interlocked.Increment(ref _timedOutOperations); } /// <summary> /// Method that gets executed when a write request has been completed. /// </summary> protected virtual void WriteCompletedHandler() { //This handler is invoked by IO threads //Make it quick WriteCompleted?.Invoke(); //There is no need for synchronization here //Only 1 thread can be here at the same time. //Set the idle timeout to avoid idle disconnects if (_heartBeatInterval > 0 && !_isClosed) { try { _idleTimer.Change(_heartBeatInterval, Timeout.Infinite); } catch (ObjectDisposedException) { //This connection is being disposed //Don't mind } } Interlocked.CompareExchange(ref _writeState, Connection.WriteStateInit, Connection.WriteStateRunning); //Send the next request, if exists //It will use a new thread RunWriteQueue(); } } }
using System; using System.Configuration; using System.Data; namespace Sqloogle.Libs.Rhino.Etl.Core.Infrastructure { /// <summary> /// Helper class to provide simple data access, when we want to access the ADO.Net /// library directly. /// </summary> public static class Use { #region Delegates /// <summary> /// Delegate to execute an action with a command /// and return a result: <typeparam name="T"/> /// </summary> public delegate T Func<T>(IDbCommand command); /// <summary> /// Delegate to execute an action with a command /// </summary> public delegate void Proc(IDbCommand command); #endregion private static readonly object activeConnectionKey = new object(); private static readonly object activeTransactionKey = new object(); private static readonly object transactionCounterKey = new object(); /// <summary> /// Gets or sets the active connection. /// </summary> /// <value>The active connection.</value> [ThreadStatic] private static IDbConnection ActiveConnection; /// <summary> /// Gets or sets the active transaction. /// </summary> /// <value>The active transaction.</value> [ThreadStatic] private static IDbTransaction ActiveTransaction; /// <summary> /// Gets or sets the transaction counter. /// </summary> /// <value>The transaction counter.</value> [ThreadStatic] private static int TransactionCounter; /// <summary> /// Execute the specified delegate inside a transaction and return /// the result of the delegate. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="connectionStringName">The name of the named connection string in the configuration file</param> /// <param name="actionToExecute">The action to execute</param> /// <returns></returns> public static T Transaction<T>(string connectionStringName, Func<T> actionToExecute) { T result = default(T); ConnectionStringSettings connectionStringSettings = ConfigurationManager.ConnectionStrings[connectionStringName]; if (connectionStringSettings == null) throw new InvalidOperationException("Could not find connnection string: " + connectionStringName); Transaction(connectionStringSettings, delegate(IDbCommand command) { result = actionToExecute(command); }); return result; } /// <summary> /// Execute the specified delegate inside a transaction and return /// the result of the delegate. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="connectionStringSettings">The connection string settings to use for the connection</param> /// <param name="actionToExecute">The action to execute</param> /// <returns></returns> public static T Transaction<T>(ConnectionStringSettings connectionStringSettings, Func<T> actionToExecute) { T result = default(T); Transaction(connectionStringSettings, delegate(IDbCommand command) { result = actionToExecute(command); }); return result; } /// <summary> /// Execute the specified delegate inside a transaction /// </summary> /// <param name="connectionStringName">Name of the connection string.</param> /// <param name="actionToExecute">The action to execute.</param> public static void Transaction(string connectionStringName, Proc actionToExecute) { ConnectionStringSettings connectionStringSettings = ConfigurationManager.ConnectionStrings[connectionStringName]; if (connectionStringSettings == null) throw new InvalidOperationException("Could not find connnection string: " + connectionStringName); Transaction(connectionStringSettings, IsolationLevel.Unspecified, actionToExecute); } /// <summary> /// Execute the specified delegate inside a transaction /// </summary> /// <param name="connectionStringSettings">The connection string settings to use for the connection</param> /// <param name="actionToExecute">The action to execute.</param> public static void Transaction(ConnectionStringSettings connectionStringSettings, Proc actionToExecute) { Transaction(connectionStringSettings, IsolationLevel.Unspecified, actionToExecute); } /// <summary> /// Execute the specified delegate inside a transaction with the specific /// isolation level /// </summary> /// <param name="connectionStringName">Name of the connection string.</param> /// <param name="isolationLevel">The isolation level.</param> /// <param name="actionToExecute">The action to execute.</param> public static void Transaction(string connectionStringName, IsolationLevel isolationLevel, Proc actionToExecute) { ConnectionStringSettings connectionStringSettings = ConfigurationManager.ConnectionStrings[connectionStringName]; if (connectionStringSettings == null) throw new InvalidOperationException("Could not find connnection string: " + connectionStringName); Transaction(connectionStringSettings, isolationLevel, actionToExecute); } /// <summary> /// Execute the specified delegate inside a transaction with the specific /// isolation level /// </summary> /// <param name="connectionStringSettings">Connection string settings node to use for the connection</param> /// <param name="isolationLevel">The isolation level.</param> /// <param name="actionToExecute">The action to execute.</param> public static void Transaction(ConnectionStringSettings connectionStringSettings, IsolationLevel isolationLevel, Proc actionToExecute) { StartTransaction(connectionStringSettings, isolationLevel); try { using (IDbCommand command = ActiveConnection.CreateCommand()) { command.Transaction = ActiveTransaction; actionToExecute(command); } CommitTransaction(); } catch { RollbackTransaction(); throw; } finally { DisposeTransaction(); } } /// <summary> /// Disposes the transaction. /// </summary> private static void DisposeTransaction() { if (TransactionCounter <= 0) { ActiveConnection.Dispose(); ActiveConnection = null; } } /// <summary> /// Rollbacks the transaction. /// </summary> private static void RollbackTransaction() { ActiveTransaction.Rollback(); ActiveTransaction.Dispose(); ActiveTransaction = null; TransactionCounter = 0; } /// <summary> /// Commits the transaction. /// </summary> private static void CommitTransaction() { TransactionCounter--; if (TransactionCounter == 0 && ActiveTransaction != null) { ActiveTransaction.Commit(); ActiveTransaction.Dispose(); ActiveTransaction = null; } } /// <summary> /// Starts the transaction. /// </summary> /// <param name="connectionStringSettings">The connection string settings to use for the transaction</param> /// <param name="isolation">The isolation.</param> private static void StartTransaction(ConnectionStringSettings connectionStringSettings, IsolationLevel isolation) { if (TransactionCounter <= 0) { TransactionCounter = 0; ActiveConnection = Connection(connectionStringSettings); ActiveTransaction = ActiveConnection.BeginTransaction(isolation); } TransactionCounter++; } /// <summary> /// Creates an open connection for a given named connection string, using the provider name /// to select the proper implementation /// </summary> /// <param name="name">The name.</param> /// <returns>The open connection</returns> public static IDbConnection Connection(string name) { ConnectionStringSettings connectionString = ConfigurationManager.ConnectionStrings[name]; if (connectionString == null) throw new InvalidOperationException("Could not find connnection string: " + name); return Connection(connectionString); } /// <summary> /// Creates an open connection for a given connection string setting, using the provider /// name of select the proper implementation /// </summary> /// <param name="connectionString">ConnectionStringSetting node</param> /// <returns>The open connection</returns> public static IDbConnection Connection(ConnectionStringSettings connectionString) { if (connectionString == null) throw new InvalidOperationException("Null ConnectionStringSettings specified"); Type type = Type.GetType(connectionString.ProviderName); if (type == null) throw new InvalidOperationException("The type name '" + connectionString.ProviderName + "' could not be found for connection string: " + connectionString.Name); IDbConnection connection = (IDbConnection)Activator.CreateInstance(type); connection.ConnectionString = connectionString.ConnectionString; connection.Open(); return connection; } } }
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 MamIndicadorN class. /// </summary> [Serializable] public partial class MamIndicadorNCollection : ActiveList<MamIndicadorN, MamIndicadorNCollection> { public MamIndicadorNCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>MamIndicadorNCollection</returns> public MamIndicadorNCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { MamIndicadorN 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 MAM_IndicadorN table. /// </summary> [Serializable] public partial class MamIndicadorN : ActiveRecord<MamIndicadorN>, IActiveRecord { #region .ctors and Default Settings public MamIndicadorN() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public MamIndicadorN(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public MamIndicadorN(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public MamIndicadorN(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("MAM_IndicadorN", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdIndicadorN = new TableSchema.TableColumn(schema); colvarIdIndicadorN.ColumnName = "idIndicadorN"; colvarIdIndicadorN.DataType = DbType.Int32; colvarIdIndicadorN.MaxLength = 0; colvarIdIndicadorN.AutoIncrement = true; colvarIdIndicadorN.IsNullable = false; colvarIdIndicadorN.IsPrimaryKey = true; colvarIdIndicadorN.IsForeignKey = false; colvarIdIndicadorN.IsReadOnly = false; colvarIdIndicadorN.DefaultSetting = @""; colvarIdIndicadorN.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdIndicadorN); TableSchema.TableColumn colvarDescripcion = new TableSchema.TableColumn(schema); colvarDescripcion.ColumnName = "descripcion"; colvarDescripcion.DataType = DbType.AnsiString; colvarDescripcion.MaxLength = 100; colvarDescripcion.AutoIncrement = false; colvarDescripcion.IsNullable = false; colvarDescripcion.IsPrimaryKey = false; colvarDescripcion.IsForeignKey = false; colvarDescripcion.IsReadOnly = false; colvarDescripcion.DefaultSetting = @"('')"; colvarDescripcion.ForeignKeyTableName = ""; schema.Columns.Add(colvarDescripcion); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("MAM_IndicadorN",schema); } } #endregion #region Props [XmlAttribute("IdIndicadorN")] [Bindable(true)] public int IdIndicadorN { get { return GetColumnValue<int>(Columns.IdIndicadorN); } set { SetColumnValue(Columns.IdIndicadorN, value); } } [XmlAttribute("Descripcion")] [Bindable(true)] public string Descripcion { get { return GetColumnValue<string>(Columns.Descripcion); } set { SetColumnValue(Columns.Descripcion, value); } } #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 varDescripcion) { MamIndicadorN item = new MamIndicadorN(); item.Descripcion = varDescripcion; 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 varIdIndicadorN,string varDescripcion) { MamIndicadorN item = new MamIndicadorN(); item.IdIndicadorN = varIdIndicadorN; item.Descripcion = varDescripcion; 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 IdIndicadorNColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn DescripcionColumn { get { return Schema.Columns[1]; } } #endregion #region Columns Struct public struct Columns { public static string IdIndicadorN = @"idIndicadorN"; public static string Descripcion = @"descripcion"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
/* * 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 <[email protected]> */ using System; using System.IO; using Net.Pkcs11Interop.Common; using Net.Pkcs11Interop.LowLevelAPI40; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Net.Pkcs11Interop.Tests.LowLevelAPI40 { /// <summary> /// C_SignInit, C_Sign, C_SignUpdate, C_SignFinal, C_VerifyInit, C_Verify, C_VerifyUpdate and C_VerifyFinal tests. /// </summary> [TestClass] public class _21_SignAndVerifyTest { /// <summary> /// C_SignInit, C_Sign, C_VerifyInit and C_Verify test with CKM_RSA_PKCS mechanism. /// </summary> [TestMethod] public void _01_SignAndVerifySinglePartTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); CKR rv = CKR.CKR_OK; using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath)) { rv = pkcs11.C_Initialize(Settings.InitArgs40); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present uint slotId = Helpers.GetUsableSlot(pkcs11); uint session = CK.CK_INVALID_HANDLE; rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Login as normal user rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt32(Settings.NormalUserPinArray.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate asymetric key pair uint pubKeyId = CK.CK_INVALID_HANDLE; uint privKeyId = CK.CK_INVALID_HANDLE; rv = Helpers.GenerateKeyPair(pkcs11, session, ref pubKeyId, ref privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Specify signing mechanism (needs no parameter => no unamanaged memory is needed) CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_SHA1_RSA_PKCS); // Initialize signing operation rv = pkcs11.C_SignInit(session, ref mechanism, privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world"); // Get length of signature in first call uint signatureLen = 0; rv = pkcs11.C_Sign(session, sourceData, Convert.ToUInt32(sourceData.Length), null, ref signatureLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(signatureLen > 0); // Allocate array for signature byte[] signature = new byte[signatureLen]; // Get signature in second call rv = pkcs11.C_Sign(session, sourceData, Convert.ToUInt32(sourceData.Length), signature, ref signatureLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Do something interesting with signature // Initialize verification operation rv = pkcs11.C_VerifyInit(session, ref mechanism, pubKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Verify signature rv = pkcs11.C_Verify(session, sourceData, Convert.ToUInt32(sourceData.Length), signature, Convert.ToUInt32(signature.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Do something interesting with verification result rv = pkcs11.C_DestroyObject(session, privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_DestroyObject(session, pubKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Logout(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } /// <summary> /// C_SignInit, C_SignUpdate, C_SignFinal, C_VerifyInit, C_VerifyUpdate and C_VerifyFinal test. /// </summary> [TestMethod] public void _02_SignAndVerifyMultiPartTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); CKR rv = CKR.CKR_OK; using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath)) { rv = pkcs11.C_Initialize(Settings.InitArgs40); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present uint slotId = Helpers.GetUsableSlot(pkcs11); uint session = CK.CK_INVALID_HANDLE; rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Login as normal user rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt32(Settings.NormalUserPinArray.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate asymetric key pair uint pubKeyId = CK.CK_INVALID_HANDLE; uint privKeyId = CK.CK_INVALID_HANDLE; rv = Helpers.GenerateKeyPair(pkcs11, session, ref pubKeyId, ref privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Specify signing mechanism (needs no parameter => no unamanaged memory is needed) CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_SHA1_RSA_PKCS); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world"); byte[] signature = null; // Multipart signature functions C_SignUpdate and C_SignFinal can be used i.e. for signing of streamed data using (MemoryStream inputStream = new MemoryStream(sourceData)) { // Initialize signing operation rv = pkcs11.C_SignInit(session, ref mechanism, privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Prepare buffer for source data part // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long byte[] part = new byte[8]; // Read input stream with source data int bytesRead = 0; while ((bytesRead = inputStream.Read(part, 0, part.Length)) > 0) { // Process each individual source data part rv = pkcs11.C_SignUpdate(session, part, Convert.ToUInt32(bytesRead)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } // Get the length of signature in first call uint signatureLen = 0; rv = pkcs11.C_SignFinal(session, null, ref signatureLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(signatureLen > 0); // Allocate array for signature signature = new byte[signatureLen]; // Get signature in second call rv = pkcs11.C_SignFinal(session, signature, ref signatureLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } // Do something interesting with signature // Multipart verification functions C_VerifyUpdate and C_VerifyFinal can be used i.e. for signature verification of streamed data using (MemoryStream inputStream = new MemoryStream(sourceData)) { // Initialize verification operation rv = pkcs11.C_VerifyInit(session, ref mechanism, pubKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Prepare buffer for source data part // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long byte[] part = new byte[8]; // Read input stream with source data int bytesRead = 0; while ((bytesRead = inputStream.Read(part, 0, part.Length)) > 0) { // Process each individual source data part rv = pkcs11.C_VerifyUpdate(session, part, Convert.ToUInt32(bytesRead)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } // Verify signature rv = pkcs11.C_VerifyFinal(session, signature, Convert.ToUInt32(signature.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } // Do something interesting with verification result rv = pkcs11.C_DestroyObject(session, privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_DestroyObject(session, pubKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Logout(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } } }
// // UnsavedRevision.cs // // Author: // Zachary Gramana <[email protected]> // // Copyright (c) 2014 Xamarin Inc // Copyright (c) 2014 .NET 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. // // // Copyright (c) 2014 Couchbase, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. // using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using Couchbase.Lite.Util; using Couchbase.Lite.Revisions; using Couchbase.Lite.Internal; using Microsoft.IO; namespace Couchbase.Lite { /// <summary> /// An unsaved Couchbase Lite Document Revision. /// </summary> public class UnsavedRevision : Revision, IDisposable { #region Constants private static readonly string Tag = typeof(UnsavedRevision).Name; #endregion #region Non-public Members IDictionary<String, Object> properties; String ParentRevisionID { get; set; } /// <summary>Creates or updates an attachment.</summary> /// <remarks> /// Creates or updates an attachment. /// The attachment data will be written to the database when the revision is saved. /// </remarks> /// <param name="attachment">A newly-created Attachment (not yet associated with any revision)</param> /// <param name="name">The attachment name.</param> internal void AddAttachment(Attachment attachment, string name) { var attachments = Properties.Get("_attachments").AsDictionary<string, object>() ?? new Dictionary<string, object>(); var oldAttach = attachments.GetCast<Attachment>(name); if(oldAttach != null) { oldAttach.Dispose(); } if(attachment == null) { attachments.Remove(name); } else { attachments[name] = attachment; } Properties["_attachments"] = attachments; if(attachment != null) { attachment.Name = name; } } #endregion #region Constructors internal UnsavedRevision(Document document, SavedRevision parentRevision) : base(document) { if(parentRevision == null) ParentRevisionID = null; else ParentRevisionID = parentRevision.Id; IDictionary<string, object> parentRevisionProperties; if(parentRevision == null) { parentRevisionProperties = null; } else { parentRevisionProperties = parentRevision.Properties; } if(parentRevisionProperties == null) { properties = new Dictionary<string, object>(); properties["_id"] = document.Id; if(ParentRevisionID != null) { properties.SetRevID(ParentRevisionID); } } else { properties = new Dictionary<string, object>(parentRevisionProperties); } } #endregion #region Instance Members /// <summary> /// Gets or sets if the <see cref="Couchbase.Lite.Revision"/> marks the deletion of its <see cref="Couchbase.Lite.Document"/>. /// </summary> /// <value> /// <c>true</c> if tthe <see cref="Couchbase.Lite.Revision"/> marks the deletion of its <see cref="Couchbase.Lite.Document"/>; /// otherwise, <c>false</c>. /// </value> public new bool IsDeletion { get { return base.IsDeletion; } set { if(value) { properties["_deleted"] = true; } else { properties.Remove("_deleted"); } } } /// <summary> /// Gets the parent <see cref="Couchbase.Lite.Revision"/>. /// </summary> /// <value>The parent.</value> public override SavedRevision Parent { get { return String.IsNullOrEmpty(ParentId) ? null : Document.GetRevision(ParentId); } } /// <summary> /// Gets the parent <see cref="Couchbase.Lite.Revision"/>'s Id. /// </summary> /// <value>The parent.</value> public override string ParentId { get { return ParentRevisionID; } } /// <summary>Returns the history of this document as an array of <see cref="Couchbase.Lite.Revision"/>s, in forward order.</summary> /// <remarks> /// Returns the history of this document as an array of <see cref="Couchbase.Lite.Revision"/>s, in forward order. /// Older, ancestor, revisions are not guaranteed to have their properties available. /// </remarks> /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> public override IEnumerable<SavedRevision> RevisionHistory { get { // (Don't include self in the array, because this revision doesn't really exist yet) return Parent != null ? Parent.RevisionHistory : new List<SavedRevision>(); } } /// <summary>Gets the Revision's id.</summary> public override String Id { get { return null; // Once a revision is saved, it gets an id, but also becomes a new SavedRevision instance. } } /// <summary> /// Gets the properties of the <see cref="Couchbase.Lite.Revision"/>. /// </summary> public override IDictionary<String, Object> Properties { get { return properties; } } /// <summary> /// Sets the properties of the <see cref="Couchbase.Lite.Revision"/>. /// </summary> /// <param name="newProperties">New properties.</param> public void SetProperties(IDictionary<String, Object> newProperties) { properties = newProperties; } /// <summary> /// Gets or sets the userProperties of the <see cref="Couchbase.Lite.Revision"/>. /// </summary> /// <remarks> /// Gets or sets the userProperties of the <see cref="Couchbase.Lite.Revision"/>. /// Get, returns the properties of the <see cref="Couchbase.Lite.Revision"/> /// without any properties with keys prefixed with '_' (which contain Couchbase Lite data). /// Set, replaces all properties except for those with keys prefixed with '_'. /// </remarks> /// <value>The userProperties of the <see cref="Couchbase.Lite.Revision"/>.</value> public void SetUserProperties(IDictionary<String, Object> userProperties) { var newProps = new Dictionary<String, Object>(); newProps.PutAll(userProperties); foreach(string key in Properties.Keys) { if(key.StartsWith("_", StringComparison.InvariantCultureIgnoreCase)) { newProps[key] = properties.Get(key); } } // Preserve metadata properties properties = newProps; } /// <summary> /// Saves the <see cref="Couchbase.Lite.UnsavedRevision"/>. /// This will fail if its parent is not the current <see cref="Couchbase.Lite.Revision"/> /// of the associated <see cref="Couchbase.Lite.Document"/>. /// </summary> /// <exception cref="Couchbase.Lite.CouchbaseLiteException"> /// Thrown if an issue occurs while saving the <see cref="Couchbase.Lite.UnsavedRevision"/>. /// </exception> public SavedRevision Save() { return Document.PutProperties(Properties, ParentId.AsRevID(), false); } /// <summary> /// Saves the <see cref="Couchbase.Lite.UnsavedRevision"/>, optionally allowing /// the save when there is a conflict. /// </summary> /// <param name="allowConflict"> /// Whether or not to allow saving when there is a conflict. /// </param> /// <exception cref="Couchbase.Lite.CouchbaseLiteException"> /// Thrown if an issue occurs while saving the <see cref="Couchbase.Lite.UnsavedRevision"/>. /// </exception> public SavedRevision Save(bool allowConflict) { return Document.PutProperties(Properties, ParentId.AsRevID(), allowConflict); } /// <summary> /// Sets the attachment with the given name. /// </summary> /// <remarks> /// Sets the <see cref="Couchbase.Lite.Attachment"/> with the given name. /// The <see cref="Couchbase.Lite.Attachment"/> data will be written to /// the <see cref="Couchbase.Lite.Database"/> when the /// <see cref="Couchbase.Lite.Revision"/> is saved. /// </remarks> /// <param name="name">The name of the <see cref="Couchbase.Lite.Attachment"/> to set.</param> /// <param name="contentType">The content-type of the <see cref="Couchbase.Lite.Attachment"/>.</param> /// <param name="content">The <see cref="Couchbase.Lite.Attachment"/> content.</param> public void SetAttachment(string name, string contentType, IEnumerable<byte> content) { var data = content?.ToArray(); if(data == null) { AddAttachment(null, name); return; } var stream = RecyclableMemoryStreamManager.SharedInstance.GetStream("UnsavedRevision", data, 0, data.Length); var attachment = new Attachment(stream, contentType); AddAttachment(attachment, name); } /// <summary> /// Sets the attachment with the given name. /// </summary> /// <remarks> /// Sets the <see cref="Couchbase.Lite.Attachment"/> with the given name. /// The <see cref="Couchbase.Lite.Attachment"/> data will be written to /// the <see cref="Couchbase.Lite.Database"/> when the /// <see cref="Couchbase.Lite.Revision"/> is saved. /// </remarks> /// <param name="name">The name of the <see cref="Couchbase.Lite.Attachment"/> to set.</param> /// <param name="contentType">The content-type of the <see cref="Couchbase.Lite.Attachment"/>.</param> /// <param name="content">The <see cref="Couchbase.Lite.Attachment"/> content.</param> public void SetAttachment(String name, String contentType, Stream content) { var attachment = new Attachment(content, contentType); AddAttachment(attachment, name); } /// <summary> /// Sets the attachment with the given name. /// </summary> /// <remarks> /// Sets the <see cref="Couchbase.Lite.Attachment"/> with the given name. /// The <see cref="Couchbase.Lite.Attachment"/> data will be written to /// the <see cref="Couchbase.Lite.Database"/> when the /// <see cref="Couchbase.Lite.Revision"/> is saved. /// </remarks> /// <param name="name">The name of the <see cref="Couchbase.Lite.Attachment"/> to set.</param> /// <param name="contentType">The content-type of the <see cref="Couchbase.Lite.Attachment"/>.</param> /// <param name="contentUrl">The URL of the <see cref="Couchbase.Lite.Attachment"/> content.</param> public void SetAttachment(String name, String contentType, Uri contentUrl) { try { byte[] inputBytes = null; var request = WebRequest.Create(contentUrl); using(var response = request.GetResponse()) using(var inputStream = response.GetResponseStream()) { var length = inputStream.Length; inputBytes = inputStream.ReadAllBytes(); } SetAttachment(name, contentType, inputBytes); } catch(IOException e) { throw Misc.CreateExceptionAndLog(Log.To.Database, e, Tag, "Error opening stream for url: {0}", contentUrl); } } /// <summary> /// Removes the <see cref="Couchbase.Lite.Attachment"/> /// with the given name. /// </summary> /// <remarks> /// Removes the <see cref="Couchbase.Lite.Attachment"/> with the given name. /// The <see cref="Couchbase.Lite.Attachment"/> will be deleted from the /// Database when the Revision is saved. /// </remarks> /// <param name="name"> /// The name of the <see cref="Couchbase.Lite.Attachment"/> to delete. /// </param> public void RemoveAttachment(String name) { AddAttachment(null, name); } #endregion #region Overrides #pragma warning disable 1591 public override string ToString() { var docId = Document == null ? "(null)" : Document.Id; return String.Format("UnsavedRevision[ID={0}, ParentRev={1}, Deletion={2}]", new SecureLogString(docId, LogMessageSensitivity.PotentiallyInsecure), ParentId, IsDeletion); } #endregion #region IDisposable /// <summary> /// Releases all resource used by the <see cref="Couchbase.Lite.UnsavedRevision"/> object. /// </summary> /// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="Couchbase.Lite.UnsavedRevision"/>. The /// <see cref="Dispose"/> method leaves the <see cref="Couchbase.Lite.UnsavedRevision"/> in an unusable state. /// After calling <see cref="Dispose"/>, you must release all references to the /// <see cref="Couchbase.Lite.UnsavedRevision"/> so the garbage collector can reclaim the memory that the /// <see cref="Couchbase.Lite.UnsavedRevision"/> was occupying.</remarks> public void Dispose() { var attachments = GetProperty("_attachments").AsDictionary<string, object>(); if(attachments == null) { return; } foreach(var pair in attachments) { var cast = pair.Value as IDisposable; if(cast != null) { cast.Dispose(); } } } #pragma warning restore 1591 #endregion } }
// Copyright 2017 Esri. // // 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 Android.App; using Android.OS; using Android.Views; using Android.Widget; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.UI.Controls; using System; namespace ArcGISRuntimeXamarin.Samples.ManageBookmarks { [Activity(Label = "ManageBookmarks")] public class ManageBookmarks : Activity { // MapView for the app private MapView _myMapView = new MapView(); // Dialog for entering the name of a new bookmark private AlertDialog _newBookmarkDialog = null; // Button to show available bookmarks (in a menu) Button _bookmarksButton; // Text input for the name of a new bookmark private EditText _bookmarkNameText; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); Title = "Manage bookmarks"; // Create the UI CreateLayout(); // Initialize the app Initialize(); } private void Initialize() { // Create a new map with a World Imagery base map var myMap = new Map(Basemap.CreateImageryWithLabels()); // Add the map to the MapView _myMapView.Map = myMap; // Create a set of predefined bookmarks; each one follows the pattern of: // ~ Initialize a viewpoint pointing to a latitude longitude // ~ Create a new bookmark // ~ Give the bookmark a name // ~ Assign the viewpoint // ~ Add the bookmark to bookmark collection of the map // Bookmark-1 Viewpoint myViewpoint1 = new Viewpoint(27.3805833, 33.6321389, 6000); Bookmark myBookmark1 = new Bookmark(); myBookmark1.Name = "Mysterious Desert Pattern"; myBookmark1.Viewpoint = myViewpoint1; _myMapView.Map.Bookmarks.Add(myBookmark1); // Bookmark-2 Viewpoint myViewpoint2 = new Viewpoint(37.401573, -116.867808, 6000); Bookmark myBookmark2 = new Bookmark(); myBookmark2.Name = "Strange Symbol"; myBookmark2.Viewpoint = myViewpoint2; _myMapView.Map.Bookmarks.Add(myBookmark2); // Bookmark-3 Viewpoint myViewpoint3 = new Viewpoint(-33.867886, -63.985, 40000); Bookmark myBookmark3 = new Bookmark(); myBookmark3.Name = "Guitar-Shaped Forest"; myBookmark3.Viewpoint = myViewpoint3; _myMapView.Map.Bookmarks.Add(myBookmark3); // Bookmark-4 Viewpoint myViewpoint4 = new Viewpoint(44.525049, -110.83819, 6000); Bookmark myBookmark4 = new Bookmark(); myBookmark4.Name = "Grand Prismatic Spring"; myBookmark4.Viewpoint = myViewpoint4; _myMapView.Map.Bookmarks.Add(myBookmark4); } private void CreateLayout() { // Create a new vertical layout for the app var layout = new LinearLayout(this) { Orientation = Orientation.Vertical }; // Create button to show bookmarks _bookmarksButton = new Button(this); _bookmarksButton.Text = "Bookmarks"; _bookmarksButton.Click += OnBookmarksClicked; // Add bookmarks button to the layout layout.AddView(_bookmarksButton); // Add the map view to the layout layout.AddView(_myMapView); // Show the layout in the app SetContentView(layout); } private void OnBookmarksClicked(object sender, EventArgs e) { // Create menu to show bookmarks var bookmarksMenu = new PopupMenu(this, _bookmarksButton); bookmarksMenu.MenuItemClick += OnBookmarksMenuItemClicked; // Create a menu option for each of the map's bookmarks foreach (Bookmark mark in _myMapView.Map.Bookmarks) { bookmarksMenu.Menu.Add(mark.Name); } // Add a final menu item for adding a new bookmark for the current viewpoint bookmarksMenu.Menu.Add("Add ..."); // Show menu in the view bookmarksMenu.Show(); } private void OnBookmarksMenuItemClicked(object sender, PopupMenu.MenuItemClickEventArgs e) { // Get title from the selected item var selectedBookmarkName = e.Item.TitleCondensedFormatted.ToString(); // If this is the "Add ..." choice, call a function to create a new bookmark if (selectedBookmarkName == "Add ...") { AddBookmark(); return; } // Get the collection of bookmarks in the map BookmarkCollection myBookmarkCollection = _myMapView.Map.Bookmarks; // Loop through bookmarks foreach (var myBookmark in myBookmarkCollection) { // Get this bookmark name var theBookmarkName = myBookmark.Name; // If this is the selected bookmark, use it to set the map's viewpoint if (theBookmarkName == selectedBookmarkName) { _myMapView.SetViewpoint(myBookmark.Viewpoint); // Set the name of the button to display the current bookmark _bookmarksButton.Text = selectedBookmarkName; break; } } } private void AddBookmark() { // Create a dialog for entering the bookmark name AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); // Create the layout LinearLayout dialogLayout = new LinearLayout(this); dialogLayout.Orientation = Orientation.Vertical; // Create a layout for the text entry LinearLayout nameTextLayout = new LinearLayout(this); nameTextLayout.Orientation = Orientation.Horizontal; // EditText control for entering the bookmark name _bookmarkNameText = new EditText(this); // Label for the text entry var nameLabel = new TextView(this); nameLabel.Text = "Name:"; // Add the controls to the layout nameTextLayout.AddView(nameLabel); nameTextLayout.AddView(_bookmarkNameText); // Create a layout for the dialog buttons (OK and Cancel) LinearLayout buttonLayout = new LinearLayout(this); buttonLayout.Orientation = Orientation.Horizontal; // Button to cancel the new bookmark var cancelButton = new Button(this); cancelButton.Text = "Cancel"; cancelButton.Click += (s, e) => _newBookmarkDialog.Dismiss(); // Button to save the current viewpoint as a new bookmark var okButton = new Button(this); okButton.Text = "OK"; okButton.Click += CreateNewBookmark; // Add the buttons to the layout buttonLayout.AddView(cancelButton); buttonLayout.AddView(okButton); // Build the dialog with the text control and button layouts dialogLayout.AddView(nameTextLayout); dialogLayout.AddView(buttonLayout); // Set dialog content dialogBuilder.SetView(dialogLayout); dialogBuilder.SetTitle("New Bookmark"); // Show the dialog _newBookmarkDialog = dialogBuilder.Show(); } // Handler for the click event of the New Bookmark dialog's OK button private void CreateNewBookmark(object sender, EventArgs e) { if (_newBookmarkDialog != null) { // See if the bookmark name conflicts with an existing name var bookmarkName = _bookmarkNameText.Text.Trim(); var nameExists = false; foreach (Bookmark bookmark in _myMapView.Map.Bookmarks) { // See if this bookmark exists (or conflicts with the "Add ..." menu choice) if (bookmarkName.ToLower() == bookmark.Name.ToLower() || bookmarkName.ToLower() == "add ...") { nameExists = true; break; } } // If the name is an empty string or exists in the collection, warn the user and return if (string.IsNullOrEmpty(bookmarkName) || nameExists) { AlertDialog.Builder dlgBuilder = new AlertDialog.Builder(this); dlgBuilder.SetTitle("Error"); dlgBuilder.SetMessage("Please enter a unique name for the bookmark."); dlgBuilder.Show(); return; } // Create a new bookmark Bookmark newBookmark = new Bookmark(); // Use the current viewpoint for the bookmark Viewpoint currentViewpoint = _myMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry); newBookmark.Viewpoint = currentViewpoint; // Set the name with the value entered by the user newBookmark.Name = bookmarkName; // Add the bookmark to the map's bookmark collection _myMapView.Map.Bookmarks.Add(newBookmark); // Show this bookmark name as the button text _bookmarksButton.Text = bookmarkName; // Dismiss the dialog for entering the bookmark name _newBookmarkDialog.Dismiss(); } } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace Invoices.Business { /// <summary> /// ProductEdit (editable root object).<br/> /// This is a generated <see cref="ProductEdit"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="Suppliers"/> of type <see cref="ProductSupplierColl"/> (1:M relation to <see cref="ProductSupplierItem"/>) /// </remarks> [Serializable] public partial class ProductEdit : BusinessBase<ProductEdit> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="ProductId"/> property. /// </summary> [NotUndoable] public static readonly PropertyInfo<Guid> ProductIdProperty = RegisterProperty<Guid>(p => p.ProductId, "Product Id"); /// <summary> /// Gets or sets the Product Id. /// </summary> /// <value>The Product Id.</value> public Guid ProductId { get { return GetProperty(ProductIdProperty); } set { SetProperty(ProductIdProperty, value); } } /// <summary> /// Maintains metadata about <see cref="ProductCode"/> property. /// </summary> public static readonly PropertyInfo<string> ProductCodeProperty = RegisterProperty<string>(p => p.ProductCode, "Product Code"); /// <summary> /// Gets or sets the Product Code. /// </summary> /// <value>The Product Code.</value> public string ProductCode { get { return GetProperty(ProductCodeProperty); } set { SetProperty(ProductCodeProperty, value); } } /// <summary> /// Maintains metadata about <see cref="Name"/> property. /// </summary> public static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(p => p.Name, "Name"); /// <summary> /// Gets or sets the Name. /// </summary> /// <value>The Name.</value> public string Name { get { return GetProperty(NameProperty); } set { SetProperty(NameProperty, value); } } /// <summary> /// Maintains metadata about <see cref="ProductTypeId"/> property. /// </summary> public static readonly PropertyInfo<int> ProductTypeIdProperty = RegisterProperty<int>(p => p.ProductTypeId, "Product Type Id"); /// <summary> /// Gets or sets the Product Type Id. /// </summary> /// <value>The Product Type Id.</value> public int ProductTypeId { get { return GetProperty(ProductTypeIdProperty); } set { SetProperty(ProductTypeIdProperty, value); } } /// <summary> /// Maintains metadata about <see cref="UnitCost"/> property. /// </summary> public static readonly PropertyInfo<string> UnitCostProperty = RegisterProperty<string>(p => p.UnitCost, "Unit Cost"); /// <summary> /// Gets or sets the Unit Cost. /// </summary> /// <value>The Unit Cost.</value> public string UnitCost { get { return GetProperty(UnitCostProperty); } set { SetProperty(UnitCostProperty, value); } } /// <summary> /// Maintains metadata about <see cref="StockByteNull"/> property. /// </summary> public static readonly PropertyInfo<byte?> StockByteNullProperty = RegisterProperty<byte?>(p => p.StockByteNull, "Stock Byte Null"); /// <summary> /// Gets or sets the Stock Byte Null. /// </summary> /// <value>The Stock Byte Null.</value> public byte? StockByteNull { get { return GetProperty(StockByteNullProperty); } set { SetProperty(StockByteNullProperty, value); } } /// <summary> /// Maintains metadata about <see cref="StockByte"/> property. /// </summary> public static readonly PropertyInfo<byte> StockByteProperty = RegisterProperty<byte>(p => p.StockByte, "Stock Byte"); /// <summary> /// Gets or sets the Stock Byte. /// </summary> /// <value>The Stock Byte.</value> public byte StockByte { get { return GetProperty(StockByteProperty); } set { SetProperty(StockByteProperty, value); } } /// <summary> /// Maintains metadata about <see cref="StockShortNull"/> property. /// </summary> public static readonly PropertyInfo<short?> StockShortNullProperty = RegisterProperty<short?>(p => p.StockShortNull, "Stock Short Null"); /// <summary> /// Gets or sets the Stock Short Null. /// </summary> /// <value>The Stock Short Null.</value> public short? StockShortNull { get { return GetProperty(StockShortNullProperty); } set { SetProperty(StockShortNullProperty, value); } } /// <summary> /// Maintains metadata about <see cref="StockShort"/> property. /// </summary> public static readonly PropertyInfo<short> StockShortProperty = RegisterProperty<short>(p => p.StockShort, "Stock Short"); /// <summary> /// Gets or sets the Stock Short. /// </summary> /// <value>The Stock Short.</value> public short StockShort { get { return GetProperty(StockShortProperty); } set { SetProperty(StockShortProperty, value); } } /// <summary> /// Maintains metadata about <see cref="StockIntNull"/> property. /// </summary> public static readonly PropertyInfo<int?> StockIntNullProperty = RegisterProperty<int?>(p => p.StockIntNull, "Stock Int Null"); /// <summary> /// Gets or sets the Stock Int Null. /// </summary> /// <value>The Stock Int Null.</value> public int? StockIntNull { get { return GetProperty(StockIntNullProperty); } set { SetProperty(StockIntNullProperty, value); } } /// <summary> /// Maintains metadata about <see cref="StockInt"/> property. /// </summary> public static readonly PropertyInfo<int> StockIntProperty = RegisterProperty<int>(p => p.StockInt, "Stock Int"); /// <summary> /// Gets or sets the Stock Int. /// </summary> /// <value>The Stock Int.</value> public int StockInt { get { return GetProperty(StockIntProperty); } set { SetProperty(StockIntProperty, value); } } /// <summary> /// Maintains metadata about <see cref="StockLongNull"/> property. /// </summary> public static readonly PropertyInfo<long?> StockLongNullProperty = RegisterProperty<long?>(p => p.StockLongNull, "Stock Long Null"); /// <summary> /// Gets or sets the Stock Long Null. /// </summary> /// <value>The Stock Long Null.</value> public long? StockLongNull { get { return GetProperty(StockLongNullProperty); } set { SetProperty(StockLongNullProperty, value); } } /// <summary> /// Maintains metadata about <see cref="StockLong"/> property. /// </summary> public static readonly PropertyInfo<long> StockLongProperty = RegisterProperty<long>(p => p.StockLong, "Stock Long"); /// <summary> /// Gets or sets the Stock Long. /// </summary> /// <value>The Stock Long.</value> public long StockLong { get { return GetProperty(StockLongProperty); } set { SetProperty(StockLongProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="Suppliers"/> property. /// </summary> public static readonly PropertyInfo<ProductSupplierColl> SuppliersProperty = RegisterProperty<ProductSupplierColl>(p => p.Suppliers, "Suppliers", RelationshipTypes.Child); /// <summary> /// Gets the Suppliers ("parent load" child property). /// </summary> /// <value>The Suppliers.</value> public ProductSupplierColl Suppliers { get { return GetProperty(SuppliersProperty); } private set { LoadProperty(SuppliersProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="ProductEdit"/> object. /// </summary> /// <returns>A reference to the created <see cref="ProductEdit"/> object.</returns> public static ProductEdit NewProductEdit() { return DataPortal.Create<ProductEdit>(); } /// <summary> /// Factory method. Loads a <see cref="ProductEdit"/> object, based on given parameters. /// </summary> /// <param name="productId">The ProductId parameter of the ProductEdit to fetch.</param> /// <returns>A reference to the fetched <see cref="ProductEdit"/> object.</returns> public static ProductEdit GetProductEdit(Guid productId) { return DataPortal.Fetch<ProductEdit>(productId); } /// <summary> /// Factory method. Asynchronously creates a new <see cref="ProductEdit"/> object. /// </summary> /// <param name="callback">The completion callback method.</param> public static void NewProductEdit(EventHandler<DataPortalResult<ProductEdit>> callback) { DataPortal.BeginCreate<ProductEdit>(callback); } /// <summary> /// Factory method. Asynchronously loads a <see cref="ProductEdit"/> object, based on given parameters. /// </summary> /// <param name="productId">The ProductId parameter of the ProductEdit to fetch.</param> /// <param name="callback">The completion callback method.</param> public static void GetProductEdit(Guid productId, EventHandler<DataPortalResult<ProductEdit>> callback) { DataPortal.BeginFetch<ProductEdit>(productId, callback); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="ProductEdit"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public ProductEdit() { // Use factory methods and do not use direct creation. } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="ProductEdit"/> object properties. /// </summary> [RunLocal] protected override void DataPortal_Create() { LoadProperty(ProductIdProperty, Guid.NewGuid()); LoadProperty(ProductCodeProperty, null); LoadProperty(SuppliersProperty, DataPortal.CreateChild<ProductSupplierColl>()); var args = new DataPortalHookArgs(); OnCreate(args); base.DataPortal_Create(); } /// <summary> /// Loads a <see cref="ProductEdit"/> object from the database, based on given criteria. /// </summary> /// <param name="productId">The Product Id.</param> protected void DataPortal_Fetch(Guid productId) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("Invoices")) { using (var cmd = new SqlCommand("dbo.GetProductEdit", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ProductId", productId).DbType = DbType.Guid; var args = new DataPortalHookArgs(cmd, productId); OnFetchPre(args); Fetch(cmd); OnFetchPost(args); } } // check all object rules and property rules BusinessRules.CheckRules(); } private void Fetch(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { if (dr.Read()) { Fetch(dr); FetchChildren(dr); } } } /// <summary> /// Loads a <see cref="ProductEdit"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(ProductIdProperty, dr.GetGuid("ProductId")); LoadProperty(ProductCodeProperty, dr.IsDBNull("ProductCode") ? null : dr.GetString("ProductCode")); LoadProperty(NameProperty, dr.GetString("Name")); LoadProperty(ProductTypeIdProperty, dr.GetInt32("ProductTypeId")); LoadProperty(UnitCostProperty, dr.GetString("UnitCost")); LoadProperty(StockByteNullProperty, (byte?)dr.GetValue("StockByteNull")); LoadProperty(StockByteProperty, dr.GetByte("StockByte")); LoadProperty(StockShortNullProperty, (short?)dr.GetValue("StockShortNull")); LoadProperty(StockShortProperty, dr.GetInt16("StockShort")); LoadProperty(StockIntNullProperty, (int?)dr.GetValue("StockIntNull")); LoadProperty(StockIntProperty, dr.GetInt32("StockInt")); LoadProperty(StockLongNullProperty, (long?)dr.GetValue("StockLongNull")); LoadProperty(StockLongProperty, dr.GetInt64("StockLong")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child objects from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void FetchChildren(SafeDataReader dr) { dr.NextResult(); LoadProperty(SuppliersProperty, DataPortal.FetchChild<ProductSupplierColl>(dr)); } /// <summary> /// Inserts a new <see cref="ProductEdit"/> object in the database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Insert() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("Invoices")) { using (var cmd = new SqlCommand("dbo.AddProductEdit", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ProductId", ReadProperty(ProductIdProperty)).DbType = DbType.Guid; cmd.Parameters.AddWithValue("@ProductCode", ReadProperty(ProductCodeProperty) == null ? (object)DBNull.Value : ReadProperty(ProductCodeProperty)).DbType = DbType.StringFixedLength; cmd.Parameters.AddWithValue("@Name", ReadProperty(NameProperty)).DbType = DbType.String; cmd.Parameters.AddWithValue("@ProductTypeId", ReadProperty(ProductTypeIdProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@UnitCost", ReadProperty(UnitCostProperty)).DbType = DbType.StringFixedLength; cmd.Parameters.AddWithValue("@StockByteNull", ReadProperty(StockByteNullProperty) == null ? (object)DBNull.Value : ReadProperty(StockByteNullProperty).Value).DbType = DbType.Byte; cmd.Parameters.AddWithValue("@StockByte", ReadProperty(StockByteProperty)).DbType = DbType.Byte; cmd.Parameters.AddWithValue("@StockShortNull", ReadProperty(StockShortNullProperty) == null ? (object)DBNull.Value : ReadProperty(StockShortNullProperty).Value).DbType = DbType.Int16; cmd.Parameters.AddWithValue("@StockShort", ReadProperty(StockShortProperty)).DbType = DbType.Int16; cmd.Parameters.AddWithValue("@StockIntNull", ReadProperty(StockIntNullProperty) == null ? (object)DBNull.Value : ReadProperty(StockIntNullProperty).Value).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@StockInt", ReadProperty(StockIntProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@StockLongNull", ReadProperty(StockLongNullProperty) == null ? (object)DBNull.Value : ReadProperty(StockLongNullProperty).Value).DbType = DbType.Int64; cmd.Parameters.AddWithValue("@StockLong", ReadProperty(StockLongProperty)).DbType = DbType.Int64; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="ProductEdit"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Update() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("Invoices")) { using (var cmd = new SqlCommand("dbo.UpdateProductEdit", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ProductId", ReadProperty(ProductIdProperty)).DbType = DbType.Guid; cmd.Parameters.AddWithValue("@ProductCode", ReadProperty(ProductCodeProperty) == null ? (object)DBNull.Value : ReadProperty(ProductCodeProperty)).DbType = DbType.StringFixedLength; cmd.Parameters.AddWithValue("@Name", ReadProperty(NameProperty)).DbType = DbType.String; cmd.Parameters.AddWithValue("@ProductTypeId", ReadProperty(ProductTypeIdProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@UnitCost", ReadProperty(UnitCostProperty)).DbType = DbType.StringFixedLength; cmd.Parameters.AddWithValue("@StockByteNull", ReadProperty(StockByteNullProperty) == null ? (object)DBNull.Value : ReadProperty(StockByteNullProperty).Value).DbType = DbType.Byte; cmd.Parameters.AddWithValue("@StockByte", ReadProperty(StockByteProperty)).DbType = DbType.Byte; cmd.Parameters.AddWithValue("@StockShortNull", ReadProperty(StockShortNullProperty) == null ? (object)DBNull.Value : ReadProperty(StockShortNullProperty).Value).DbType = DbType.Int16; cmd.Parameters.AddWithValue("@StockShort", ReadProperty(StockShortProperty)).DbType = DbType.Int16; cmd.Parameters.AddWithValue("@StockIntNull", ReadProperty(StockIntNullProperty) == null ? (object)DBNull.Value : ReadProperty(StockIntNullProperty).Value).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@StockInt", ReadProperty(StockIntProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@StockLongNull", ReadProperty(StockLongNullProperty) == null ? (object)DBNull.Value : ReadProperty(StockLongNullProperty).Value).DbType = DbType.Int64; cmd.Parameters.AddWithValue("@StockLong", ReadProperty(StockLongProperty)).DbType = DbType.Int64; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } // flushes all pending data operations FieldManager.UpdateChildren(this); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
using System.Collections.Generic; using System; using Cocos2D; namespace CocosDenshion { public class CCSimpleAudioEngine { /// <summary> /// The list of sounds that are configured for looping. These need to be stopped when the game pauses. /// </summary> private Dictionary<int, int> _LoopedSounds = new Dictionary<int, int>(); /// <summary> /// The shared sound effect list. The key is the hashcode of the file path. /// </summary> public static Dictionary<int, CCEffectPlayer> SharedList { get { return (s_List); } } /// <summary> /// The shared music player. /// </summary> private static CCMusicPlayer SharedMusic { get { return(s_Music); } } /// <summary> /// The singleton instance of this class. /// </summary> public static CCSimpleAudioEngine SharedEngine { get { return _Instance; } } public float BackgroundMusicVolume { get { return SharedMusic.Volume; } set { SharedMusic.Volume = value; } } /** @brief The volume of the effects max value is 1.0,the min value is 0.0 */ public float EffectsVolume { get { return CCEffectPlayer.Volume; } set { CCEffectPlayer.Volume = value; } } public static string FullPath(string szPath) { // todo: return self now return szPath; } /** @brief Release the shared Engine object @warning It must be called before the application exit, or a memroy leak will be casued. */ public void End () { SharedMusic.Close (); lock (SharedList) { foreach (var kvp in SharedList) { kvp.Value.Close (); } SharedList.Clear (); } } /// <summary> /// Restore the media player's state to how it was prior to the game launch. You need to do this when the game terminates /// if you run music that clobbers the music that was playing before the game launched. /// </summary> public void RestoreMediaState() { SharedMusic.RestoreMediaState(); } /// <summary> /// Save the media player's current playback state. /// </summary> public void SaveMediaState() { SharedMusic.SaveMediaState(); } /** @brief Set the zip file name @param pszZipFileName The relative path of the .zip file */ [Obsolete("This is not used in this version of the library")] public static void SetResource(string pszZipFileName) { } /** @brief Preload background music @param pszFilePath The path of the background music file,or the FileName of T_SoundResInfo */ public void PreloadBackgroundMusic(string pszFilePath) { SharedMusic.Open(FullPath(pszFilePath), pszFilePath.GetHashCode()); } /** @brief Play background music @param pszFilePath The path of the background music file,or the FileName of T_SoundResInfo @param bLoop Whether the background music loop or not */ public void PlayBackgroundMusic(string pszFilePath, bool bLoop) { if (null == pszFilePath) { return; } SharedMusic.Open(FullPath(pszFilePath), pszFilePath.GetHashCode()); SharedMusic.Play(bLoop); } /** @brief Play background music @param pszFilePath The path of the background music file,or the FileName of T_SoundResInfo */ public void PlayBackgroundMusic(string pszFilePath) { PlayBackgroundMusic(pszFilePath, false); } /** @brief Stop playing background music @param bReleaseData If release the background music data or not.As default value is false */ public void StopBackgroundMusic(bool bReleaseData) { if (bReleaseData) { SharedMusic.Close(); } else { SharedMusic.Stop(); } } /** @brief Stop playing background music */ public void StopBackgroundMusic() { StopBackgroundMusic(false); } /** @brief Pause playing background music */ public void PauseBackgroundMusic() { SharedMusic.Pause(); } /** @brief Resume playing background music */ public void ResumeBackgroundMusic() { SharedMusic.Resume(); } /** @brief Rewind playing background music */ public void RewindBackgroundMusic() { SharedMusic.Rewind(); } public bool WillPlayBackgroundMusic() { return false; } /** @brief Whether the background music is playing @return If is playing return true,or return false */ public bool IsBackgroundMusicPlaying() { return SharedMusic.IsPlaying(); } /// <summary> /// Play the sound effect with the given path and optionally set it to lopo. /// </summary> /// <param name="pszFilePath">The path to the sound effect file.</param> /// <param name="bLoop">True if the sound effect will play continuously, and false if it will play then stop.</param> /// <returns></returns> public int PlayEffect (string pszFilePath, bool bLoop) { int nId = pszFilePath.GetHashCode (); PreloadEffect (pszFilePath); lock (SharedList) { try { if (SharedList.ContainsKey(nId)) { SharedList[nId].Play(bLoop); if (bLoop) { _LoopedSounds[nId] = nId; } } } catch (Exception ex) { CCLog.Log("Unexpected exception while playing a SoundEffect: {0}", pszFilePath); CCLog.Log(ex.ToString()); } } return nId; } /// <summary> /// Plays the given sound effect without looping. /// </summary> /// <param name="pszFilePath">The path to the sound effect</param> /// <returns></returns> public int PlayEffect(string pszFilePath) { return PlayEffect(pszFilePath, false); } /// <summary> /// Stops the sound effect with the given id. /// </summary> /// <param name="nSoundId"></param> public void StopEffect(int nSoundId) { lock (SharedList) { if (SharedList.ContainsKey(nSoundId)) { SharedList[nSoundId].Stop(); } } lock (_LoopedSounds) { if (_LoopedSounds.ContainsKey(nSoundId)) { _LoopedSounds.Remove(nSoundId); } } } /// <summary> /// Stops all of the sound effects that are currently playing and looping. /// </summary> public void StopAllLoopingEffects() { lock (SharedList) { if (_LoopedSounds.Count > 0) { int[] a = new int[_LoopedSounds.Keys.Count]; _LoopedSounds.Keys.CopyTo(a, 0); foreach (int key in a) { StopEffect(key); } } } } /** @brief preload a compressed audio file @details the compressed audio will be decode to wave, then write into an internal buffer in SimpleaudioEngine */ /// <summary> /// Load the sound effect found with the given path. The sound effect is only loaded one time and the /// effect is cached as an instance of EffectPlayer. /// </summary> public void PreloadEffect(string pszFilePath) { if (string.IsNullOrEmpty(pszFilePath)) { return; } int nId = pszFilePath.GetHashCode(); lock (SharedList) { if (SharedList.ContainsKey(nId)) { return; } } CCEffectPlayer eff = new CCEffectPlayer(); eff.Open(FullPath(pszFilePath), nId); SharedList[nId] = eff; } /** @brief unload the preloaded effect from internal buffer @param[in] pszFilePath The path of the effect file,or the FileName of T_SoundResInfo */ public void UnloadEffect (string pszFilePath) { int nId = pszFilePath.GetHashCode (); lock (SharedList) { if (SharedList.ContainsKey(nId)) { SharedList.Remove(nId); } } lock (_LoopedSounds) { if (_LoopedSounds.ContainsKey(nId)) { _LoopedSounds.Remove(nId); } } } private static Dictionary<int, CCEffectPlayer> s_List = new Dictionary<int,CCEffectPlayer>(); private static CCMusicPlayer s_Music = new CCMusicPlayer(); private static CCSimpleAudioEngine _Instance = new CCSimpleAudioEngine(); } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // System.Net.HttpConnection // // Author: // Gonzalo Paniagua Javier ([email protected]) // // Copyright (c) 2005-2009 Novell, Inc. (http://www.novell.com) // Copyright (c) 2012 Xamarin, Inc. (http://xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.IO; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; namespace System.Net { internal sealed class HttpConnection { private static AsyncCallback s_onreadCallback = new AsyncCallback(OnRead); private const int BufferSize = 8192; private Socket _socket; private Stream _stream; private HttpEndPointListener _epl; private MemoryStream _memoryStream; private byte[] _buffer; private HttpListenerContext _context; private StringBuilder _currentLine; private ListenerPrefix _prefix; private HttpRequestStream _requestStream; private HttpResponseStream _responseStream; private bool _chunked; private int _reuses; private bool _contextBound; private bool _secure; private X509Certificate _cert; private int _timeout = 90000; // 90k ms for first request, 15k ms from then on private Timer _timer; private IPEndPoint _localEndPoint; private HttpListener _lastListener; private int[] _clientCertErrors; private X509Certificate2 _clientCert; private SslStream _sslStream; private InputState _inputState = InputState.RequestLine; private LineState _lineState = LineState.None; private int _position; public HttpConnection(Socket sock, HttpEndPointListener epl, bool secure, X509Certificate cert) { _socket = sock; _epl = epl; _secure = secure; _cert = cert; if (secure == false) { _stream = new NetworkStream(sock, false); } else { _sslStream = epl.Listener.CreateSslStream(new NetworkStream(sock, false), false, (t, c, ch, e) => { if (c == null) { return true; } var c2 = c as X509Certificate2; if (c2 == null) { c2 = new X509Certificate2(c.GetRawCertData()); } _clientCert = c2; _clientCertErrors = new int[] { (int)e }; return true; }); _stream = _sslStream; } _timer = new Timer(OnTimeout, null, Timeout.Infinite, Timeout.Infinite); Init(); } internal int[] ClientCertificateErrors { get { return _clientCertErrors; } } internal X509Certificate2 ClientCertificate { get { return _clientCert; } } private void Init() { if (_sslStream != null) { _sslStream.AuthenticateAsServer(_cert, true, (SslProtocols)ServicePointManager.SecurityProtocol, false); } _contextBound = false; _requestStream = null; _responseStream = null; _prefix = null; _chunked = false; _memoryStream = new MemoryStream(); _position = 0; _inputState = InputState.RequestLine; _lineState = LineState.None; _context = new HttpListenerContext(this); } public Stream ConnectedStream => _stream; public bool IsClosed { get { return (_socket == null); } } public int Reuses { get { return _reuses; } } public IPEndPoint LocalEndPoint { get { if (_localEndPoint != null) return _localEndPoint; _localEndPoint = (IPEndPoint)_socket.LocalEndPoint; return _localEndPoint; } } public IPEndPoint RemoteEndPoint { get { return (IPEndPoint)_socket.RemoteEndPoint; } } public bool IsSecure { get { return _secure; } } public ListenerPrefix Prefix { get { return _prefix; } set { _prefix = value; } } private void OnTimeout(object unused) { CloseSocket(); Unbind(); } public void BeginReadRequest() { if (_buffer == null) _buffer = new byte[BufferSize]; try { if (_reuses == 1) _timeout = 15000; _timer.Change(_timeout, Timeout.Infinite); _stream.BeginRead(_buffer, 0, BufferSize, s_onreadCallback, this); } catch { _timer.Change(Timeout.Infinite, Timeout.Infinite); CloseSocket(); Unbind(); } } public HttpRequestStream GetRequestStream(bool chunked, long contentlength) { if (_requestStream == null) { byte[] buffer = _memoryStream.GetBuffer(); int length = (int)_memoryStream.Length; _memoryStream = null; if (chunked) { _chunked = true; _context.Response.SendChunked = true; _requestStream = new ChunkedInputStream(_context, _stream, buffer, _position, length - _position); } else { _requestStream = new HttpRequestStream(_stream, buffer, _position, length - _position, contentlength); } } return _requestStream; } public HttpResponseStream GetResponseStream() { if (_responseStream == null) { HttpListener listener = _context._listener; if (listener == null) return new HttpResponseStream(_stream, _context.Response, true); _responseStream = new HttpResponseStream(_stream, _context.Response, listener.IgnoreWriteExceptions); } return _responseStream; } private static void OnRead(IAsyncResult ares) { HttpConnection cnc = (HttpConnection)ares.AsyncState; cnc.OnReadInternal(ares); } private void OnReadInternal(IAsyncResult ares) { _timer.Change(Timeout.Infinite, Timeout.Infinite); int nread = -1; try { nread = _stream.EndRead(ares); _memoryStream.Write(_buffer, 0, nread); if (_memoryStream.Length > 32768) { SendError(HttpStatusDescription.Get(400), 400); Close(true); return; } } catch { if (_memoryStream != null && _memoryStream.Length > 0) SendError(); if (_socket != null) { CloseSocket(); Unbind(); } return; } if (nread == 0) { CloseSocket(); Unbind(); return; } if (ProcessInput(_memoryStream)) { if (!_context.HaveError) _context.Request.FinishInitialization(); if (_context.HaveError) { SendError(); Close(true); return; } if (!_epl.BindContext(_context)) { SendError("Invalid host", 400); Close(true); return; } HttpListener listener = _context._listener; if (_lastListener != listener) { RemoveConnection(); listener.AddConnection(this); _lastListener = listener; } _contextBound = true; listener.RegisterContext(_context); return; } _stream.BeginRead(_buffer, 0, BufferSize, s_onreadCallback, this); } private void RemoveConnection() { if (_lastListener == null) _epl.RemoveConnection(this); else _lastListener.RemoveConnection(this); } private enum InputState { RequestLine, Headers } private enum LineState { None, CR, LF } // true -> done processing // false -> need more input private bool ProcessInput(MemoryStream ms) { byte[] buffer = ms.GetBuffer(); int len = (int)ms.Length; int used = 0; string line; while (true) { if (_context.HaveError) return true; if (_position >= len) break; try { line = ReadLine(buffer, _position, len - _position, ref used); _position += used; } catch { _context.ErrorMessage = HttpStatusDescription.Get(400); _context.ErrorStatus = 400; return true; } if (line == null) break; if (line == "") { if (_inputState == InputState.RequestLine) continue; _currentLine = null; ms = null; return true; } if (_inputState == InputState.RequestLine) { _context.Request.SetRequestLine(line); _inputState = InputState.Headers; } else { try { _context.Request.AddHeader(line); } catch (Exception e) { _context.ErrorMessage = e.Message; _context.ErrorStatus = 400; return true; } } } if (used == len) { ms.SetLength(0); _position = 0; } return false; } private string ReadLine(byte[] buffer, int offset, int len, ref int used) { if (_currentLine == null) _currentLine = new StringBuilder(128); int last = offset + len; used = 0; for (int i = offset; i < last && _lineState != LineState.LF; i++) { used++; byte b = buffer[i]; if (b == 13) { _lineState = LineState.CR; } else if (b == 10) { _lineState = LineState.LF; } else { _currentLine.Append((char)b); } } string result = null; if (_lineState == LineState.LF) { _lineState = LineState.None; result = _currentLine.ToString(); _currentLine.Length = 0; } return result; } public void SendError(string msg, int status) { try { HttpListenerResponse response = _context.Response; response.StatusCode = status; response.ContentType = "text/html"; string description = HttpStatusDescription.Get(status); string str; if (msg != null) str = string.Format("<h1>{0} ({1})</h1>", description, msg); else str = string.Format("<h1>{0}</h1>", description); byte[] error = _context.Response.ContentEncoding.GetBytes(str); response.Close(error, false); } catch { // response was already closed } } public void SendError() { SendError(_context.ErrorMessage, _context.ErrorStatus); } private void Unbind() { if (_contextBound) { _epl.UnbindContext(_context); _contextBound = false; } } public void Close() { Close(false); } private void CloseSocket() { if (_socket == null) return; try { _socket.Close(); } catch { } finally { _socket = null; } RemoveConnection(); } internal void Close(bool force) { if (_socket != null) { Stream st = GetResponseStream(); if (st != null) st.Close(); _responseStream = null; } if (_socket != null) { force |= !_context.Request.KeepAlive; if (!force) force = (_context.Response.Headers[HttpKnownHeaderNames.Connection] == HttpHeaderStrings.Close); if (!force && _context.Request.FlushInput()) { if (_chunked && _context.Response.ForceCloseChunked == false) { // Don't close. Keep working. _reuses++; Unbind(); Init(); BeginReadRequest(); return; } _reuses++; Unbind(); Init(); BeginReadRequest(); return; } Socket s = _socket; _socket = null; try { if (s != null) s.Shutdown(SocketShutdown.Both); } catch { } finally { if (s != null) s.Close(); } Unbind(); RemoveConnection(); return; } } } }
//----------------------------------------------------------------------------- // // <copyright file="PackWebResponse.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: // WebResponse class to handle pack-specific URI's // // History: // 10/09/2003: BruceMac: Created. // 01/05/2004: BruceMac: Rearchitect to return a new stream for each GetResponseStream call. // 01/08/2004: BruceMac: Disable serialization // 05/10/2004: BruceMac: Port to pack scheme // //----------------------------------------------------------------------------- #if DEBUG #define TRACE #endif using System; using System.IO; using System.Net; using System.Runtime.Serialization; using System.Diagnostics; // For Assert using System.Threading; // for ManualResetEvent using System.Globalization; // for CultureInfo using MS.Internal.PresentationCore; // for ExceptionStringTable using MS.Internal.IO.Packaging; // for ResponseStream using System.Security; using System.Security.Permissions; using System.Windows.Navigation; using MS.Utility; using MS.Internal; #pragma warning disable 1634, 1691 // disable warning about unknown Presharp warnings namespace System.IO.Packaging { /// <summary> /// Pack-specific WebRequest handler /// </summary> /// <remarks> /// This WebRequest overload exists to handle Pack-specific URI's based on our custom schema /// </remarks> public sealed class PackWebResponse: WebResponse { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ /// <SecurityNote> /// Critical as the BooleanSwitch has a LinkDemand /// TreatAsSafe as this is just a diag switch, Debug-only and internal-only, no input data /// is passed to BooleanSwitch, and the overall operation is considered safe. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] static PackWebResponse() { #if DEBUG _forceWebResponseLengthFailureSwitch = new BooleanSwitch("PackWebResponseBadServerLength", "Simulate PackWebResponse handling of server that returns bogus content length"); #endif } /// <summary> /// Constructor /// </summary> /// <param name="innerRequest">real web request</param> /// <param name="uri">full uri</param> /// <param name="innerUri">inner uri</param> /// <param name="partName">part name in the container - null if uri is to entire container only</param> /// <remarks>intended for use only by PackWebRequest</remarks> /// <SecurityNote> /// Critical /// 1) assigns Critical member _webRequest and calls BeginGetResponse() on it. /// </SecurityNote> [SecurityCritical] internal PackWebResponse(Uri uri, Uri innerUri, Uri partName, WebRequest innerRequest) { if (uri == null) throw new ArgumentNullException("uri"); if (innerUri == null) throw new ArgumentNullException("innerUri"); if (innerRequest == null) throw new ArgumentNullException("innerRequest"); _lockObject = new Object(); // required for synchronization _uri = uri; #if DEBUG if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "PackWebResponse - Creating response "); #endif _innerUri = innerUri; _partName = partName; // may be null _webRequest = innerRequest; _mimeType = null; // until we find out the real value // only create these in non-cache case // Create before any Timeout timer to prevent a race condition with the Timer callback // (that expects _responseAvailable to exist) _responseAvailable = new ManualResetEvent(false); // do we need a timer? // if the TimeOut has been set on the innerRequest, we need to simulate this behavior for // our synchronous clients if (innerRequest.Timeout != Timeout.Infinite) { #if DEBUG if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "PackWebResponse() starting timeout timer " + innerRequest.Timeout + " ms"); #endif _timeoutTimer = new Timer(new TimerCallback(TimeoutCallback), null, innerRequest.Timeout, Timeout.Infinite); } #if DEBUG if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "PackWebResponse() BeginGetResponse()"); #endif // Issue the async request to get our "real" WebResponse // don't access this value until we set the ManualResetEvent _webRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), this); } /// <summary> /// Constructor: Cache-entry overload /// </summary> /// <param name="uri"></param> /// <param name="innerUri"></param> /// <param name="partName"></param> /// <param name="cacheEntry">entry from cache</param> /// <param name="cachedPackageIsThreadSafe">is entry thread safe?</param> internal PackWebResponse(Uri uri, Uri innerUri, Uri partName, Package cacheEntry, bool cachedPackageIsThreadSafe) { _lockObject = new Object(); // required for synchronization if (uri == null) throw new ArgumentNullException("uri"); if (innerUri == null) throw new ArgumentNullException("innerUri"); if (partName == null) throw new ArgumentNullException("partName"); if (cacheEntry == null) throw new ArgumentNullException("cacheEntry"); #if DEBUG if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "PackWebResponse - Creating response from Package Cache"); #endif _uri = uri; _innerUri = innerUri; _partName = partName; // may not be null _mimeType = null; // until we find out the real value // delegate work to private class _cachedResponse = new CachedResponse(this, cacheEntry, cachedPackageIsThreadSafe); } //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region WebResponse Overloads /// <summary> /// Retrieves a stream for reading bytes from the requested resource /// </summary> /// <returns>stream</returns> /// <SecurityNote> /// Critical /// 1) Passes Critical member _webRequest to NetStream constructor /// Safe /// 1) Providing _webRequest to NetStream is safe because NetStream treats _webRequest as Critical /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] public override Stream GetResponseStream() { CheckDisposed(); // redirect if (FromPackageCache) return _cachedResponse.GetResponseStream(); EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordXPS, EventTrace.Event.WClientDRXGetStreamBegin); #if DEBUG if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "PackWebResponse - GetResponseStream()"); #endif // create and return only a single stream for multiple calls if (_responseStream == null) { // can't do this until the response is available WaitForResponse(); // after this call, we have a viable _fullResponse object because WaitForResponse would have thrown otherwise // determine content length long streamLength = _fullResponse.ContentLength; #if DEBUG if (_forceWebResponseLengthFailureSwitch.Enabled) streamLength = -1; // special handling for servers that won't or can't give us the length of the resource - byte-range downloading is impossible if (streamLength <= 0) { if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "PackWebResponse - GetResponseStream() - stream length not available - disabling progressive download"); } #endif // Start reading data from the response stream. _responseStream = _fullResponse.GetResponseStream(); // require NetStream for progressivity and for network streams that don't // directly support seeking. if (!_responseStream.CanSeek || !_innerUri.IsFile) { // Create a smart stream that will spawn byte-range requests as needed // and support seeking. Each read has overhead of Mutex and many of the // reads come through asking for 4 bytes at a time _responseStream = new NetStream( _responseStream, streamLength, _innerUri, _webRequest, _fullResponse); // wrap our stream for efficiency (short reads are expanded) _responseStream = new BufferedStream(_responseStream); } // handle degenerate case where there is no part name if (_partName == null) { _fullStreamLength = streamLength; // entire container _mimeType = WpfWebRequestHelper.GetContentType(_fullResponse); // pass this so that ResponseStream holds a reference to us until the stream is closed _responseStream = new ResponseStream(_responseStream, this); } else { // open container on netStream Package c = Package.Open(_responseStream); if (!c.PartExists(_partName)) throw new WebException(SR.Get(SRID.WebResponsePartNotFound)); PackagePart p = c.GetPart(_partName); Stream s = p.GetStream(FileMode.Open, FileAccess.Read); _mimeType = new MS.Internal.ContentType(p.ContentType); // save this for use in ContentType property - may still be null _fullStreamLength = s.Length; // just this stream // Wrap in a ResponseStream so that this container will be released // when the stream is closed _responseStream = new ResponseStream(s, this, _responseStream, c); } // length available? (-1 means the server chose not to report it) if (_fullStreamLength >= 0) { _lengthAvailable = true; } } EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordXPS, EventTrace.Event.WClientDRXGetStreamEnd); return _responseStream; } /// <summary> /// Close stream /// </summary> public override void Close() { Dispose(true); } #endregion //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ /// <summary> /// InnerResponse /// </summary> /// <value>inner WebResponse</value> public WebResponse InnerResponse { get { CheckDisposed(); // no inner response if (FromPackageCache) return null; // can't do this until the response is available WaitForResponse(); return _fullResponse; } } /// <summary> /// Headers /// </summary> /// <value>web headers</value> public override WebHeaderCollection Headers { get { CheckDisposed(); // redirect if (FromPackageCache) return _cachedResponse.Headers; // can't do this until the response is available WaitForResponse(); return _fullResponse.Headers; } } /// <summary> /// ResponseUri /// </summary> /// <value>Fully-qualified pack uri reflecting any server redirection.</value> /// <remarks>For the inner ResponseUri access the InnerResponse like this: /// Uri innerResponseUri = packResponse.InnerResponse.ResponseUri</remarks> public override Uri ResponseUri { get { CheckDisposed(); // If data is served from a cached package, we simply return the original, fully-qualified // pack uri. if (FromPackageCache) return _uri; else { // If data is served from an actual webResponse, we need to re-compose the original pack uri // with the responseUri provided by the real webResponse to account for server redirects. // We can't do this until the response is available so we wait. WaitForResponse(); // create new pack uri with webResponse and original part name uri return PackUriHelper.Create(_fullResponse.ResponseUri, _partName); } } } /// <summary> /// IsFromCache /// </summary> /// <value>true if result is from the cache</value> public override bool IsFromCache { get { CheckDisposed(); // quick answer if (FromPackageCache) return true; // can't do this until the response is available WaitForResponse(); return _fullResponse.IsFromCache; } } /// <summary> /// ContentType /// </summary> /// <value>string</value> /// <remarks>There are four separate results possible from this property. If the PartName is /// empty, then the container MIME type is returned. If it is not, we return the MIME type of the /// stream in the following order or preference: /// 1. If the PackagePart offers a MIME type, we return that /// 2. If the stream name has an extension, we determine the MIME type from that using a lookup table /// 3. We return String.Empty if no extension is found.</remarks> public override string ContentType { get { CheckDisposed(); // No need to wait if working from cache // But we can share the logic as none of it hits the _webResponse if (!FromPackageCache) { // can't do this until the response is available WaitForResponse(); } // cache the value - if it's empty that means we already tried (and failed) to find a real type if (_mimeType == null) { // Get the response stream which has the side effect of setting the _mimeType member. GetResponseStream(); } return _mimeType.ToString(); } } /// <summary> /// ContentLength /// </summary> /// <value>length of response stream</value> public override long ContentLength { get { CheckDisposed(); // redirect if (FromPackageCache) return _cachedResponse.ContentLength; // can't do this until the response is available WaitForResponse(); // is the length available? if (!_lengthAvailable) { _fullStreamLength = GetResponseStream().Length; _lengthAvailable = true; } // use the stored value return _fullStreamLength; } } //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ /// <summary> /// AbortResponse - called only from Close() /// </summary> /// <remarks>assumes caller has locked the syncObject and that we are not disposed</remarks> /// <SecurityNote> /// Critical /// 1) accesses Critical _webRequest /// Safe /// 1) Not modifying WebRequest.Proxy member which is what is really Critical /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] private void AbortResponse() { // Disable the PreSharp warning about empty catch blocks - we need this one because sub-classes of WebResponse may or may // not implement Abort() and we want to silently ignore this if they don't. #pragma warning disable 56502 // Close was called - abort the response if necessary try { // Only abort if the response is still "outstanding". // Non-blocking "peek" at the event to see if it is set or not. if (!_responseAvailable.WaitOne(0, false)) { _webRequest.Abort(); // response not back yet so abort it } } catch (NotImplementedException) { // Ignore - innerRequest class chose to implement BeginGetResponse but not Abort. This is allowed. } #pragma warning restore 56502 } protected override void Dispose(bool disposing) { if (!_disposed) { if (disposing) { // ignore multiple calls to Close() // no lock required here because the only place where _disposed is changed is later in this same function and this // function is never entered by more than one thread if (_disposed) return; // redirect for cache case // NOTE: FromPackageCache need not be synchronized because it is only set once in the constructor and never // changes. if (FromPackageCache) { _cachedResponse.Close(); // indirectly sets _disposed on this class _cachedResponse = null; // release return; } #if DEBUG if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "PackWebResponse.Close()"); #endif // prevent async callback from accessing these resources while we are disposing them lock (_lockObject) { try { // abort any outstanding response AbortResponse(); // prevent recursion in our call to _responseStream.Close() _disposed = true; if (_responseStream != null) { #if DEBUG if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "PackWebResponse.Close() - close stream"); #endif _responseStream.Close(); } // FullResponse if (_fullResponse != null) { #if DEBUG if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "PackWebResponse.Close() - close response"); #endif // always call Dispose to satisfy FxCop ((IDisposable)_fullResponse).Dispose(); } // must free this regardless of whether GetResponseStream was invoked _responseAvailable.Close(); // this call can not throw an exception // timer if (_timeoutTimer != null) { _timeoutTimer.Dispose(); } } finally { _timeoutTimer = null; _responseStream = null; _fullResponse = null; _responseAvailable = null; #if DEBUG if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "PackWebResponse.Close() - exiting"); #endif } } // lock } } } //------------------------------------------------------ // // Private Properties // //------------------------------------------------------ private bool FromPackageCache { get { return (_cachedResponse != null); } } //------------------------------------------------------ // // Private Classes // //------------------------------------------------------ /// <summary> /// CachedResponse class /// </summary> /// <remarks>Isolate cache-specific functionality to reduce complexity</remarks> private class CachedResponse { //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ internal CachedResponse(PackWebResponse parent, Package cacheEntry, bool cachedPackageIsThreadSafe) { _parent = parent; _cacheEntry = cacheEntry; _cachedPackageIsThreadSafe = cachedPackageIsThreadSafe; } /// <summary> /// Cache version of GetResponseStream /// </summary> /// <returns></returns> internal Stream GetResponseStream() { // prevent concurrent access to GetPart() which is not thread-safe lock (_cacheEntry) { #if DEBUG if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "CachedResponse - Getting response stream"); #endif // only one copy if (_parent._responseStream == null) { // full container request? if (_parent._partName == null) { Debug.Assert(false, "Cannot return full-container stream from cached container object"); } else { #if DEBUG if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "CachedResponse - Getting part " + _parent._partName); #endif // open the requested stream PackagePart p = _cacheEntry.GetPart(_parent._partName); #if DEBUG if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "CachedResponse - Getting part stream "); #endif Stream s = p.GetStream(FileMode.Open, FileAccess.Read); // Unless package is thread-safe, wrap the returned stream so that // package access is serialized if (!_cachedPackageIsThreadSafe) { // Return a stream that provides thread-safe access // to the cached package by locking on the cached Package s = new SynchronizingStream(s, _cacheEntry); } #if DEBUG if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "CachedResponse - Getting part contenttype"); #endif _parent._mimeType = new MS.Internal.ContentType(p.ContentType); // cache this in case they ask for it after the stream has been closed _parent._lengthAvailable = s.CanSeek; if (s.CanSeek) { #if DEBUG if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "CachedResponse - Length is available from stream"); #endif _parent._fullStreamLength = s.Length; } #if DEBUG else { if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "CachedResponse - Length is not available from stream" + _parent._partName); } #endif // re-use existing member variable _parent._responseStream = s; } } } return _parent._responseStream; } /// <summary> /// Release some resources /// </summary> internal void Close() { try { // Prevent recursion - this [....]-protected member is safe to set in a CachedResponse // mode because we have no other thread in operation. _parent._disposed = true; if (_parent._responseStream != null) _parent._responseStream.Close(); } finally { _cacheEntry = null; _parent._uri = null; _parent._mimeType = null; _parent._innerUri = null; _parent._partName = null; _parent._responseStream = null; _parent = null; } } //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ internal WebHeaderCollection Headers { get { // empty - bogus collection - prevents exceptions for callers return new WebHeaderCollection(); } } public long ContentLength { get { // if fullStreamLength not already set, get the stream which has // the side effect of updating the length if (!_parent._lengthAvailable) GetResponseStream(); return _parent._fullStreamLength; } } // fields private PackWebResponse _parent; private Package _cacheEntry; private bool _cachedPackageIsThreadSafe; } /// <summary> /// Throw exception if we are already closed /// </summary> private void CheckDisposed() { // no need to lock here because only Close() sets this variable and we are not ThreadSafe if (_disposed) throw new ObjectDisposedException("PackWebResponse"); } /// <summary> /// ResponseCallBack /// </summary> /// <param name="ar">async result</param> /// <remarks>static method not necessary</remarks> /// <SecurityNote> /// Critical /// 1) calls EndGetResponse() on Critical member _webRequest /// </SecurityNote> [SecurityCritical] private void ResponseCallback(IAsyncResult ar) { lock (_lockObject) // prevent race condition accessing _timeoutTimer, _disposed, _responseAvailable { try { // If disposed, the message is too late // Exit early and don't access members as they have been disposed if (!_disposed) { // dispose the timer - it is no longer needed if (_timeoutTimer != null) _timeoutTimer.Dispose(); #if DEBUG if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "PackWebResponse.ResponseCallBack()"); #endif // Dispose/Close waits on _responseAvailable so we know that these are available // No need to lock. // Call EndGetResponse, which produces the WebResponse object // that came from the request issued above. _fullResponse = MS.Internal.WpfWebRequestHelper.EndGetResponse(_webRequest, ar); } } catch (WebException e) { // web exceptions are meaningful to our client code - keep these to re-throw on the other thread _responseException = e; _responseError = true; } catch // catch (and re-throw) all kinds of exceptions so we can inform the other thread { #if DEBUG if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceError( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "PackWebResponse.ResponseCallBack() exception"); #endif // inform other thread of error condition _responseError = true; throw; } finally { _timeoutTimer = null; // harmless if already null, and removes need for extra try/finally block above #if DEBUG if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "PackWebResponse.ResponseCallBack() - signal response available"); #endif // We need the original webRequest to get HttpStack information so that they can be used to make // additional byte range request; So we cannot null it out anymore // _webRequest = null; // don't need this anymore so release // this must be set even when there is an exception so that our client // can be unblocked // make sure this wasn't already free'd when the Timercallback thread released // the blocked Close() thread if (!_disposed) _responseAvailable.Set(); } } } /// <summary> /// All methods that need to access variables only available after the response callback has been /// handled should call this to block. Doing it in one place simplifies our need to respond to any /// exceptions encountered in the other thread and rethrow these. /// </summary> private void WaitForResponse() { #if DEBUG if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "PackWebResponse.WaitForResponse()"); #endif // wait for the response callback _responseAvailable.WaitOne(); // We get here only when the other thread signals. // Need to inspect for errors and throw if there was trouble on the other thread. if (_responseError) { if (_responseException == null) throw new WebException(SR.Get(SRID.WebResponseFailure)); else throw _responseException; // throw literal exception if there is one } } /// <summary> /// Timeout callback /// </summary> /// <param name="stateInfo"></param> private void TimeoutCallback(Object stateInfo) { lock (_lockObject) // prevent race condition accessing _timeoutTimer, _disposed, _responseAvailable { // If disposed, the message is too late // Exit early and don't access members as they have been disposed // Let Close() method clean up our Timer object if (_disposed) return; try { // If we get called, need to check if response is available before escalating // just in case it arrived "just now". If the event is already signalled, we can ignore // the callback as no "timeout" occurred. if (!_responseAvailable.WaitOne(0, false)) { #if DEBUG if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceError( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "PackWebResponse.TimerCallback() timeout - throwing exception"); #endif // caller is still blocked so need to throw to indicate timeout // create exception to be thrown on client thread, then unblock the caller // thread will be discovered and re-thrown in WaitForResponse() method _responseError = true; _responseException = new WebException(SR.Get(SRID.WebRequestTimeout, null), WebExceptionStatus.Timeout); } #if DEBUG else { if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "PackWebResponse.TimerCallback() no timeout - ignoring callback"); } #endif // clean up if (_timeoutTimer != null) { _timeoutTimer.Dispose(); } } finally { _timeoutTimer = null; if (!_disposed) { // this must be set so that our client can be unblocked and then discover the exception _responseAvailable.Set(); } } } // lock } //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ private MS.Internal.ContentType _mimeType; // type of the returned stream - cached because it never changes private const int _bufferSize = 0x1000; // 4k private Uri _uri; // full uri private Uri _innerUri; // inner uri private Uri _partName; // path to stream private bool _disposed; // closed? /// <SecurityNote> /// Critical /// 1) Proxy member is Critical because we use it under Unrestricted assert /// </SecurityNote> [SecurityCritical] // only WebRequest.Proxy member is Critical private WebRequest _webRequest; // the real web request private WebResponse _fullResponse; // the real web response private long _fullStreamLength; // need to return this in call to get_Length private Stream _responseStream; // mimic existing Response behavior by creating and returning // one and only one stream private bool _responseError; // will be true if exception occurs calling EndGetResponse() private Exception _responseException; // actual exception to throw (if any) private Timer _timeoutTimer; // used if Timeout specified // OS event used to signal that the response is available private ManualResetEvent _responseAvailable; // protects access to _fullResponse object // flag to signal that _fullStreamLength is valid - needed because some servers don't return // the length (usually FTP servers) so calls to Stream.Length must block until we know the actual length. private bool _lengthAvailable; // PackageCache response? private CachedResponse _cachedResponse; // null if cache not used // private object to prevent deadlock (should not lock(_lockObject) based on PreSharp rule 6517) private Object _lockObject; // Serialize access to _disposed, _timoutTimer and _responseAvailable because even though the main client // thread blocks on WaitForResponse (_responseAvailable event) the optional Timer thread and the // Response callback thread may arrive independently at any time. #if DEBUG // toggle this switch to force execution of code that handles servers that return bogus content length internal static System.Diagnostics.BooleanSwitch _forceWebResponseLengthFailureSwitch; #endif } }
// Copyright (C) 2014 dot42 // // Original filename: Org.Apache.Http.Params.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Org.Apache.Http.Params { /// <java-name> /// org/apache/http/params/HttpProtocolParamBean /// </java-name> [Dot42.DexImport("org/apache/http/params/HttpProtocolParamBean", AccessFlags = 33)] public partial class HttpProtocolParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public HttpProtocolParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { } /// <java-name> /// setHttpElementCharset /// </java-name> [Dot42.DexImport("setHttpElementCharset", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetHttpElementCharset(string httpElementCharset) /* MethodBuilder.Create */ { } /// <java-name> /// setContentCharset /// </java-name> [Dot42.DexImport("setContentCharset", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetContentCharset(string contentCharset) /* MethodBuilder.Create */ { } /// <java-name> /// setVersion /// </java-name> [Dot42.DexImport("setVersion", "(Lorg/apache/http/HttpVersion;)V", AccessFlags = 1)] public virtual void SetVersion(global::Org.Apache.Http.HttpVersion version) /* MethodBuilder.Create */ { } /// <java-name> /// setUserAgent /// </java-name> [Dot42.DexImport("setUserAgent", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetUserAgent(string userAgent) /* MethodBuilder.Create */ { } /// <java-name> /// setUseExpectContinue /// </java-name> [Dot42.DexImport("setUseExpectContinue", "(Z)V", AccessFlags = 1)] public virtual void SetUseExpectContinue(bool useExpectContinue) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal HttpProtocolParamBean() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>An adaptor for accessing connection parameters in HttpParams. <br></br> Note that the <b>implements</b> relation to CoreConnectionPNames is for compatibility with existing application code only. References to the parameter names should use the interface, not this class.</para><para><para></para><para></para><title>Revision:</title><para>576089 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/HttpConnectionParams /// </java-name> [Dot42.DexImport("org/apache/http/params/HttpConnectionParams", AccessFlags = 49)] public sealed partial class HttpConnectionParams : global::Org.Apache.Http.Params.ICoreConnectionPNames /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal HttpConnectionParams() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the default socket timeout (<code>SO_TIMEOUT</code>) in milliseconds which is the timeout for waiting for data. A timeout value of zero is interpreted as an infinite timeout. This value is used when no socket timeout is set in the method parameters.</para><para></para> /// </summary> /// <returns> /// <para>timeout in milliseconds </para> /// </returns> /// <java-name> /// getSoTimeout /// </java-name> [Dot42.DexImport("getSoTimeout", "(Lorg/apache/http/params/HttpParams;)I", AccessFlags = 9)] public static int GetSoTimeout(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Sets the default socket timeout (<code>SO_TIMEOUT</code>) in milliseconds which is the timeout for waiting for data. A timeout value of zero is interpreted as an infinite timeout. This value is used when no socket timeout is set in the method parameters.</para><para></para> /// </summary> /// <java-name> /// setSoTimeout /// </java-name> [Dot42.DexImport("setSoTimeout", "(Lorg/apache/http/params/HttpParams;I)V", AccessFlags = 9)] public static void SetSoTimeout(global::Org.Apache.Http.Params.IHttpParams @params, int timeout) /* MethodBuilder.Create */ { } /// <summary> /// <para>Tests if Nagle's algorithm is to be used.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the Nagle's algorithm is to NOT be used (that is enable TCP_NODELAY), <code>false</code> otherwise. </para> /// </returns> /// <java-name> /// getTcpNoDelay /// </java-name> [Dot42.DexImport("getTcpNoDelay", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)] public static bool GetTcpNoDelay(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Determines whether Nagle's algorithm is to be used. The Nagle's algorithm tries to conserve bandwidth by minimizing the number of segments that are sent. When applications wish to decrease network latency and increase performance, they can disable Nagle's algorithm (that is enable TCP_NODELAY). Data will be sent earlier, at the cost of an increase in bandwidth consumption.</para><para></para> /// </summary> /// <java-name> /// setTcpNoDelay /// </java-name> [Dot42.DexImport("setTcpNoDelay", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)] public static void SetTcpNoDelay(global::Org.Apache.Http.Params.IHttpParams @params, bool value) /* MethodBuilder.Create */ { } /// <java-name> /// getSocketBufferSize /// </java-name> [Dot42.DexImport("getSocketBufferSize", "(Lorg/apache/http/params/HttpParams;)I", AccessFlags = 9)] public static int GetSocketBufferSize(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// setSocketBufferSize /// </java-name> [Dot42.DexImport("setSocketBufferSize", "(Lorg/apache/http/params/HttpParams;I)V", AccessFlags = 9)] public static void SetSocketBufferSize(global::Org.Apache.Http.Params.IHttpParams @params, int size) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns linger-on-close timeout. Value <code>0</code> implies that the option is disabled. Value <code>-1</code> implies that the JRE default is used.</para><para></para> /// </summary> /// <returns> /// <para>the linger-on-close timeout </para> /// </returns> /// <java-name> /// getLinger /// </java-name> [Dot42.DexImport("getLinger", "(Lorg/apache/http/params/HttpParams;)I", AccessFlags = 9)] public static int GetLinger(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Returns linger-on-close timeout. This option disables/enables immediate return from a close() of a TCP Socket. Enabling this option with a non-zero Integer timeout means that a close() will block pending the transmission and acknowledgement of all data written to the peer, at which point the socket is closed gracefully. Value <code>0</code> implies that the option is disabled. Value <code>-1</code> implies that the JRE default is used.</para><para></para> /// </summary> /// <java-name> /// setLinger /// </java-name> [Dot42.DexImport("setLinger", "(Lorg/apache/http/params/HttpParams;I)V", AccessFlags = 9)] public static void SetLinger(global::Org.Apache.Http.Params.IHttpParams @params, int value) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the timeout until a connection is etablished. A value of zero means the timeout is not used. The default value is zero.</para><para></para> /// </summary> /// <returns> /// <para>timeout in milliseconds. </para> /// </returns> /// <java-name> /// getConnectionTimeout /// </java-name> [Dot42.DexImport("getConnectionTimeout", "(Lorg/apache/http/params/HttpParams;)I", AccessFlags = 9)] public static int GetConnectionTimeout(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Sets the timeout until a connection is etablished. A value of zero means the timeout is not used. The default value is zero.</para><para></para> /// </summary> /// <java-name> /// setConnectionTimeout /// </java-name> [Dot42.DexImport("setConnectionTimeout", "(Lorg/apache/http/params/HttpParams;I)V", AccessFlags = 9)] public static void SetConnectionTimeout(global::Org.Apache.Http.Params.IHttpParams @params, int timeout) /* MethodBuilder.Create */ { } /// <summary> /// <para>Tests whether stale connection check is to be used. Disabling stale connection check may result in slight performance improvement at the risk of getting an I/O error when executing a request over a connection that has been closed at the server side.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if stale connection check is to be used, <code>false</code> otherwise. </para> /// </returns> /// <java-name> /// isStaleCheckingEnabled /// </java-name> [Dot42.DexImport("isStaleCheckingEnabled", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)] public static bool IsStaleCheckingEnabled(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Defines whether stale connection check is to be used. Disabling stale connection check may result in slight performance improvement at the risk of getting an I/O error when executing a request over a connection that has been closed at the server side.</para><para></para> /// </summary> /// <java-name> /// setStaleCheckingEnabled /// </java-name> [Dot42.DexImport("setStaleCheckingEnabled", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)] public static void SetStaleCheckingEnabled(global::Org.Apache.Http.Params.IHttpParams @params, bool value) /* MethodBuilder.Create */ { } } /// <summary> /// <para>Abstract base class for parameter collections. Type specific setters and getters are mapped to the abstract, generic getters and setters.</para><para><para> </para><simplesectsep></simplesectsep><para></para><para></para><title>Revision:</title><para>542224 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/AbstractHttpParams /// </java-name> [Dot42.DexImport("org/apache/http/params/AbstractHttpParams", AccessFlags = 1057)] public abstract partial class AbstractHttpParams : global::Org.Apache.Http.Params.IHttpParams /* scope: __dot42__ */ { /// <summary> /// <para>Instantiates parameters. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 4)] protected internal AbstractHttpParams() /* MethodBuilder.Create */ { } /// <java-name> /// getLongParameter /// </java-name> [Dot42.DexImport("getLongParameter", "(Ljava/lang/String;J)J", AccessFlags = 1)] public virtual long GetLongParameter(string name, long defaultValue) /* MethodBuilder.Create */ { return default(long); } /// <java-name> /// setLongParameter /// </java-name> [Dot42.DexImport("setLongParameter", "(Ljava/lang/String;J)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public virtual global::Org.Apache.Http.Params.IHttpParams SetLongParameter(string name, long value) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } /// <java-name> /// getIntParameter /// </java-name> [Dot42.DexImport("getIntParameter", "(Ljava/lang/String;I)I", AccessFlags = 1)] public virtual int GetIntParameter(string name, int defaultValue) /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// setIntParameter /// </java-name> [Dot42.DexImport("setIntParameter", "(Ljava/lang/String;I)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public virtual global::Org.Apache.Http.Params.IHttpParams SetIntParameter(string name, int value) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } /// <java-name> /// getDoubleParameter /// </java-name> [Dot42.DexImport("getDoubleParameter", "(Ljava/lang/String;D)D", AccessFlags = 1)] public virtual double GetDoubleParameter(string name, double defaultValue) /* MethodBuilder.Create */ { return default(double); } /// <java-name> /// setDoubleParameter /// </java-name> [Dot42.DexImport("setDoubleParameter", "(Ljava/lang/String;D)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public virtual global::Org.Apache.Http.Params.IHttpParams SetDoubleParameter(string name, double value) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } /// <java-name> /// getBooleanParameter /// </java-name> [Dot42.DexImport("getBooleanParameter", "(Ljava/lang/String;Z)Z", AccessFlags = 1)] public virtual bool GetBooleanParameter(string name, bool defaultValue) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// setBooleanParameter /// </java-name> [Dot42.DexImport("setBooleanParameter", "(Ljava/lang/String;Z)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public virtual global::Org.Apache.Http.Params.IHttpParams SetBooleanParameter(string name, bool value) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } /// <java-name> /// isParameterTrue /// </java-name> [Dot42.DexImport("isParameterTrue", "(Ljava/lang/String;)Z", AccessFlags = 1)] public virtual bool IsParameterTrue(string name) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// isParameterFalse /// </java-name> [Dot42.DexImport("isParameterFalse", "(Ljava/lang/String;)Z", AccessFlags = 1)] public virtual bool IsParameterFalse(string name) /* MethodBuilder.Create */ { return default(bool); } [Dot42.DexImport("org/apache/http/params/HttpParams", "getParameter", "(Ljava/lang/String;)Ljava/lang/Object;", AccessFlags = 1025)] public virtual object GetParameter(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(object); } [Dot42.DexImport("org/apache/http/params/HttpParams", "setParameter", "(Ljava/lang/String;Ljava/lang/Object;)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] public virtual global::Org.Apache.Http.Params.IHttpParams SetParameter(string name, object value) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.Params.IHttpParams); } [Dot42.DexImport("org/apache/http/params/HttpParams", "copy", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] public virtual global::Org.Apache.Http.Params.IHttpParams Copy() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.Params.IHttpParams); } [Dot42.DexImport("org/apache/http/params/HttpParams", "removeParameter", "(Ljava/lang/String;)Z", AccessFlags = 1025)] public virtual bool RemoveParameter(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(bool); } } /// <summary> /// <para>Defines parameter names for protocol execution in HttpCore.</para><para><para></para><title>Revision:</title><para>576077 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/CoreProtocolPNames /// </java-name> [Dot42.DexImport("org/apache/http/params/CoreProtocolPNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class ICoreProtocolPNamesConstants /* scope: __dot42__ */ { /// <summary> /// <para>Defines the protocol version used per default. </para><para>This parameter expects a value of type org.apache.http.ProtocolVersion. </para> /// </summary> /// <java-name> /// PROTOCOL_VERSION /// </java-name> [Dot42.DexImport("PROTOCOL_VERSION", "Ljava/lang/String;", AccessFlags = 25)] public const string PROTOCOL_VERSION = "http.protocol.version"; /// <summary> /// <para>Defines the charset to be used for encoding HTTP protocol elements. </para><para>This parameter expects a value of type String. </para> /// </summary> /// <java-name> /// HTTP_ELEMENT_CHARSET /// </java-name> [Dot42.DexImport("HTTP_ELEMENT_CHARSET", "Ljava/lang/String;", AccessFlags = 25)] public const string HTTP_ELEMENT_CHARSET = "http.protocol.element-charset"; /// <summary> /// <para>Defines the charset to be used per default for encoding content body. </para><para>This parameter expects a value of type String. </para> /// </summary> /// <java-name> /// HTTP_CONTENT_CHARSET /// </java-name> [Dot42.DexImport("HTTP_CONTENT_CHARSET", "Ljava/lang/String;", AccessFlags = 25)] public const string HTTP_CONTENT_CHARSET = "http.protocol.content-charset"; /// <summary> /// <para>Defines the content of the <code>User-Agent</code> header. </para><para>This parameter expects a value of type String. </para> /// </summary> /// <java-name> /// USER_AGENT /// </java-name> [Dot42.DexImport("USER_AGENT", "Ljava/lang/String;", AccessFlags = 25)] public const string USER_AGENT = "http.useragent"; /// <summary> /// <para>Defines the content of the <code>Server</code> header. </para><para>This parameter expects a value of type String. </para> /// </summary> /// <java-name> /// ORIGIN_SERVER /// </java-name> [Dot42.DexImport("ORIGIN_SERVER", "Ljava/lang/String;", AccessFlags = 25)] public const string ORIGIN_SERVER = "http.origin-server"; /// <summary> /// <para>Defines whether responses with an invalid <code>Transfer-Encoding</code> header should be rejected. </para><para>This parameter expects a value of type Boolean. </para> /// </summary> /// <java-name> /// STRICT_TRANSFER_ENCODING /// </java-name> [Dot42.DexImport("STRICT_TRANSFER_ENCODING", "Ljava/lang/String;", AccessFlags = 25)] public const string STRICT_TRANSFER_ENCODING = "http.protocol.strict-transfer-encoding"; /// <summary> /// <para>Activates 'Expect: 100-continue' handshake for the entity enclosing methods. The purpose of the 'Expect: 100-continue' handshake to allow a client that is sending a request message with a request body to determine if the origin server is willing to accept the request (based on the request headers) before the client sends the request body. </para><para>The use of the 'Expect: 100-continue' handshake can result in noticable peformance improvement for entity enclosing requests (such as POST and PUT) that require the target server's authentication. </para><para>'Expect: 100-continue' handshake should be used with caution, as it may cause problems with HTTP servers and proxies that do not support HTTP/1.1 protocol. </para><para>This parameter expects a value of type Boolean. </para> /// </summary> /// <java-name> /// USE_EXPECT_CONTINUE /// </java-name> [Dot42.DexImport("USE_EXPECT_CONTINUE", "Ljava/lang/String;", AccessFlags = 25)] public const string USE_EXPECT_CONTINUE = "http.protocol.expect-continue"; /// <summary> /// <para>Defines the maximum period of time in milliseconds the client should spend waiting for a 100-continue response. </para><para>This parameter expects a value of type Integer. </para> /// </summary> /// <java-name> /// WAIT_FOR_CONTINUE /// </java-name> [Dot42.DexImport("WAIT_FOR_CONTINUE", "Ljava/lang/String;", AccessFlags = 25)] public const string WAIT_FOR_CONTINUE = "http.protocol.wait-for-continue"; } /// <summary> /// <para>Defines parameter names for protocol execution in HttpCore.</para><para><para></para><title>Revision:</title><para>576077 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/CoreProtocolPNames /// </java-name> [Dot42.DexImport("org/apache/http/params/CoreProtocolPNames", AccessFlags = 1537)] public partial interface ICoreProtocolPNames /* scope: __dot42__ */ { } /// <summary> /// <para>HttpParams implementation that delegates resolution of a parameter to the given default HttpParams instance if the parameter is not present in the local one. The state of the local collection can be mutated, whereas the default collection is treated as read-only.</para><para><para></para><para></para><title>Revision:</title><para>610763 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/DefaultedHttpParams /// </java-name> [Dot42.DexImport("org/apache/http/params/DefaultedHttpParams", AccessFlags = 49)] public sealed partial class DefaultedHttpParams : global::Org.Apache.Http.Params.AbstractHttpParams /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public DefaultedHttpParams(global::Org.Apache.Http.Params.IHttpParams local, global::Org.Apache.Http.Params.IHttpParams defaults) /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a copy of the local collection with the same default </para> /// </summary> /// <java-name> /// copy /// </java-name> [Dot42.DexImport("copy", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public override global::Org.Apache.Http.Params.IHttpParams Copy() /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } /// <summary> /// <para>Retrieves the value of the parameter from the local collection and, if the parameter is not set locally, delegates its resolution to the default collection. </para> /// </summary> /// <java-name> /// getParameter /// </java-name> [Dot42.DexImport("getParameter", "(Ljava/lang/String;)Ljava/lang/Object;", AccessFlags = 1)] public override object GetParameter(string name) /* MethodBuilder.Create */ { return default(object); } /// <summary> /// <para>Attempts to remove the parameter from the local collection. This method <b>does not</b> modify the default collection. </para> /// </summary> /// <java-name> /// removeParameter /// </java-name> [Dot42.DexImport("removeParameter", "(Ljava/lang/String;)Z", AccessFlags = 1)] public override bool RemoveParameter(string name) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Sets the parameter in the local collection. This method <b>does not</b> modify the default collection. </para> /// </summary> /// <java-name> /// setParameter /// </java-name> [Dot42.DexImport("setParameter", "(Ljava/lang/String;Ljava/lang/Object;)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public override global::Org.Apache.Http.Params.IHttpParams SetParameter(string name, object value) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } /// <java-name> /// getDefaults /// </java-name> [Dot42.DexImport("getDefaults", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public global::Org.Apache.Http.Params.IHttpParams GetDefaults() /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal DefaultedHttpParams() /* TypeBuilder.AddDefaultConstructor */ { } /// <java-name> /// getDefaults /// </java-name> public global::Org.Apache.Http.Params.IHttpParams Defaults { [Dot42.DexImport("getDefaults", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] get{ return GetDefaults(); } } } /// <summary> /// <para>This class implements an adaptor around the HttpParams interface to simplify manipulation of the HTTP protocol specific parameters. <br></br> Note that the <b>implements</b> relation to CoreProtocolPNames is for compatibility with existing application code only. References to the parameter names should use the interface, not this class.</para><para><para></para><para></para><title>Revision:</title><para>576089 </para></para><para><para>4.0</para><para>CoreProtocolPNames </para></para> /// </summary> /// <java-name> /// org/apache/http/params/HttpProtocolParams /// </java-name> [Dot42.DexImport("org/apache/http/params/HttpProtocolParams", AccessFlags = 49)] public sealed partial class HttpProtocolParams : global::Org.Apache.Http.Params.ICoreProtocolPNames /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal HttpProtocolParams() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the charset to be used for writing HTTP headers. </para> /// </summary> /// <returns> /// <para>The charset </para> /// </returns> /// <java-name> /// getHttpElementCharset /// </java-name> [Dot42.DexImport("getHttpElementCharset", "(Lorg/apache/http/params/HttpParams;)Ljava/lang/String;", AccessFlags = 9)] public static string GetHttpElementCharset(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the charset to be used for writing HTTP headers. </para> /// </summary> /// <java-name> /// setHttpElementCharset /// </java-name> [Dot42.DexImport("setHttpElementCharset", "(Lorg/apache/http/params/HttpParams;Ljava/lang/String;)V", AccessFlags = 9)] public static void SetHttpElementCharset(global::Org.Apache.Http.Params.IHttpParams @params, string charset) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the default charset to be used for writing content body, when no charset explicitly specified. </para> /// </summary> /// <returns> /// <para>The charset </para> /// </returns> /// <java-name> /// getContentCharset /// </java-name> [Dot42.DexImport("getContentCharset", "(Lorg/apache/http/params/HttpParams;)Ljava/lang/String;", AccessFlags = 9)] public static string GetContentCharset(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the default charset to be used for writing content body, when no charset explicitly specified. </para> /// </summary> /// <java-name> /// setContentCharset /// </java-name> [Dot42.DexImport("setContentCharset", "(Lorg/apache/http/params/HttpParams;Ljava/lang/String;)V", AccessFlags = 9)] public static void SetContentCharset(global::Org.Apache.Http.Params.IHttpParams @params, string charset) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns protocol version to be used per default.</para><para></para> /// </summary> /// <returns> /// <para>protocol version </para> /// </returns> /// <java-name> /// getVersion /// </java-name> [Dot42.DexImport("getVersion", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/ProtocolVersion;", AccessFlags = 9)] public static global::Org.Apache.Http.ProtocolVersion GetVersion(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.ProtocolVersion); } /// <summary> /// <para>Assigns the protocol version to be used by the HTTP methods that this collection of parameters applies to.</para><para></para> /// </summary> /// <java-name> /// setVersion /// </java-name> [Dot42.DexImport("setVersion", "(Lorg/apache/http/params/HttpParams;Lorg/apache/http/ProtocolVersion;)V", AccessFlags = 9)] public static void SetVersion(global::Org.Apache.Http.Params.IHttpParams @params, global::Org.Apache.Http.ProtocolVersion version) /* MethodBuilder.Create */ { } /// <java-name> /// getUserAgent /// </java-name> [Dot42.DexImport("getUserAgent", "(Lorg/apache/http/params/HttpParams;)Ljava/lang/String;", AccessFlags = 9)] public static string GetUserAgent(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// setUserAgent /// </java-name> [Dot42.DexImport("setUserAgent", "(Lorg/apache/http/params/HttpParams;Ljava/lang/String;)V", AccessFlags = 9)] public static void SetUserAgent(global::Org.Apache.Http.Params.IHttpParams @params, string useragent) /* MethodBuilder.Create */ { } /// <java-name> /// useExpectContinue /// </java-name> [Dot42.DexImport("useExpectContinue", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)] public static bool UseExpectContinue(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// setUseExpectContinue /// </java-name> [Dot42.DexImport("setUseExpectContinue", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)] public static void SetUseExpectContinue(global::Org.Apache.Http.Params.IHttpParams @params, bool b) /* MethodBuilder.Create */ { } } /// <summary> /// <para>Represents a collection of HTTP protocol and framework parameters.</para><para><para></para><para></para><title>Revision:</title><para>610763 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/HttpParams /// </java-name> [Dot42.DexImport("org/apache/http/params/HttpParams", AccessFlags = 1537)] public partial interface IHttpParams /* scope: __dot42__ */ { /// <summary> /// <para>Obtains the value of the given parameter.</para><para><para>setParameter(String, Object) </para></para> /// </summary> /// <returns> /// <para>an object that represents the value of the parameter, <code>null</code> if the parameter is not set or if it is explicitly set to <code>null</code></para> /// </returns> /// <java-name> /// getParameter /// </java-name> [Dot42.DexImport("getParameter", "(Ljava/lang/String;)Ljava/lang/Object;", AccessFlags = 1025)] object GetParameter(string name) /* MethodBuilder.Create */ ; /// <summary> /// <para>Assigns the value to the parameter with the given name.</para><para></para> /// </summary> /// <java-name> /// setParameter /// </java-name> [Dot42.DexImport("setParameter", "(Ljava/lang/String;Ljava/lang/Object;)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] global::Org.Apache.Http.Params.IHttpParams SetParameter(string name, object value) /* MethodBuilder.Create */ ; /// <summary> /// <para>Creates a copy of these parameters.</para><para></para> /// </summary> /// <returns> /// <para>a new set of parameters holding the same values as this one </para> /// </returns> /// <java-name> /// copy /// </java-name> [Dot42.DexImport("copy", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] global::Org.Apache.Http.Params.IHttpParams Copy() /* MethodBuilder.Create */ ; /// <summary> /// <para>Removes the parameter with the specified name.</para><para></para> /// </summary> /// <returns> /// <para>true if the parameter existed and has been removed, false else. </para> /// </returns> /// <java-name> /// removeParameter /// </java-name> [Dot42.DexImport("removeParameter", "(Ljava/lang/String;)Z", AccessFlags = 1025)] bool RemoveParameter(string name) /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns a Long parameter value with the given name. If the parameter is not explicitly set, the default value is returned.</para><para><para>setLongParameter(String, long) </para></para> /// </summary> /// <returns> /// <para>a Long that represents the value of the parameter.</para> /// </returns> /// <java-name> /// getLongParameter /// </java-name> [Dot42.DexImport("getLongParameter", "(Ljava/lang/String;J)J", AccessFlags = 1025)] long GetLongParameter(string name, long defaultValue) /* MethodBuilder.Create */ ; /// <summary> /// <para>Assigns a Long to the parameter with the given name</para><para></para> /// </summary> /// <java-name> /// setLongParameter /// </java-name> [Dot42.DexImport("setLongParameter", "(Ljava/lang/String;J)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] global::Org.Apache.Http.Params.IHttpParams SetLongParameter(string name, long value) /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns an Integer parameter value with the given name. If the parameter is not explicitly set, the default value is returned.</para><para><para>setIntParameter(String, int) </para></para> /// </summary> /// <returns> /// <para>a Integer that represents the value of the parameter.</para> /// </returns> /// <java-name> /// getIntParameter /// </java-name> [Dot42.DexImport("getIntParameter", "(Ljava/lang/String;I)I", AccessFlags = 1025)] int GetIntParameter(string name, int defaultValue) /* MethodBuilder.Create */ ; /// <summary> /// <para>Assigns an Integer to the parameter with the given name</para><para></para> /// </summary> /// <java-name> /// setIntParameter /// </java-name> [Dot42.DexImport("setIntParameter", "(Ljava/lang/String;I)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] global::Org.Apache.Http.Params.IHttpParams SetIntParameter(string name, int value) /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns a Double parameter value with the given name. If the parameter is not explicitly set, the default value is returned.</para><para><para>setDoubleParameter(String, double) </para></para> /// </summary> /// <returns> /// <para>a Double that represents the value of the parameter.</para> /// </returns> /// <java-name> /// getDoubleParameter /// </java-name> [Dot42.DexImport("getDoubleParameter", "(Ljava/lang/String;D)D", AccessFlags = 1025)] double GetDoubleParameter(string name, double defaultValue) /* MethodBuilder.Create */ ; /// <summary> /// <para>Assigns a Double to the parameter with the given name</para><para></para> /// </summary> /// <java-name> /// setDoubleParameter /// </java-name> [Dot42.DexImport("setDoubleParameter", "(Ljava/lang/String;D)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] global::Org.Apache.Http.Params.IHttpParams SetDoubleParameter(string name, double value) /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns a Boolean parameter value with the given name. If the parameter is not explicitly set, the default value is returned.</para><para><para>setBooleanParameter(String, boolean) </para></para> /// </summary> /// <returns> /// <para>a Boolean that represents the value of the parameter.</para> /// </returns> /// <java-name> /// getBooleanParameter /// </java-name> [Dot42.DexImport("getBooleanParameter", "(Ljava/lang/String;Z)Z", AccessFlags = 1025)] bool GetBooleanParameter(string name, bool defaultValue) /* MethodBuilder.Create */ ; /// <summary> /// <para>Assigns a Boolean to the parameter with the given name</para><para></para> /// </summary> /// <java-name> /// setBooleanParameter /// </java-name> [Dot42.DexImport("setBooleanParameter", "(Ljava/lang/String;Z)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] global::Org.Apache.Http.Params.IHttpParams SetBooleanParameter(string name, bool value) /* MethodBuilder.Create */ ; /// <summary> /// <para>Checks if a boolean parameter is set to <code>true</code>.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the parameter is set to value <code>true</code>, <code>false</code> if it is not set or set to <code>false</code> </para> /// </returns> /// <java-name> /// isParameterTrue /// </java-name> [Dot42.DexImport("isParameterTrue", "(Ljava/lang/String;)Z", AccessFlags = 1025)] bool IsParameterTrue(string name) /* MethodBuilder.Create */ ; /// <summary> /// <para>Checks if a boolean parameter is not set or <code>false</code>.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the parameter is either not set or set to value <code>false</code>, <code>false</code> if it is set to <code>true</code> </para> /// </returns> /// <java-name> /// isParameterFalse /// </java-name> [Dot42.DexImport("isParameterFalse", "(Ljava/lang/String;)Z", AccessFlags = 1025)] bool IsParameterFalse(string name) /* MethodBuilder.Create */ ; } /// <summary> /// <para>This class represents a collection of HTTP protocol parameters. Protocol parameters may be linked together to form a hierarchy. If a particular parameter value has not been explicitly defined in the collection itself, its value will be drawn from the parent collection of parameters.</para><para><para></para><para></para><title>Revision:</title><para>610464 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/BasicHttpParams /// </java-name> [Dot42.DexImport("org/apache/http/params/BasicHttpParams", AccessFlags = 49)] public sealed partial class BasicHttpParams : global::Org.Apache.Http.Params.AbstractHttpParams, global::Java.Io.ISerializable, global::Java.Lang.ICloneable /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public BasicHttpParams() /* MethodBuilder.Create */ { } /// <java-name> /// getParameter /// </java-name> [Dot42.DexImport("getParameter", "(Ljava/lang/String;)Ljava/lang/Object;", AccessFlags = 1)] public override object GetParameter(string name) /* MethodBuilder.Create */ { return default(object); } /// <java-name> /// setParameter /// </java-name> [Dot42.DexImport("setParameter", "(Ljava/lang/String;Ljava/lang/Object;)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public override global::Org.Apache.Http.Params.IHttpParams SetParameter(string name, object value) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } /// <summary> /// <para>Removes the parameter with the specified name.</para><para></para> /// </summary> /// <returns> /// <para>true if the parameter existed and has been removed, false else. </para> /// </returns> /// <java-name> /// removeParameter /// </java-name> [Dot42.DexImport("removeParameter", "(Ljava/lang/String;)Z", AccessFlags = 1)] public override bool RemoveParameter(string name) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Assigns the value to all the parameter with the given names</para><para></para> /// </summary> /// <java-name> /// setParameters /// </java-name> [Dot42.DexImport("setParameters", "([Ljava/lang/String;Ljava/lang/Object;)V", AccessFlags = 1)] public void SetParameters(string[] names, object value) /* MethodBuilder.Create */ { } /// <java-name> /// isParameterSet /// </java-name> [Dot42.DexImport("isParameterSet", "(Ljava/lang/String;)Z", AccessFlags = 1)] public bool IsParameterSet(string name) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// isParameterSetLocally /// </java-name> [Dot42.DexImport("isParameterSetLocally", "(Ljava/lang/String;)Z", AccessFlags = 1)] public bool IsParameterSetLocally(string name) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Removes all parameters from this collection. </para> /// </summary> /// <java-name> /// clear /// </java-name> [Dot42.DexImport("clear", "()V", AccessFlags = 1)] public void Clear() /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a copy of these parameters. The implementation here instantiates BasicHttpParams, then calls copyParams(HttpParams) to populate the copy.</para><para></para> /// </summary> /// <returns> /// <para>a new set of params holding a copy of the <b>local</b> parameters in this object. </para> /// </returns> /// <java-name> /// copy /// </java-name> [Dot42.DexImport("copy", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public override global::Org.Apache.Http.Params.IHttpParams Copy() /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } /// <java-name> /// clone /// </java-name> [Dot42.DexImport("clone", "()Ljava/lang/Object;", AccessFlags = 1)] public object Clone() /* MethodBuilder.Create */ { return default(object); } /// <summary> /// <para>Copies the locally defined parameters to the argument parameters. This method is called from copy().</para><para></para> /// </summary> /// <java-name> /// copyParams /// </java-name> [Dot42.DexImport("copyParams", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 4)] internal void CopyParams(global::Org.Apache.Http.Params.IHttpParams target) /* MethodBuilder.Create */ { } } /// <summary> /// <para>Defines parameter names for connections in HttpCore.</para><para><para></para><title>Revision:</title><para>576077 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/CoreConnectionPNames /// </java-name> [Dot42.DexImport("org/apache/http/params/CoreConnectionPNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class ICoreConnectionPNamesConstants /* scope: __dot42__ */ { /// <summary> /// <para>Defines the default socket timeout (<code>SO_TIMEOUT</code>) in milliseconds which is the timeout for waiting for data. A timeout value of zero is interpreted as an infinite timeout. This value is used when no socket timeout is set in the method parameters. </para><para>This parameter expects a value of type Integer. </para><para><para>java.net.SocketOptions::SO_TIMEOUT </para></para> /// </summary> /// <java-name> /// SO_TIMEOUT /// </java-name> [Dot42.DexImport("SO_TIMEOUT", "Ljava/lang/String;", AccessFlags = 25)] public const string SO_TIMEOUT = "http.socket.timeout"; /// <summary> /// <para>Determines whether Nagle's algorithm is to be used. The Nagle's algorithm tries to conserve bandwidth by minimizing the number of segments that are sent. When applications wish to decrease network latency and increase performance, they can disable Nagle's algorithm (that is enable TCP_NODELAY). Data will be sent earlier, at the cost of an increase in bandwidth consumption. </para><para>This parameter expects a value of type Boolean. </para><para><para>java.net.SocketOptions::TCP_NODELAY </para></para> /// </summary> /// <java-name> /// TCP_NODELAY /// </java-name> [Dot42.DexImport("TCP_NODELAY", "Ljava/lang/String;", AccessFlags = 25)] public const string TCP_NODELAY = "http.tcp.nodelay"; /// <summary> /// <para>Determines the size of the internal socket buffer used to buffer data while receiving / transmitting HTTP messages. </para><para>This parameter expects a value of type Integer. </para> /// </summary> /// <java-name> /// SOCKET_BUFFER_SIZE /// </java-name> [Dot42.DexImport("SOCKET_BUFFER_SIZE", "Ljava/lang/String;", AccessFlags = 25)] public const string SOCKET_BUFFER_SIZE = "http.socket.buffer-size"; /// <summary> /// <para>Sets SO_LINGER with the specified linger time in seconds. The maximum timeout value is platform specific. Value <code>0</code> implies that the option is disabled. Value <code>-1</code> implies that the JRE default is used. The setting only affects socket close. </para><para>This parameter expects a value of type Integer. </para><para><para>java.net.SocketOptions::SO_LINGER </para></para> /// </summary> /// <java-name> /// SO_LINGER /// </java-name> [Dot42.DexImport("SO_LINGER", "Ljava/lang/String;", AccessFlags = 25)] public const string SO_LINGER = "http.socket.linger"; /// <summary> /// <para>Determines the timeout until a connection is etablished. A value of zero means the timeout is not used. The default value is zero. </para><para>This parameter expects a value of type Integer. </para> /// </summary> /// <java-name> /// CONNECTION_TIMEOUT /// </java-name> [Dot42.DexImport("CONNECTION_TIMEOUT", "Ljava/lang/String;", AccessFlags = 25)] public const string CONNECTION_TIMEOUT = "http.connection.timeout"; /// <summary> /// <para>Determines whether stale connection check is to be used. Disabling stale connection check may result in slight performance improvement at the risk of getting an I/O error when executing a request over a connection that has been closed at the server side. </para><para>This parameter expects a value of type Boolean. </para> /// </summary> /// <java-name> /// STALE_CONNECTION_CHECK /// </java-name> [Dot42.DexImport("STALE_CONNECTION_CHECK", "Ljava/lang/String;", AccessFlags = 25)] public const string STALE_CONNECTION_CHECK = "http.connection.stalecheck"; /// <summary> /// <para>Determines the maximum line length limit. If set to a positive value, any HTTP line exceeding this limit will cause an IOException. A negative or zero value will effectively disable the check. </para><para>This parameter expects a value of type Integer. </para> /// </summary> /// <java-name> /// MAX_LINE_LENGTH /// </java-name> [Dot42.DexImport("MAX_LINE_LENGTH", "Ljava/lang/String;", AccessFlags = 25)] public const string MAX_LINE_LENGTH = "http.connection.max-line-length"; /// <summary> /// <para>Determines the maximum HTTP header count allowed. If set to a positive value, the number of HTTP headers received from the data stream exceeding this limit will cause an IOException. A negative or zero value will effectively disable the check. </para><para>This parameter expects a value of type Integer. </para> /// </summary> /// <java-name> /// MAX_HEADER_COUNT /// </java-name> [Dot42.DexImport("MAX_HEADER_COUNT", "Ljava/lang/String;", AccessFlags = 25)] public const string MAX_HEADER_COUNT = "http.connection.max-header-count"; } /// <summary> /// <para>Defines parameter names for connections in HttpCore.</para><para><para></para><title>Revision:</title><para>576077 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/CoreConnectionPNames /// </java-name> [Dot42.DexImport("org/apache/http/params/CoreConnectionPNames", AccessFlags = 1537)] public partial interface ICoreConnectionPNames /* scope: __dot42__ */ { } /// <java-name> /// org/apache/http/params/HttpConnectionParamBean /// </java-name> [Dot42.DexImport("org/apache/http/params/HttpConnectionParamBean", AccessFlags = 33)] public partial class HttpConnectionParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public HttpConnectionParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { } /// <java-name> /// setSoTimeout /// </java-name> [Dot42.DexImport("setSoTimeout", "(I)V", AccessFlags = 1)] public virtual void SetSoTimeout(int soTimeout) /* MethodBuilder.Create */ { } /// <java-name> /// setTcpNoDelay /// </java-name> [Dot42.DexImport("setTcpNoDelay", "(Z)V", AccessFlags = 1)] public virtual void SetTcpNoDelay(bool tcpNoDelay) /* MethodBuilder.Create */ { } /// <java-name> /// setSocketBufferSize /// </java-name> [Dot42.DexImport("setSocketBufferSize", "(I)V", AccessFlags = 1)] public virtual void SetSocketBufferSize(int socketBufferSize) /* MethodBuilder.Create */ { } /// <java-name> /// setLinger /// </java-name> [Dot42.DexImport("setLinger", "(I)V", AccessFlags = 1)] public virtual void SetLinger(int linger) /* MethodBuilder.Create */ { } /// <java-name> /// setConnectionTimeout /// </java-name> [Dot42.DexImport("setConnectionTimeout", "(I)V", AccessFlags = 1)] public virtual void SetConnectionTimeout(int connectionTimeout) /* MethodBuilder.Create */ { } /// <java-name> /// setStaleCheckingEnabled /// </java-name> [Dot42.DexImport("setStaleCheckingEnabled", "(Z)V", AccessFlags = 1)] public virtual void SetStaleCheckingEnabled(bool staleCheckingEnabled) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal HttpConnectionParamBean() /* TypeBuilder.AddDefaultConstructor */ { } } /// <java-name> /// org/apache/http/params/HttpAbstractParamBean /// </java-name> [Dot42.DexImport("org/apache/http/params/HttpAbstractParamBean", AccessFlags = 1057)] public abstract partial class HttpAbstractParamBean /* scope: __dot42__ */ { /// <java-name> /// params /// </java-name> [Dot42.DexImport("params", "Lorg/apache/http/params/HttpParams;", AccessFlags = 20)] protected internal readonly global::Org.Apache.Http.Params.IHttpParams Params; [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public HttpAbstractParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal HttpAbstractParamBean() /* TypeBuilder.AddDefaultConstructor */ { } } }
/* * 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.IO; using System.Collections; using Lucene.Net.Analysis; using Lucene.Net.Analysis.Tokenattributes; using Lucene.Net.Util; namespace Lucene.Net.Analysis.NGram { /* * Tokenizes the input from an edge into n-grams of given size(s). * <p> * This <see cref="Tokenizer"/> create n-grams from the beginning edge or ending edge of a input token. * MaxGram can't be larger than 1024 because of limitation. * </p> */ public sealed class EdgeNGramTokenizer : Tokenizer { public static Side DEFAULT_SIDE = Side.FRONT; public static int DEFAULT_MAX_GRAM_SIZE = 1; public static int DEFAULT_MIN_GRAM_SIZE = 1; private ITermAttribute termAtt; private IOffsetAttribute offsetAtt; /* Specifies which side of the input the n-gram should be generated from */ // Moved Side enum from this class to external definition private int minGram; private int maxGram; private int gramSize; private Side side; private bool started = false; private int inLen; private string inStr; /* * Creates EdgeNGramTokenizer that can generate n-grams in the sizes of the given range * * <param name="input"><see cref="TextReader"/> holding the input to be tokenized</param> * <param name="side">the <see cref="Side"/> from which to chop off an n-gram</param> * <param name="minGram">the smallest n-gram to generate</param> * <param name="maxGram">the largest n-gram to generate</param> */ public EdgeNGramTokenizer(TextReader input, Side side, int minGram, int maxGram) : base(input) { init(side, minGram, maxGram); } /* * Creates EdgeNGramTokenizer that can generate n-grams in the sizes of the given range * * <param name="source"><see cref="AttributeSource"/> to use</param> * <param name="input"><see cref="TextReader"/> holding the input to be tokenized</param> * <param name="side">the <see cref="Side"/> from which to chop off an n-gram</param> * <param name="minGram">the smallest n-gram to generate</param> * <param name="maxGram">the largest n-gram to generate</param> */ public EdgeNGramTokenizer(AttributeSource source, TextReader input, Side side, int minGram, int maxGram) : base(source, input) { init(side, minGram, maxGram); } /* * Creates EdgeNGramTokenizer that can generate n-grams in the sizes of the given range * * <param name="factory"><see cref="AttributeSource.AttributeFactory"/> to use</param> * <param name="input"><see cref="TextReader"/> holding the input to be tokenized</param> * <param name="side">the <see cref="Side"/> from which to chop off an n-gram</param> * <param name="minGram">the smallest n-gram to generate</param> * <param name="maxGram">the largest n-gram to generate</param> */ public EdgeNGramTokenizer(AttributeFactory factory, TextReader input, Side side, int minGram, int maxGram) : base(factory, input) { init(side, minGram, maxGram); } /* * Creates EdgeNGramTokenizer that can generate n-grams in the sizes of the given range * * <param name="input"><see cref="TextReader"/> holding the input to be tokenized</param> * <param name="sideLabel">the name of the <see cref="Side"/> from which to chop off an n-gram</param> * <param name="minGram">the smallest n-gram to generate</param> * <param name="maxGram">the largest n-gram to generate</param> */ public EdgeNGramTokenizer(TextReader input, string sideLabel, int minGram, int maxGram) : this(input, SideExtensions.GetSide(sideLabel), minGram, maxGram) { } /* * Creates EdgeNGramTokenizer that can generate n-grams in the sizes of the given range * * <param name="source"><see cref="AttributeSource"/> to use</param> * <param name="input"><see cref="TextReader"/> holding the input to be tokenized</param> * <param name="sideLabel">the name of the <see cref="Side"/> from which to chop off an n-gram</param> * <param name="minGram">the smallest n-gram to generate</param> * <param name="maxGram">the largest n-gram to generate</param> */ public EdgeNGramTokenizer(AttributeSource source, TextReader input, string sideLabel, int minGram, int maxGram) : this(source, input, SideExtensions.GetSide(sideLabel), minGram, maxGram) { } /* * Creates EdgeNGramTokenizer that can generate n-grams in the sizes of the given range * * <param name="factory"><see cref="AttributeSource.AttributeFactory"/> to use</param> * <param name="input"><see cref="TextReader"/> holding the input to be tokenized</param> * <param name="sideLabel">the name of the <see cref="Side"/> from which to chop off an n-gram</param> * <param name="minGram">the smallest n-gram to generate</param> * <param name="maxGram">the largest n-gram to generate</param> */ public EdgeNGramTokenizer(AttributeFactory factory, TextReader input, string sideLabel, int minGram, int maxGram) : this(factory, input, SideExtensions.GetSide(sideLabel), minGram, maxGram) { } private void init(Side side, int minGram, int maxGram) { if (side == null) { throw new System.ArgumentException("sideLabel must be either front or back"); } if (minGram < 1) { throw new System.ArgumentException("minGram must be greater than zero"); } if (minGram > maxGram) { throw new System.ArgumentException("minGram must not be greater than maxGram"); } this.minGram = minGram; this.maxGram = maxGram; this.side = side; this.termAtt = AddAttribute<ITermAttribute>(); this.offsetAtt = AddAttribute<IOffsetAttribute>(); } /* Returns the next token in the stream, or null at EOS. */ public override bool IncrementToken() { ClearAttributes(); // if we are just starting, read the whole input if (!started) { started = true; char[] chars = new char[1024]; inStr = input.ReadToEnd().Trim(); // remove any leading or trailing spaces inLen = inStr.Length; gramSize = minGram; } // if the remaining input is too short, we can't generate any n-grams if (gramSize > inLen) { return false; } // if we have hit the end of our n-gram size range, quit if (gramSize > maxGram) { return false; } // grab gramSize chars from front or back int start = side == Side.FRONT ? 0 : inLen - gramSize; int end = start + gramSize; termAtt.SetTermBuffer(inStr, start, gramSize); offsetAtt.SetOffset(CorrectOffset(start), CorrectOffset(end)); gramSize++; return true; } public override void End() { // set offset int finalOffset = inLen; this.offsetAtt.SetOffset(finalOffset, finalOffset); } public override void Reset(TextReader input) { base.Reset(input); Reset(); } public override void Reset() { base.Reset(); started = false; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace GitHub.Unity { public class TaskQueue : TPLTask { private TaskCompletionSource<bool> aggregateTask = new TaskCompletionSource<bool>(); private readonly List<ITask> queuedTasks = new List<ITask>(); private int finishedTaskCount; public TaskQueue() : base() { Initialize(aggregateTask.Task); } public ITask Queue(ITask task) { // if this task fails, both OnEnd and Catch will be called // if a task before this one on the chain fails, only Catch will be called // so avoid calling TaskFinished twice by ignoring failed OnEnd calls task.OnEnd += InvokeFinishOnlyOnSuccess; task.Catch(e => TaskFinished(false, e)); queuedTasks.Add(task); return this; } public override void RunSynchronously() { if (queuedTasks.Any()) { foreach (var task in queuedTasks) task.Start(); } else { aggregateTask.TrySetResult(true); } base.RunSynchronously(); } protected override void Schedule() { if (queuedTasks.Any()) { foreach (var task in queuedTasks) task.Start(); } else { aggregateTask.TrySetResult(true); } base.Schedule(); } private void InvokeFinishOnlyOnSuccess(ITask task, bool success, Exception ex) { if (success) TaskFinished(true, null); } private void TaskFinished(bool success, Exception ex) { var count = Interlocked.Increment(ref finishedTaskCount); if (count == queuedTasks.Count) { var exceptions = queuedTasks.Where(x => !x.Successful).Select(x => x.Exception).ToArray(); var isSuccessful = exceptions.Length == 0; if (isSuccessful) { aggregateTask.TrySetResult(true); } else { aggregateTask.TrySetException(new AggregateException(exceptions)); } } } } public class TaskQueue<TTaskResult, TResult> : TPLTask<List<TResult>> { private TaskCompletionSource<List<TResult>> aggregateTask = new TaskCompletionSource<List<TResult>>(); private readonly List<ITask<TTaskResult>> queuedTasks = new List<ITask<TTaskResult>>(); private int finishedTaskCount; private Func<ITask<TTaskResult>, TResult> resultConverter; /// <summary> /// If <typeparamref name="TTaskResult"/> is not assignable to <typeparamref name="TResult"/>, you must pass a /// method to convert between the two. Implicit conversions don't count (so even though NPath has an implicit /// conversion to string, you still need to pass in a converter) /// </summary> /// <param name="resultConverter"></param> public TaskQueue(Func<ITask<TTaskResult>, TResult> resultConverter = null) : base() { // this excludes implicit operators - that requires using reflection to figure out if // the types are convertible, and I'd rather not do that if (resultConverter == null && !typeof(TResult).IsAssignableFrom(typeof(TTaskResult))) { throw new ArgumentNullException(nameof(resultConverter), String.Format(CultureInfo.InvariantCulture, "Cannot cast {0} to {1} and no {2} method was passed in to do the conversion", typeof(TTaskResult), typeof(TResult), nameof(resultConverter))); } this.resultConverter = resultConverter; Initialize(aggregateTask.Task); } /// <summary> /// Queues an ITask for running, and when the task is done, <paramref name="theResultConverter"/> is called /// to convert the result of the task to something else /// </summary> /// <param name="task"></param> /// /// <returns></returns> public ITask<TTaskResult> Queue(ITask<TTaskResult> task) { // if this task fails, both OnEnd and Catch will be called // if a task before this one on the chain fails, only Catch will be called // so avoid calling TaskFinished twice by ignoring failed OnEnd calls task.OnEnd += InvokeFinishOnlyOnSuccess; task.Catch(e => TaskFinished(default(TTaskResult), false, e)); queuedTasks.Add(task); return task; } public override List<TResult> RunSynchronously() { if (queuedTasks.Any()) { foreach (var task in queuedTasks) task.Start(); } else { aggregateTask.TrySetResult(new List<TResult>()); } return base.RunSynchronously(); } protected override void Schedule() { if (queuedTasks.Any()) { foreach (var task in queuedTasks) task.Start(); } else { aggregateTask.TrySetResult(new List<TResult>()); } base.Schedule(); } private void InvokeFinishOnlyOnSuccess(ITask<TTaskResult> task, TTaskResult result, bool success, Exception ex) { if (success) TaskFinished(result, true, null); } private void TaskFinished(TTaskResult result, bool success, Exception ex) { var count = Interlocked.Increment(ref finishedTaskCount); if (count == queuedTasks.Count) { var exceptions = queuedTasks.Where(x => !x.Successful).Select(x => x.Exception).ToArray(); var isSuccessful = exceptions.Length == 0; if (isSuccessful) { List<TResult> results; if (resultConverter != null) results = queuedTasks.Select(x => resultConverter(x)).ToList(); else results = queuedTasks.Select(x => (TResult)(object)x.Result).ToList(); aggregateTask.TrySetResult(results); } else { aggregateTask.TrySetException(new AggregateException(exceptions)); } } } } public class TPLTask : TaskBase { private Task task; protected TPLTask() : base() {} public TPLTask(Task task) : base() { Initialize(task); } protected void Initialize(Task theTask) { this.task = theTask; Task = new Task(RunSynchronously, Token, TaskCreationOptions.None); } protected override void Run(bool success) { base.Run(success); Token.ThrowIfCancellationRequested(); try { if (task.Status == TaskStatus.Created && !task.IsCompleted && ((task.CreationOptions & (TaskCreationOptions)512) == TaskCreationOptions.None)) { var scheduler = TaskManager.GetScheduler(Affinity); Token.ThrowIfCancellationRequested(); task.RunSynchronously(scheduler); } else task.Wait(); } catch (Exception ex) { if (!RaiseFaultHandlers(ex)) throw exception; Token.ThrowIfCancellationRequested(); } } } public class TPLTask<T> : TaskBase<T> { private Task<T> task; protected TPLTask() : base() { } public TPLTask(Task<T> task) : base() { Initialize(task); } protected void Initialize(Task<T> theTask) { this.task = theTask; Task = new Task<T>(RunSynchronously, Token, TaskCreationOptions.None); } protected override T RunWithReturn(bool success) { var ret = base.RunWithReturn(success); Token.ThrowIfCancellationRequested(); try { if (task.Status == TaskStatus.Created && !task.IsCompleted && ((task.CreationOptions & (TaskCreationOptions)512) == TaskCreationOptions.None)) { var scheduler = TaskManager.GetScheduler(Affinity); Token.ThrowIfCancellationRequested(); task.RunSynchronously(scheduler); } ret = task.Result; } catch (Exception ex) { if (!RaiseFaultHandlers(ex)) throw exception; Token.ThrowIfCancellationRequested(); } return ret; } } public class ActionTask : TaskBase { protected Action<bool> Callback { get; } protected Action<bool, Exception> CallbackWithException { get; } public ActionTask(CancellationToken token, Action action) : base(token) { Guard.ArgumentNotNull(action, "action"); this.Callback = _ => action(); Name = "ActionTask"; } public ActionTask(CancellationToken token, Action<bool> action) : base(token) { Guard.ArgumentNotNull(action, "action"); this.Callback = action; Name = "ActionTask"; } public ActionTask(CancellationToken token, Action<bool, Exception> action) : base(token) { Guard.ArgumentNotNull(action, "action"); this.CallbackWithException = action; Name = "ActionTask<Exception>"; } protected override void Run(bool success) { base.Run(success); try { Callback?.Invoke(success); if (CallbackWithException != null) { var thrown = GetThrownException(); CallbackWithException?.Invoke(success, thrown); } } catch (Exception ex) { if (!RaiseFaultHandlers(ex)) throw exception; } } } public class ActionTask<T> : TaskBase { private readonly Func<T> getPreviousResult; protected Action<bool, T> Callback { get; } protected Action<bool, Exception, T> CallbackWithException { get; } /// <summary> /// /// </summary> /// <param name="token"></param> /// <param name="action"></param> /// <param name="getPreviousResult">Method to call that returns the value that this task is going to work with. You can also use the PreviousResult property to set this value</param> public ActionTask(CancellationToken token, Action<bool, T> action, Func<T> getPreviousResult = null) : base(token) { Guard.ArgumentNotNull(action, "action"); this.Callback = action; this.getPreviousResult = getPreviousResult; Task = new Task(RunSynchronously, Token, TaskCreationOptions.None); Name = $"ActionTask<{typeof(T)}>"; } /// <summary> /// /// </summary> /// <param name="token"></param> /// <param name="action"></param> /// <param name="getPreviousResult">Method to call that returns the value that this task is going to work with. You can also use the PreviousResult property to set this value</param> public ActionTask(CancellationToken token, Action<bool, Exception, T> action, Func<T> getPreviousResult = null) : base(token) { Guard.ArgumentNotNull(action, "action"); this.CallbackWithException = action; this.getPreviousResult = getPreviousResult; Task = new Task(RunSynchronously, Token, TaskCreationOptions.None); Name = $"ActionTask<Exception, {typeof(T)}>"; } public override void RunSynchronously() { RaiseOnStart(); Token.ThrowIfCancellationRequested(); var previousIsSuccessful = previousSuccess.HasValue ? previousSuccess.Value : (DependsOn?.Successful ?? true); // if this task depends on another task and the dependent task was successful, use the value of that other task as input to this task // otherwise if there's a method to retrieve the value, call that // otherwise use the PreviousResult property T prevResult = PreviousResult; if (previousIsSuccessful && DependsOn != null && DependsOn is ITask<T>) prevResult = ((ITask<T>)DependsOn).Result; else if (getPreviousResult != null) prevResult = getPreviousResult(); try { Run(previousIsSuccessful, prevResult); } finally { RaiseOnEnd(); } } protected virtual void Run(bool success, T previousResult) { base.Run(success); try { Callback?.Invoke(success, previousResult); if (CallbackWithException != null) { var thrown = GetThrownException(); CallbackWithException?.Invoke(success, thrown, previousResult); } } catch (Exception ex) { if (!RaiseFaultHandlers(ex)) throw exception; } } public T PreviousResult { get; set; } = default(T); } public class FuncTask<T> : TaskBase<T> { protected Func<bool, T> Callback { get; } protected Func<bool, Exception, T> CallbackWithException { get; } public FuncTask(CancellationToken token, Func<T> action) : base(token) { Guard.ArgumentNotNull(action, "action"); this.Callback = _ => action(); Name = $"FuncTask<{typeof(T)}>"; } public FuncTask(CancellationToken token, Func<bool, T> action) : base(token) { Guard.ArgumentNotNull(action, "action"); this.Callback = action; Name = $"FuncTask<{typeof(T)}>"; } public FuncTask(CancellationToken token, Func<bool, Exception, T> action) : base(token) { Guard.ArgumentNotNull(action, "action"); this.CallbackWithException = action; Name = $"FuncTask<Exception, {typeof(T)}>"; } protected override T RunWithReturn(bool success) { T result = base.RunWithReturn(success); try { if (Callback != null) { result = Callback(success); } else if (CallbackWithException != null) { var thrown = GetThrownException(); result = CallbackWithException(success, thrown); } } catch (Exception ex) { if (!RaiseFaultHandlers(ex)) throw exception; } return result; } } public class FuncTask<T, TResult> : TaskBase<T, TResult> { protected Func<bool, T, TResult> Callback { get; } protected Func<bool, Exception, T, TResult> CallbackWithException { get; } public FuncTask(CancellationToken token, Func<bool, T, TResult> action, Func<T> getPreviousResult = null) : base(token, getPreviousResult) { Guard.ArgumentNotNull(action, "action"); this.Callback = action; Name = $"FuncTask<{typeof(T)}, {typeof(TResult)}>"; } public FuncTask(CancellationToken token, Func<bool, Exception, T, TResult> action, Func<T> getPreviousResult = null) : base(token, getPreviousResult) { Guard.ArgumentNotNull(action, "action"); this.CallbackWithException = action; Name = $"FuncTask<{typeof(T)}, Exception, {typeof(TResult)}>"; } protected override TResult RunWithData(bool success, T previousResult) { var result = base.RunWithData(success, previousResult); try { if (Callback != null) { result = Callback(success, previousResult); } else if (CallbackWithException != null) { var thrown = GetThrownException(); result = CallbackWithException(success, thrown, previousResult); } } catch (Exception ex) { if (!RaiseFaultHandlers(ex)) throw exception; } return result; } } public class FuncListTask<T> : DataTaskBase<T, List<T>> { protected Func<bool, List<T>> Callback { get; } protected Func<bool, FuncListTask<T>, List<T>> CallbackWithSelf { get; } protected Func<bool, Exception, List<T>> CallbackWithException { get; } public FuncListTask(CancellationToken token, Func<bool, List<T>> action) : base(token) { Guard.ArgumentNotNull(action, "action"); this.Callback = action; } public FuncListTask(CancellationToken token, Func<bool, Exception, List<T>> action) : base(token) { Guard.ArgumentNotNull(action, "action"); this.CallbackWithException = action; } public FuncListTask(CancellationToken token, Func<bool, FuncListTask<T>, List<T>> action) : base(token) { Guard.ArgumentNotNull(action, "action"); this.CallbackWithSelf = action; } protected override List<T> RunWithReturn(bool success) { var result = base.RunWithReturn(success); try { if (Callback != null) { result = Callback(success); } else if (CallbackWithSelf != null) { result = CallbackWithSelf(success, this); } else if (CallbackWithException != null) { var thrown = GetThrownException(); result = CallbackWithException(success, thrown); } } catch (Exception ex) { if (!RaiseFaultHandlers(ex)) throw exception; } finally { if (result == null) result = new List<T>(); } return result; } } public class FuncListTask<T, TData, TResult> : DataTaskBase<T, TData, List<TResult>> { protected Func<bool, T, List<TResult>> Callback { get; } protected Func<bool, Exception, T, List<TResult>> CallbackWithException { get; } public FuncListTask(CancellationToken token, Func<bool, T, List<TResult>> action) : base(token) { Guard.ArgumentNotNull(action, "action"); this.Callback = action; } public FuncListTask(CancellationToken token, Func<bool, Exception, T, List<TResult>> action) : base(token) { Guard.ArgumentNotNull(action, "action"); this.CallbackWithException = action; } protected override List<TResult> RunWithData(bool success, T previousResult) { var result = base.RunWithData(success, previousResult); try { if (Callback != null) { result = Callback(success, previousResult); } else if (CallbackWithException != null) { var thrown = GetThrownException(); result = CallbackWithException(success, thrown, previousResult); } } catch (Exception ex) { if (!RaiseFaultHandlers(ex)) throw exception; } return result; } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * 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; using System.Collections.Generic; using CookComputing.XmlRpc; namespace XenAPI { /// <summary> /// A physical GPU (pGPU) /// First published in XenServer 6.0. /// </summary> public partial class PGPU : XenObject<PGPU> { public PGPU() { } public PGPU(string uuid, XenRef<PCI> PCI, XenRef<GPU_group> GPU_group, XenRef<Host> host, Dictionary<string, string> other_config, List<XenRef<VGPU_type>> supported_VGPU_types, List<XenRef<VGPU_type>> enabled_VGPU_types, List<XenRef<VGPU>> resident_VGPUs, Dictionary<XenRef<VGPU_type>, long> supported_VGPU_max_capacities, pgpu_dom0_access dom0_access, bool is_system_display_device) { this.uuid = uuid; this.PCI = PCI; this.GPU_group = GPU_group; this.host = host; this.other_config = other_config; this.supported_VGPU_types = supported_VGPU_types; this.enabled_VGPU_types = enabled_VGPU_types; this.resident_VGPUs = resident_VGPUs; this.supported_VGPU_max_capacities = supported_VGPU_max_capacities; this.dom0_access = dom0_access; this.is_system_display_device = is_system_display_device; } /// <summary> /// Creates a new PGPU from a Proxy_PGPU. /// </summary> /// <param name="proxy"></param> public PGPU(Proxy_PGPU proxy) { this.UpdateFromProxy(proxy); } public override void UpdateFrom(PGPU update) { uuid = update.uuid; PCI = update.PCI; GPU_group = update.GPU_group; host = update.host; other_config = update.other_config; supported_VGPU_types = update.supported_VGPU_types; enabled_VGPU_types = update.enabled_VGPU_types; resident_VGPUs = update.resident_VGPUs; supported_VGPU_max_capacities = update.supported_VGPU_max_capacities; dom0_access = update.dom0_access; is_system_display_device = update.is_system_display_device; } internal void UpdateFromProxy(Proxy_PGPU proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; PCI = proxy.PCI == null ? null : XenRef<PCI>.Create(proxy.PCI); GPU_group = proxy.GPU_group == null ? null : XenRef<GPU_group>.Create(proxy.GPU_group); host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host); other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); supported_VGPU_types = proxy.supported_VGPU_types == null ? null : XenRef<VGPU_type>.Create(proxy.supported_VGPU_types); enabled_VGPU_types = proxy.enabled_VGPU_types == null ? null : XenRef<VGPU_type>.Create(proxy.enabled_VGPU_types); resident_VGPUs = proxy.resident_VGPUs == null ? null : XenRef<VGPU>.Create(proxy.resident_VGPUs); supported_VGPU_max_capacities = proxy.supported_VGPU_max_capacities == null ? null : Maps.convert_from_proxy_XenRefVGPU_type_long(proxy.supported_VGPU_max_capacities); dom0_access = proxy.dom0_access == null ? (pgpu_dom0_access) 0 : (pgpu_dom0_access)Helper.EnumParseDefault(typeof(pgpu_dom0_access), (string)proxy.dom0_access); is_system_display_device = (bool)proxy.is_system_display_device; } public Proxy_PGPU ToProxy() { Proxy_PGPU result_ = new Proxy_PGPU(); result_.uuid = (uuid != null) ? uuid : ""; result_.PCI = (PCI != null) ? PCI : ""; result_.GPU_group = (GPU_group != null) ? GPU_group : ""; result_.host = (host != null) ? host : ""; result_.other_config = Maps.convert_to_proxy_string_string(other_config); result_.supported_VGPU_types = (supported_VGPU_types != null) ? Helper.RefListToStringArray(supported_VGPU_types) : new string[] {}; result_.enabled_VGPU_types = (enabled_VGPU_types != null) ? Helper.RefListToStringArray(enabled_VGPU_types) : new string[] {}; result_.resident_VGPUs = (resident_VGPUs != null) ? Helper.RefListToStringArray(resident_VGPUs) : new string[] {}; result_.supported_VGPU_max_capacities = Maps.convert_to_proxy_XenRefVGPU_type_long(supported_VGPU_max_capacities); result_.dom0_access = pgpu_dom0_access_helper.ToString(dom0_access); result_.is_system_display_device = is_system_display_device; return result_; } /// <summary> /// Creates a new PGPU from a Hashtable. /// </summary> /// <param name="table"></param> public PGPU(Hashtable table) { uuid = Marshalling.ParseString(table, "uuid"); PCI = Marshalling.ParseRef<PCI>(table, "PCI"); GPU_group = Marshalling.ParseRef<GPU_group>(table, "GPU_group"); host = Marshalling.ParseRef<Host>(table, "host"); other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); supported_VGPU_types = Marshalling.ParseSetRef<VGPU_type>(table, "supported_VGPU_types"); enabled_VGPU_types = Marshalling.ParseSetRef<VGPU_type>(table, "enabled_VGPU_types"); resident_VGPUs = Marshalling.ParseSetRef<VGPU>(table, "resident_VGPUs"); supported_VGPU_max_capacities = Maps.convert_from_proxy_XenRefVGPU_type_long(Marshalling.ParseHashTable(table, "supported_VGPU_max_capacities")); dom0_access = (pgpu_dom0_access)Helper.EnumParseDefault(typeof(pgpu_dom0_access), Marshalling.ParseString(table, "dom0_access")); is_system_display_device = Marshalling.ParseBool(table, "is_system_display_device"); } public bool DeepEquals(PGPU other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._PCI, other._PCI) && Helper.AreEqual2(this._GPU_group, other._GPU_group) && Helper.AreEqual2(this._host, other._host) && Helper.AreEqual2(this._other_config, other._other_config) && Helper.AreEqual2(this._supported_VGPU_types, other._supported_VGPU_types) && Helper.AreEqual2(this._enabled_VGPU_types, other._enabled_VGPU_types) && Helper.AreEqual2(this._resident_VGPUs, other._resident_VGPUs) && Helper.AreEqual2(this._supported_VGPU_max_capacities, other._supported_VGPU_max_capacities) && Helper.AreEqual2(this._dom0_access, other._dom0_access) && Helper.AreEqual2(this._is_system_display_device, other._is_system_display_device); } public override string SaveChanges(Session session, string opaqueRef, PGPU server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { if (!Helper.AreEqual2(_other_config, server._other_config)) { PGPU.set_other_config(session, opaqueRef, _other_config); } if (!Helper.AreEqual2(_GPU_group, server._GPU_group)) { PGPU.set_GPU_group(session, opaqueRef, _GPU_group); } return null; } } /// <summary> /// Get a record containing the current state of the given PGPU. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> public static PGPU get_record(Session session, string _pgpu) { return new PGPU((Proxy_PGPU)session.proxy.pgpu_get_record(session.uuid, (_pgpu != null) ? _pgpu : "").parse()); } /// <summary> /// Get a reference to the PGPU instance with the specified UUID. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<PGPU> get_by_uuid(Session session, string _uuid) { return XenRef<PGPU>.Create(session.proxy.pgpu_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse()); } /// <summary> /// Get the uuid field of the given PGPU. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> public static string get_uuid(Session session, string _pgpu) { return (string)session.proxy.pgpu_get_uuid(session.uuid, (_pgpu != null) ? _pgpu : "").parse(); } /// <summary> /// Get the PCI field of the given PGPU. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> public static XenRef<PCI> get_PCI(Session session, string _pgpu) { return XenRef<PCI>.Create(session.proxy.pgpu_get_pci(session.uuid, (_pgpu != null) ? _pgpu : "").parse()); } /// <summary> /// Get the GPU_group field of the given PGPU. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> public static XenRef<GPU_group> get_GPU_group(Session session, string _pgpu) { return XenRef<GPU_group>.Create(session.proxy.pgpu_get_gpu_group(session.uuid, (_pgpu != null) ? _pgpu : "").parse()); } /// <summary> /// Get the host field of the given PGPU. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> public static XenRef<Host> get_host(Session session, string _pgpu) { return XenRef<Host>.Create(session.proxy.pgpu_get_host(session.uuid, (_pgpu != null) ? _pgpu : "").parse()); } /// <summary> /// Get the other_config field of the given PGPU. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> public static Dictionary<string, string> get_other_config(Session session, string _pgpu) { return Maps.convert_from_proxy_string_string(session.proxy.pgpu_get_other_config(session.uuid, (_pgpu != null) ? _pgpu : "").parse()); } /// <summary> /// Get the supported_VGPU_types field of the given PGPU. /// First published in XenServer 6.2 SP1 Tech-Preview. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> public static List<XenRef<VGPU_type>> get_supported_VGPU_types(Session session, string _pgpu) { return XenRef<VGPU_type>.Create(session.proxy.pgpu_get_supported_vgpu_types(session.uuid, (_pgpu != null) ? _pgpu : "").parse()); } /// <summary> /// Get the enabled_VGPU_types field of the given PGPU. /// First published in XenServer 6.2 SP1 Tech-Preview. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> public static List<XenRef<VGPU_type>> get_enabled_VGPU_types(Session session, string _pgpu) { return XenRef<VGPU_type>.Create(session.proxy.pgpu_get_enabled_vgpu_types(session.uuid, (_pgpu != null) ? _pgpu : "").parse()); } /// <summary> /// Get the resident_VGPUs field of the given PGPU. /// First published in XenServer 6.2 SP1 Tech-Preview. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> public static List<XenRef<VGPU>> get_resident_VGPUs(Session session, string _pgpu) { return XenRef<VGPU>.Create(session.proxy.pgpu_get_resident_vgpus(session.uuid, (_pgpu != null) ? _pgpu : "").parse()); } /// <summary> /// Get the supported_VGPU_max_capacities field of the given PGPU. /// First published in XenServer 6.2 SP1. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> public static Dictionary<XenRef<VGPU_type>, long> get_supported_VGPU_max_capacities(Session session, string _pgpu) { return Maps.convert_from_proxy_XenRefVGPU_type_long(session.proxy.pgpu_get_supported_vgpu_max_capacities(session.uuid, (_pgpu != null) ? _pgpu : "").parse()); } /// <summary> /// Get the dom0_access field of the given PGPU. /// First published in XenServer 6.5 SP1. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> public static pgpu_dom0_access get_dom0_access(Session session, string _pgpu) { return (pgpu_dom0_access)Helper.EnumParseDefault(typeof(pgpu_dom0_access), (string)session.proxy.pgpu_get_dom0_access(session.uuid, (_pgpu != null) ? _pgpu : "").parse()); } /// <summary> /// Get the is_system_display_device field of the given PGPU. /// First published in XenServer 6.5 SP1. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> public static bool get_is_system_display_device(Session session, string _pgpu) { return (bool)session.proxy.pgpu_get_is_system_display_device(session.uuid, (_pgpu != null) ? _pgpu : "").parse(); } /// <summary> /// Set the other_config field of the given PGPU. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _pgpu, Dictionary<string, string> _other_config) { session.proxy.pgpu_set_other_config(session.uuid, (_pgpu != null) ? _pgpu : "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given PGPU. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _pgpu, string _key, string _value) { session.proxy.pgpu_add_to_other_config(session.uuid, (_pgpu != null) ? _pgpu : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given PGPU. If the key is not in that Map, then do nothing. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _pgpu, string _key) { session.proxy.pgpu_remove_from_other_config(session.uuid, (_pgpu != null) ? _pgpu : "", (_key != null) ? _key : "").parse(); } /// <summary> /// /// First published in XenServer 6.2 SP1 Tech-Preview. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> /// <param name="_value">The VGPU type to enable</param> public static void add_enabled_VGPU_types(Session session, string _pgpu, string _value) { session.proxy.pgpu_add_enabled_vgpu_types(session.uuid, (_pgpu != null) ? _pgpu : "", (_value != null) ? _value : "").parse(); } /// <summary> /// /// First published in XenServer 6.2 SP1 Tech-Preview. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> /// <param name="_value">The VGPU type to enable</param> public static XenRef<Task> async_add_enabled_VGPU_types(Session session, string _pgpu, string _value) { return XenRef<Task>.Create(session.proxy.async_pgpu_add_enabled_vgpu_types(session.uuid, (_pgpu != null) ? _pgpu : "", (_value != null) ? _value : "").parse()); } /// <summary> /// /// First published in XenServer 6.2 SP1 Tech-Preview. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> /// <param name="_value">The VGPU type to disable</param> public static void remove_enabled_VGPU_types(Session session, string _pgpu, string _value) { session.proxy.pgpu_remove_enabled_vgpu_types(session.uuid, (_pgpu != null) ? _pgpu : "", (_value != null) ? _value : "").parse(); } /// <summary> /// /// First published in XenServer 6.2 SP1 Tech-Preview. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> /// <param name="_value">The VGPU type to disable</param> public static XenRef<Task> async_remove_enabled_VGPU_types(Session session, string _pgpu, string _value) { return XenRef<Task>.Create(session.proxy.async_pgpu_remove_enabled_vgpu_types(session.uuid, (_pgpu != null) ? _pgpu : "", (_value != null) ? _value : "").parse()); } /// <summary> /// /// First published in XenServer 6.2 SP1 Tech-Preview. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> /// <param name="_value">The VGPU types to enable</param> public static void set_enabled_VGPU_types(Session session, string _pgpu, List<XenRef<VGPU_type>> _value) { session.proxy.pgpu_set_enabled_vgpu_types(session.uuid, (_pgpu != null) ? _pgpu : "", (_value != null) ? Helper.RefListToStringArray(_value) : new string[] {}).parse(); } /// <summary> /// /// First published in XenServer 6.2 SP1 Tech-Preview. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> /// <param name="_value">The VGPU types to enable</param> public static XenRef<Task> async_set_enabled_VGPU_types(Session session, string _pgpu, List<XenRef<VGPU_type>> _value) { return XenRef<Task>.Create(session.proxy.async_pgpu_set_enabled_vgpu_types(session.uuid, (_pgpu != null) ? _pgpu : "", (_value != null) ? Helper.RefListToStringArray(_value) : new string[] {}).parse()); } /// <summary> /// /// First published in XenServer 6.2 SP1 Tech-Preview. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> /// <param name="_value">The group to which the PGPU will be moved</param> public static void set_GPU_group(Session session, string _pgpu, string _value) { session.proxy.pgpu_set_gpu_group(session.uuid, (_pgpu != null) ? _pgpu : "", (_value != null) ? _value : "").parse(); } /// <summary> /// /// First published in XenServer 6.2 SP1 Tech-Preview. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> /// <param name="_value">The group to which the PGPU will be moved</param> public static XenRef<Task> async_set_GPU_group(Session session, string _pgpu, string _value) { return XenRef<Task>.Create(session.proxy.async_pgpu_set_gpu_group(session.uuid, (_pgpu != null) ? _pgpu : "", (_value != null) ? _value : "").parse()); } /// <summary> /// /// First published in XenServer 6.2 SP1 Tech-Preview. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> /// <param name="_vgpu_type">The VGPU type for which we want to find the number of VGPUs which can still be started on this PGPU</param> public static long get_remaining_capacity(Session session, string _pgpu, string _vgpu_type) { return long.Parse((string)session.proxy.pgpu_get_remaining_capacity(session.uuid, (_pgpu != null) ? _pgpu : "", (_vgpu_type != null) ? _vgpu_type : "").parse()); } /// <summary> /// /// First published in XenServer 6.2 SP1 Tech-Preview. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> /// <param name="_vgpu_type">The VGPU type for which we want to find the number of VGPUs which can still be started on this PGPU</param> public static XenRef<Task> async_get_remaining_capacity(Session session, string _pgpu, string _vgpu_type) { return XenRef<Task>.Create(session.proxy.async_pgpu_get_remaining_capacity(session.uuid, (_pgpu != null) ? _pgpu : "", (_vgpu_type != null) ? _vgpu_type : "").parse()); } /// <summary> /// /// First published in XenServer 6.5 SP1. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> public static pgpu_dom0_access enable_dom0_access(Session session, string _pgpu) { return (pgpu_dom0_access)Helper.EnumParseDefault(typeof(pgpu_dom0_access), (string)session.proxy.pgpu_enable_dom0_access(session.uuid, (_pgpu != null) ? _pgpu : "").parse()); } /// <summary> /// /// First published in XenServer 6.5 SP1. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> public static XenRef<Task> async_enable_dom0_access(Session session, string _pgpu) { return XenRef<Task>.Create(session.proxy.async_pgpu_enable_dom0_access(session.uuid, (_pgpu != null) ? _pgpu : "").parse()); } /// <summary> /// /// First published in XenServer 6.5 SP1. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> public static pgpu_dom0_access disable_dom0_access(Session session, string _pgpu) { return (pgpu_dom0_access)Helper.EnumParseDefault(typeof(pgpu_dom0_access), (string)session.proxy.pgpu_disable_dom0_access(session.uuid, (_pgpu != null) ? _pgpu : "").parse()); } /// <summary> /// /// First published in XenServer 6.5 SP1. /// </summary> /// <param name="session">The session</param> /// <param name="_pgpu">The opaque_ref of the given pgpu</param> public static XenRef<Task> async_disable_dom0_access(Session session, string _pgpu) { return XenRef<Task>.Create(session.proxy.async_pgpu_disable_dom0_access(session.uuid, (_pgpu != null) ? _pgpu : "").parse()); } /// <summary> /// Return a list of all the PGPUs known to the system. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> public static List<XenRef<PGPU>> get_all(Session session) { return XenRef<PGPU>.Create(session.proxy.pgpu_get_all(session.uuid).parse()); } /// <summary> /// Get all the PGPU Records at once, in a single XML RPC call /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<PGPU>, PGPU> get_all_records(Session session) { return XenRef<PGPU>.Create<Proxy_PGPU>(session.proxy.pgpu_get_all_records(session.uuid).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid; /// <summary> /// Link to underlying PCI device /// </summary> public virtual XenRef<PCI> PCI { get { return _PCI; } set { if (!Helper.AreEqual(value, _PCI)) { _PCI = value; Changed = true; NotifyPropertyChanged("PCI"); } } } private XenRef<PCI> _PCI; /// <summary> /// GPU group the pGPU is contained in /// </summary> public virtual XenRef<GPU_group> GPU_group { get { return _GPU_group; } set { if (!Helper.AreEqual(value, _GPU_group)) { _GPU_group = value; Changed = true; NotifyPropertyChanged("GPU_group"); } } } private XenRef<GPU_group> _GPU_group; /// <summary> /// Host that own the GPU /// </summary> public virtual XenRef<Host> host { get { return _host; } set { if (!Helper.AreEqual(value, _host)) { _host = value; Changed = true; NotifyPropertyChanged("host"); } } } private XenRef<Host> _host; /// <summary> /// Additional configuration /// </summary> public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; Changed = true; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config; /// <summary> /// List of VGPU types supported by the underlying hardware /// First published in XenServer 6.2 SP1 Tech-Preview. /// </summary> public virtual List<XenRef<VGPU_type>> supported_VGPU_types { get { return _supported_VGPU_types; } set { if (!Helper.AreEqual(value, _supported_VGPU_types)) { _supported_VGPU_types = value; Changed = true; NotifyPropertyChanged("supported_VGPU_types"); } } } private List<XenRef<VGPU_type>> _supported_VGPU_types; /// <summary> /// List of VGPU types which have been enabled for this PGPU /// First published in XenServer 6.2 SP1 Tech-Preview. /// </summary> public virtual List<XenRef<VGPU_type>> enabled_VGPU_types { get { return _enabled_VGPU_types; } set { if (!Helper.AreEqual(value, _enabled_VGPU_types)) { _enabled_VGPU_types = value; Changed = true; NotifyPropertyChanged("enabled_VGPU_types"); } } } private List<XenRef<VGPU_type>> _enabled_VGPU_types; /// <summary> /// List of VGPUs running on this PGPU /// First published in XenServer 6.2 SP1 Tech-Preview. /// </summary> public virtual List<XenRef<VGPU>> resident_VGPUs { get { return _resident_VGPUs; } set { if (!Helper.AreEqual(value, _resident_VGPUs)) { _resident_VGPUs = value; Changed = true; NotifyPropertyChanged("resident_VGPUs"); } } } private List<XenRef<VGPU>> _resident_VGPUs; /// <summary> /// A map relating each VGPU type supported on this GPU to the maximum number of VGPUs of that type which can run simultaneously on this GPU /// First published in XenServer 6.2 SP1. /// </summary> public virtual Dictionary<XenRef<VGPU_type>, long> supported_VGPU_max_capacities { get { return _supported_VGPU_max_capacities; } set { if (!Helper.AreEqual(value, _supported_VGPU_max_capacities)) { _supported_VGPU_max_capacities = value; Changed = true; NotifyPropertyChanged("supported_VGPU_max_capacities"); } } } private Dictionary<XenRef<VGPU_type>, long> _supported_VGPU_max_capacities; /// <summary> /// The accessibility of this device from dom0 /// First published in XenServer 6.5 SP1. /// </summary> public virtual pgpu_dom0_access dom0_access { get { return _dom0_access; } set { if (!Helper.AreEqual(value, _dom0_access)) { _dom0_access = value; Changed = true; NotifyPropertyChanged("dom0_access"); } } } private pgpu_dom0_access _dom0_access; /// <summary> /// Is this device the system display device /// First published in XenServer 6.5 SP1. /// </summary> public virtual bool is_system_display_device { get { return _is_system_display_device; } set { if (!Helper.AreEqual(value, _is_system_display_device)) { _is_system_display_device = value; Changed = true; NotifyPropertyChanged("is_system_display_device"); } } } private bool _is_system_display_device; } }
#region Copyright //////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Dynastream Innovations Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2015 Dynastream Innovations Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 16.10Release // Tag = development-akw-16.10.00-0 //////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.IO; namespace Dynastream.Fit { /// <summary> /// Implements the CoursePoint profile message. /// </summary> public class CoursePointMesg : Mesg { #region Fields #endregion #region Constructors public CoursePointMesg() : base(Profile.mesgs[Profile.CoursePointIndex]) { } public CoursePointMesg(Mesg mesg) : base(mesg) { } #endregion // Constructors #region Methods ///<summary> /// Retrieves the MessageIndex field</summary> /// <returns>Returns nullable ushort representing the MessageIndex field</returns> public ushort? GetMessageIndex() { return (ushort?)GetFieldValue(254, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set MessageIndex field</summary> /// <param name="messageIndex_">Nullable field value to be set</param> public void SetMessageIndex(ushort? messageIndex_) { SetFieldValue(254, 0, messageIndex_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Timestamp field</summary> /// <returns>Returns DateTime representing the Timestamp field</returns> public DateTime GetTimestamp() { return TimestampToDateTime((uint?)GetFieldValue(1, 0, Fit.SubfieldIndexMainField)); } /// <summary> /// Set Timestamp field</summary> /// <param name="timestamp_">Nullable field value to be set</param> public void SetTimestamp(DateTime timestamp_) { SetFieldValue(1, 0, timestamp_.GetTimeStamp(), Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the PositionLat field /// Units: semicircles</summary> /// <returns>Returns nullable int representing the PositionLat field</returns> public int? GetPositionLat() { return (int?)GetFieldValue(2, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set PositionLat field /// Units: semicircles</summary> /// <param name="positionLat_">Nullable field value to be set</param> public void SetPositionLat(int? positionLat_) { SetFieldValue(2, 0, positionLat_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the PositionLong field /// Units: semicircles</summary> /// <returns>Returns nullable int representing the PositionLong field</returns> public int? GetPositionLong() { return (int?)GetFieldValue(3, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set PositionLong field /// Units: semicircles</summary> /// <param name="positionLong_">Nullable field value to be set</param> public void SetPositionLong(int? positionLong_) { SetFieldValue(3, 0, positionLong_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Distance field /// Units: m</summary> /// <returns>Returns nullable float representing the Distance field</returns> public float? GetDistance() { return (float?)GetFieldValue(4, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Distance field /// Units: m</summary> /// <param name="distance_">Nullable field value to be set</param> public void SetDistance(float? distance_) { SetFieldValue(4, 0, distance_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Type field</summary> /// <returns>Returns nullable CoursePoint enum representing the Type field</returns> new public CoursePoint? GetType() { object obj = GetFieldValue(5, 0, Fit.SubfieldIndexMainField); CoursePoint? value = obj == null ? (CoursePoint?)null : (CoursePoint)obj; return value; } /// <summary> /// Set Type field</summary> /// <param name="type_">Nullable field value to be set</param> public void SetType(CoursePoint? type_) { SetFieldValue(5, 0, type_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Name field</summary> /// <returns>Returns byte[] representing the Name field</returns> public byte[] GetName() { return (byte[])GetFieldValue(6, 0, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Name field</summary> /// <returns>Returns String representing the Name field</returns> public String GetNameAsString() { return Encoding.UTF8.GetString((byte[])GetFieldValue(6, 0, Fit.SubfieldIndexMainField)); } ///<summary> /// Set Name field</summary> /// <returns>Returns String representing the Name field</returns> public void SetName(String name_) { SetFieldValue(6, 0, System.Text.Encoding.UTF8.GetBytes(name_), Fit.SubfieldIndexMainField); } /// <summary> /// Set Name field</summary> /// <param name="name_">field value to be set</param> public void SetName(byte[] name_) { SetFieldValue(6, 0, name_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Favorite field</summary> /// <returns>Returns nullable Bool enum representing the Favorite field</returns> public Bool? GetFavorite() { object obj = GetFieldValue(8, 0, Fit.SubfieldIndexMainField); Bool? value = obj == null ? (Bool?)null : (Bool)obj; return value; } /// <summary> /// Set Favorite field</summary> /// <param name="favorite_">Nullable field value to be set</param> public void SetFavorite(Bool? favorite_) { SetFieldValue(8, 0, favorite_, Fit.SubfieldIndexMainField); } #endregion // Methods } // Class } // namespace
//ZLIB, 2015,burningmime // Copyright (c) 2015 burningmime // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgement in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. using System; using System.Globalization; using System.Text; #if SYSTEM_WINDOWS_VECTOR using VECTOR = System.Windows.Vector; using FLOAT = System.Double; #elif SYSTEM_NUMERICS_VECTOR using VECTOR = System.Numerics.Vector2; using FLOAT = System.Single; #elif UNITY using VECTOR = UnityEngine.Vector2; using FLOAT = System.Single; #elif PIXEL_FARM using VECTOR = PixelFarm.VectorMath.Vector2; using FLOAT = System.Double; #else #error Unknown vector type -- must define one of SYSTEM_WINDOWS_VECTOR, SYSTEM_NUMERICS_VECTOR or UNITY #endif namespace burningmime.curves { /// <summary> /// Cubic Bezier curve in 2D consisting of 4 control points. /// </summary> public readonly struct CubicBezier : IEquatable<CubicBezier> { // Control points public readonly VECTOR p0; public readonly VECTOR p1; public readonly VECTOR p2; public readonly VECTOR p3; /// <summary> /// Creates a new cubic bezier using the given control points. /// </summary> public CubicBezier(VECTOR p0, VECTOR p1, VECTOR p2, VECTOR p3) { this.p0 = p0; this.p1 = p1; this.p2 = p2; this.p3 = p3; } public bool HasSomeNanComponent { get { return (HasSomeNanComponentXY(p0.X, p0.Y) || HasSomeNanComponentXY(p1.X, p1.Y) || HasSomeNanComponentXY(p2.X, p2.Y) || HasSomeNanComponentXY(p3.X, p3.Y)); } } static bool HasSomeNanComponentXY(double x, double y) { //TODO: aggressive inline return double.IsNaN(x) || double.IsNaN(y); } /// <summary> /// Samples the bezier curve at the given t value. /// </summary> /// <param name="t">Time value at which to sample (should be between 0 and 1, though it won't fail if outside that range).</param> /// <returns>Sampled point.</returns> #if !UNITY && !PIXEL_FARM [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public VECTOR Sample(FLOAT t) { FLOAT ti = 1 - t; FLOAT t0 = ti * ti * ti; FLOAT t1 = 3 * ti * ti * t; FLOAT t2 = 3 * ti * t * t; FLOAT t3 = t * t * t; return (t0 * p0) + (t1 * p1) + (t2 * p2) + (t3 * p3); } /// <summary> /// Gets the first derivative of the curve at the given T value. /// </summary> /// <param name="t">Time value at which to sample (should be between 0 and 1, though it won't fail if outside that range).</param> /// <returns>First derivative of curve at sampled point.</returns> #if !UNITY && !PIXEL_FARM [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public VECTOR Derivative(FLOAT t) { FLOAT ti = 1 - t; FLOAT tp0 = 3 * ti * ti; FLOAT tp1 = 6 * t * ti; FLOAT tp2 = 3 * t * t; return (tp0 * (p1 - p0)) + (tp1 * (p2 - p1)) + (tp2 * (p3 - p2)); } /// <summary> /// Gets the tangent (normalized derivative) of the curve at a given T value. /// </summary> /// <param name="t">Time value at which to sample (should be between 0 and 1, though it won't fail if outside that range).</param> /// <returns>Direction the curve is going at that point.</returns> #if !UNITY && !PIXEL_FARM [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public VECTOR Tangent(FLOAT t) { return VectorHelper.Normalize(Derivative(t)); } #if DEBUG public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("CubicBezier: (<"); sb.Append(VectorHelper.GetX(p0).ToString("#.###", CultureInfo.InvariantCulture)); sb.Append(", "); sb.Append(VectorHelper.GetY(p0).ToString("#.###", CultureInfo.InvariantCulture)); sb.Append("> <"); sb.Append(VectorHelper.GetX(p1).ToString("#.###", CultureInfo.InvariantCulture)); sb.Append(", "); sb.Append(VectorHelper.GetY(p1).ToString("#.###", CultureInfo.InvariantCulture)); sb.Append("> <"); sb.Append(VectorHelper.GetX(p2).ToString("#.###", CultureInfo.InvariantCulture)); sb.Append(", "); sb.Append(VectorHelper.GetY(p2).ToString("#.###", CultureInfo.InvariantCulture)); sb.Append("> <"); sb.Append(VectorHelper.GetX(p3).ToString("#.###", CultureInfo.InvariantCulture)); sb.Append(", "); sb.Append(VectorHelper.GetY(p3).ToString("#.###", CultureInfo.InvariantCulture)); sb.Append(">)"); return sb.ToString(); } #endif // Equality members -- pretty straightforward public static bool operator ==(CubicBezier left, CubicBezier right) { return left.Equals(right); } public static bool operator !=(CubicBezier left, CubicBezier right) { return !left.Equals(right); } public bool Equals(CubicBezier other) { return p0.Equals(other.p0) && p1.Equals(other.p1) && p2.Equals(other.p2) && p3.Equals(other.p3); } public override bool Equals(object obj) { return obj is CubicBezier && Equals((CubicBezier)obj); } public override int GetHashCode() { JenkinsHash hash = new JenkinsHash(); hash.Mixin(VectorHelper.GetX(p0).GetHashCode()); hash.Mixin(VectorHelper.GetY(p0).GetHashCode()); hash.Mixin(VectorHelper.GetX(p1).GetHashCode()); hash.Mixin(VectorHelper.GetY(p1).GetHashCode()); hash.Mixin(VectorHelper.GetX(p2).GetHashCode()); hash.Mixin(VectorHelper.GetY(p2).GetHashCode()); hash.Mixin(VectorHelper.GetX(p3).GetHashCode()); hash.Mixin(VectorHelper.GetY(p3).GetHashCode()); return hash.GetValue(); } /// <summary> /// Simple implementation of Jenkin's hashing algorithm. /// http://en.wikipedia.org/wiki/Jenkins_hash_function /// I forget where I got these magic numbers from; supposedly they're good. /// </summary> private struct JenkinsHash { private int _current; #if !UNITY && !PIXEL_FARM [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void Mixin(int hash) { unchecked { int num = _current; if (num == 0) num = 0x7e53a269; else num *= -0x5aaaaad7; num += hash; num += (num << 10); num ^= (num >> 6); _current = num; } } #if !UNITY && !PIXEL_FARM [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public int GetValue() { unchecked { int num = _current; num += (num << 3); num ^= (num >> 11); num += (num << 15); return num; } } } } }
using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; using Microsoft.Msagl.Drawing; using Microsoft.Msagl.Core.Layout; using Microsoft.Msagl.Core.DataStructures; using GeometryEdge = Microsoft.Msagl.Core.Layout.Edge; using DrawingEdge = Microsoft.Msagl.Drawing.Edge; using GeometryNode = Microsoft.Msagl.Core.Layout.Node; using DrawingNode = Microsoft.Msagl.Drawing.Node; namespace Microsoft.Msagl.GraphControlSilverlight { /// <summary> /// This class represents a rendering node. It contains the Microsoft.Msagl.Drawing.Node and Microsoft.Msagl.Node. /// The rendering node is a XAML user control. Its template is stored in Themes/generic.xaml. /// </summary> public sealed class DNode : DObject, IViewerNode, IHavingDLabel { private DLabel _Label; /// <summary> /// Gets or sets the rendering label. /// </summary> public DLabel Label { get { return _Label; } set { _Label = value; // Also set the drawing label and geometry label. DrawingNode.Label = value.DrawingLabel; //DrawingNode.GeometryNode.Label = value.DrawingLabel.GeometryLabel; // NEWMSAGL no label in the geometry node?? } } /// <summary> /// the corresponding drawing node /// </summary> public Microsoft.Msagl.Drawing.Node DrawingNode { get; set; } public IEnumerable<IViewerEdge> OutEdges { get { foreach (DEdge e in _OutEdges) yield return e; } } public IEnumerable<IViewerEdge> InEdges { get { foreach (DEdge e in _InEdges) yield return e; } } public IEnumerable<IViewerEdge> SelfEdges { get { foreach (DEdge e in _SelfEdges) yield return e; } } public event Action<IViewerNode> IsCollapsedChanged; public IEnumerable<DEdge> Edges { get { foreach (DEdge e in _OutEdges) yield return e; foreach (DEdge e in _InEdges) yield return e; foreach (DEdge e in _SelfEdges) yield return e; } } internal List<DEdge> _OutEdges { get; private set; } internal List<DEdge> _InEdges { get; private set; } internal List<DEdge> _SelfEdges { get; private set; } internal DNode(DGraph graph, DrawingNode drawingNode) : base(graph) { this.DrawingNode = drawingNode; _OutEdges = new List<DEdge>(); _InEdges = new List<DEdge>(); _SelfEdges = new List<DEdge>(); PortsToDraw = new Set<Port>(); if (drawingNode.Label != null) Label = new DTextLabel(this, drawingNode.Label); } public override void MakeVisual() { if (GeometryNode.BoundaryCurve == null) return; SetValue(Canvas.LeftProperty, Node.BoundingBox.Left); SetValue(Canvas.TopProperty, Node.BoundingBox.Bottom); // Note that Draw.CreateGraphicsPath returns a curve with coordinates in graph space. var pathFigure = Draw.CreateGraphicsPath((DrawingNode.GeometryNode).BoundaryCurve); pathFigure.IsFilled = Node.Attr.FillColor != Drawing.Color.Transparent; var pathGeometry = new PathGeometry(); pathGeometry.Figures.Add(pathFigure); // Apply a translation to bring the coordinates in node space (i.e. top left corner is 0,0). pathGeometry.Transform = new TranslateTransform() { X = -Node.BoundingBox.Left, Y = -Node.BoundingBox.Bottom }; // I'm using the max of my LineWidth and MSAGL's LineWidth; this way, when the MSAGL bug is fixed (see below), my workaround shouldn't // interfere with the fix. var path = new Path() { Data = pathGeometry, StrokeThickness = Math.Max(LineWidth, Node.Attr.LineWidth), Stroke = BoundaryBrush, Fill = new SolidColorBrush(Draw.MsaglColorToDrawingColor(Node.Attr.FillColor)) }; Content = path; } // Workaround for MSAGL bug which causes Node.Attr.LineWidth to be ignored (it always returns 1 unless the GeometryNode is null). public int LineWidth { get; set; } /// <summary> /// Gets or sets the boundary brush. /// </summary> public Brush BoundaryBrush { get { return (Brush)GetValue(BoundaryBrushProperty); } set { SetValue(BoundaryBrushProperty, value); } } public static readonly DependencyProperty BoundaryBrushProperty = DependencyProperty.Register("BoundaryBrush", typeof(Brush), typeof(DNode), new PropertyMetadata(DGraph.BlackBrush)); internal void AddOutEdge(DEdge edge) { _OutEdges.Add(edge); } internal void AddInEdge(DEdge edge) { _InEdges.Add(edge); } internal void AddSelfEdge(DEdge edge) { _SelfEdges.Add(edge); } /// <summary> /// return the color of a node /// </summary> public System.Windows.Media.Color Color { get { return Draw.MsaglColorToDrawingColor(this.DrawingNode.Attr.Color); } } /// <summary> /// Fillling color of a node /// </summary> public System.Windows.Media.Color FillColor { get { return Draw.MsaglColorToDrawingColor(this.DrawingNode.Attr.FillColor); } } /// <summary> /// /// </summary> public void SetStrokeFill() { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public GeometryNode GeometryNode { get { return this.DrawingNode.GeometryNode; } } /// <summary> /// returns the corresponding DrawingNode /// </summary> public DrawingNode Node { get { return this.DrawingNode; } } /// <summary> /// returns the corresponding drawing object /// </summary> override public DrawingObject DrawingObject { get { return Node; } } internal void RemoveOutEdge(DEdge de) { _OutEdges.Remove(de); } internal void RemoveInEdge(DEdge de) { _InEdges.Remove(de); } internal void RemoveSelfEdge(DEdge de) { _SelfEdges.Remove(de); } internal Set<Port> PortsToDraw { get; private set; } /// <summary> /// /// </summary> public void AddPort(Port port) { PortsToDraw.Insert(port); } /// <summary> /// it is a class holding Microsoft.Msagl.Drawing.Node and Microsoft.Msagl.Node /// </summary> public void RemovePort(Port port) { if (port != null) PortsToDraw.Remove(port); } } }
using System; using System.Collections.Generic; using ModestTree; using System.Linq; #if !NOT_UNITY3D using UnityEngine; #endif using Zenject.Internal; namespace Zenject { public abstract class FromBinder : ScopeArgConditionCopyNonLazyBinder { public FromBinder( BindInfo bindInfo, BindFinalizerWrapper finalizerWrapper) : base(bindInfo) { FinalizerWrapper = finalizerWrapper; } protected BindFinalizerWrapper FinalizerWrapper { get; private set; } protected IBindingFinalizer SubFinalizer { set { FinalizerWrapper.SubFinalizer = value; } } protected IEnumerable<Type> AllParentTypes { get { return BindInfo.ContractTypes.Concat(BindInfo.ToTypes); } } protected IEnumerable<Type> ConcreteTypes { get { if (BindInfo.ToChoice == ToChoices.Self) { return BindInfo.ContractTypes; } Assert.IsNotEmpty(BindInfo.ToTypes); return BindInfo.ToTypes; } } // This is the default if nothing else is called public ScopeArgConditionCopyNonLazyBinder FromNew() { BindingUtil.AssertTypesAreNotComponents(ConcreteTypes); BindingUtil.AssertTypesAreNotAbstract(ConcreteTypes); return this; } public ScopeConditionCopyNonLazyBinder FromResolve() { return FromResolve(null); } public ScopeConditionCopyNonLazyBinder FromResolve(object subIdentifier) { BindInfo.RequireExplicitScope = false; SubFinalizer = new ScopableBindingFinalizer( BindInfo, SingletonTypes.FromResolve, subIdentifier, (container, type) => new ResolveProvider( type, container, subIdentifier, false, InjectSources.Any)); return new ScopeConditionCopyNonLazyBinder(BindInfo); } public SubContainerBinder FromSubContainerResolve() { return FromSubContainerResolve(null); } public SubContainerBinder FromSubContainerResolve(object subIdentifier) { // It's unlikely they will want to create the whole subcontainer with each binding // (aka transient) which is the default so require that they specify it BindInfo.RequireExplicitScope = true; return new SubContainerBinder( BindInfo, FinalizerWrapper, subIdentifier); } public ScopeArgConditionCopyNonLazyBinder FromFactory(Type factoryType) { Assert.That(factoryType.DerivesFrom<IFactory>()); BindInfo.RequireExplicitScope = true; SubFinalizer = new ScopableBindingFinalizer( BindInfo, SingletonTypes.FromFactory, factoryType, (container, type) => new UntypedFactoryProvider( factoryType, container, BindInfo.Arguments)); return new ScopeArgConditionCopyNonLazyBinder(BindInfo); } #if !NOT_UNITY3D public ScopeArgConditionCopyNonLazyBinder FromNewComponentOn(GameObject gameObject) { BindingUtil.AssertIsValidGameObject(gameObject); BindingUtil.AssertIsComponent(ConcreteTypes); BindingUtil.AssertTypesAreNotAbstract(ConcreteTypes); BindInfo.RequireExplicitScope = true; SubFinalizer = new ScopableBindingFinalizer( BindInfo, SingletonTypes.FromComponentGameObject, gameObject, (container, type) => new AddToExistingGameObjectComponentProvider( gameObject, container, type, BindInfo.ConcreteIdentifier, BindInfo.Arguments)); return new ScopeArgConditionCopyNonLazyBinder(BindInfo); } public ScopeArgConditionCopyNonLazyBinder FromNewComponentOn(Func<InjectContext, GameObject> gameObjectGetter) { BindingUtil.AssertIsComponent(ConcreteTypes); BindingUtil.AssertTypesAreNotAbstract(ConcreteTypes); BindInfo.RequireExplicitScope = true; SubFinalizer = new ScopableBindingFinalizer( BindInfo, SingletonTypes.FromComponentGameObject, gameObjectGetter, (container, type) => new AddToExistingGameObjectComponentProviderGetter( gameObjectGetter, container, type, BindInfo.ConcreteIdentifier, BindInfo.Arguments)); return new ScopeArgConditionCopyNonLazyBinder(BindInfo); } public ArgConditionCopyNonLazyBinder FromNewComponentSibling() { BindingUtil.AssertIsComponent(ConcreteTypes); BindingUtil.AssertTypesAreNotAbstract(ConcreteTypes); BindInfo.RequireExplicitScope = true; SubFinalizer = new SingleProviderBindingFinalizer( BindInfo, (container, type) => new AddToCurrentGameObjectComponentProvider( container, type, BindInfo.ConcreteIdentifier, BindInfo.Arguments)); return new ArgConditionCopyNonLazyBinder(BindInfo); } public NameTransformScopeArgConditionCopyNonLazyBinder FromNewComponentOnNewGameObject() { return FromNewComponentOnNewGameObject(new GameObjectCreationParameters()); } internal NameTransformScopeArgConditionCopyNonLazyBinder FromNewComponentOnNewGameObject( GameObjectCreationParameters gameObjectInfo) { BindingUtil.AssertIsComponent(ConcreteTypes); BindingUtil.AssertTypesAreNotAbstract(ConcreteTypes); BindInfo.RequireExplicitScope = true; SubFinalizer = new ScopableBindingFinalizer( BindInfo, SingletonTypes.FromGameObject, gameObjectInfo, (container, type) => new AddToNewGameObjectComponentProvider( container, type, BindInfo.ConcreteIdentifier, BindInfo.Arguments, gameObjectInfo)); return new NameTransformScopeArgConditionCopyNonLazyBinder(BindInfo, gameObjectInfo); } public NameTransformScopeArgConditionCopyNonLazyBinder FromComponentInNewPrefab(UnityEngine.Object prefab) { return FromComponentInNewPrefab( prefab, new GameObjectCreationParameters()); } internal NameTransformScopeArgConditionCopyNonLazyBinder FromComponentInNewPrefab( UnityEngine.Object prefab, GameObjectCreationParameters gameObjectInfo) { BindingUtil.AssertIsValidPrefab(prefab); BindingUtil.AssertIsInterfaceOrComponent(AllParentTypes); BindInfo.RequireExplicitScope = true; SubFinalizer = new PrefabBindingFinalizer( BindInfo, gameObjectInfo, prefab); return new NameTransformScopeArgConditionCopyNonLazyBinder(BindInfo, gameObjectInfo); } public NameTransformScopeArgConditionCopyNonLazyBinder FromComponentInNewPrefabResource(string resourcePath) { return FromComponentInNewPrefabResource(resourcePath, new GameObjectCreationParameters()); } internal NameTransformScopeArgConditionCopyNonLazyBinder FromComponentInNewPrefabResource( string resourcePath, GameObjectCreationParameters gameObjectInfo) { BindingUtil.AssertIsValidResourcePath(resourcePath); BindingUtil.AssertIsInterfaceOrComponent(AllParentTypes); BindInfo.RequireExplicitScope = true; SubFinalizer = new PrefabResourceBindingFinalizer( BindInfo, gameObjectInfo, resourcePath); return new NameTransformScopeArgConditionCopyNonLazyBinder(BindInfo, gameObjectInfo); } public ScopeArgConditionCopyNonLazyBinder FromNewScriptableObjectResource(string resourcePath) { return FromScriptableObjectResourceInternal(resourcePath, true); } public ScopeArgConditionCopyNonLazyBinder FromScriptableObjectResource(string resourcePath) { return FromScriptableObjectResourceInternal(resourcePath, false); } ScopeArgConditionCopyNonLazyBinder FromScriptableObjectResourceInternal( string resourcePath, bool createNew) { BindingUtil.AssertIsValidResourcePath(resourcePath); BindingUtil.AssertIsInterfaceOrScriptableObject(AllParentTypes); BindInfo.RequireExplicitScope = true; SubFinalizer = new ScopableBindingFinalizer( BindInfo, createNew ? SingletonTypes.FromNewScriptableObjectResource : SingletonTypes.FromScriptableObjectResource, resourcePath.ToLower(), (container, type) => new ScriptableObjectResourceProvider( resourcePath, type, container, BindInfo.ConcreteIdentifier, BindInfo.Arguments, createNew)); return new ScopeArgConditionCopyNonLazyBinder(BindInfo); } public ScopeConditionCopyNonLazyBinder FromResource(string resourcePath) { BindingUtil.AssertDerivesFromUnityObject(ConcreteTypes); BindInfo.RequireExplicitScope = false; SubFinalizer = new ScopableBindingFinalizer( BindInfo, SingletonTypes.FromResource, resourcePath.ToLower(), (_, type) => new ResourceProvider(resourcePath, type)); return new ScopeConditionCopyNonLazyBinder(BindInfo); } #endif public ScopeArgConditionCopyNonLazyBinder FromMethodUntyped(Func<InjectContext, object> method) { BindInfo.RequireExplicitScope = false; SubFinalizer = new ScopableBindingFinalizer( BindInfo, SingletonTypes.FromMethod, new SingletonImplIds.ToMethod(method), (container, type) => new MethodProviderUntyped(method, container)); return this; } protected ScopeArgConditionCopyNonLazyBinder FromMethodBase<TConcrete>(Func<InjectContext, TConcrete> method) { BindingUtil.AssertIsDerivedFromTypes(typeof(TConcrete), AllParentTypes); BindInfo.RequireExplicitScope = false; SubFinalizer = new ScopableBindingFinalizer( BindInfo, SingletonTypes.FromMethod, new SingletonImplIds.ToMethod(method), (container, type) => new MethodProvider<TConcrete>(method, container)); return this; } protected ScopeArgConditionCopyNonLazyBinder FromMethodMultipleBase<TConcrete>(Func<InjectContext, IEnumerable<TConcrete>> method) { BindingUtil.AssertIsDerivedFromTypes(typeof(TConcrete), AllParentTypes); BindInfo.RequireExplicitScope = false; SubFinalizer = new ScopableBindingFinalizer( BindInfo, SingletonTypes.FromMethod, new SingletonImplIds.ToMethod(method), (container, type) => new MethodProviderMultiple<TConcrete>(method, container)); return this; } protected ScopeArgConditionCopyNonLazyBinder FromFactoryBase<TConcrete, TFactory>() where TFactory : IFactory<TConcrete> { BindingUtil.AssertIsDerivedFromTypes(typeof(TConcrete), AllParentTypes); // This is kind of like a look up method like FromMethod so don't enforce specifying scope BindInfo.RequireExplicitScope = false; SubFinalizer = new ScopableBindingFinalizer( BindInfo, SingletonTypes.FromFactory, typeof(TFactory), (container, type) => new FactoryProvider<TConcrete, TFactory>(container, BindInfo.Arguments)); return new ScopeArgConditionCopyNonLazyBinder(BindInfo); } protected ScopeConditionCopyNonLazyBinder FromResolveGetterBase<TObj, TResult>( object identifier, Func<TObj, TResult> method) { BindingUtil.AssertIsDerivedFromTypes(typeof(TResult), AllParentTypes); BindInfo.RequireExplicitScope = false; SubFinalizer = new ScopableBindingFinalizer( BindInfo, SingletonTypes.FromGetter, new SingletonImplIds.ToGetter(identifier, method), (container, type) => new GetterProvider<TObj, TResult>(identifier, method, container)); return new ScopeConditionCopyNonLazyBinder(BindInfo); } protected ScopeConditionCopyNonLazyBinder FromInstanceBase(object instance, bool allowNull) { if (!allowNull) { Assert.That(!ZenUtilInternal.IsNull(instance), "Found null instance for type '{0}' in FromInstance method", ConcreteTypes.First()); } BindingUtil.AssertInstanceDerivesFromOrEqual(instance, AllParentTypes); BindInfo.RequireExplicitScope = false; SubFinalizer = new ScopableBindingFinalizer( BindInfo, SingletonTypes.FromInstance, instance, (container, type) => new InstanceProvider(type, instance, container)); return new ScopeConditionCopyNonLazyBinder(BindInfo); } } }
namespace System.Spatial { using Linq; /// <summary> /// Represents a 4 x 4 matrix. /// </summary> public static class Matrix4D { public const Int32 Order = 4; public static Matrix Create(Func<Int32, Int32, Double> valueFactory) { return Matrix.Build.Dense(Order, Order, valueFactory); } public static Plane[] Frustum(Matrix matrix) { if (matrix == null) { throw new ArgumentNullException(nameof(matrix)); } if (matrix.ColumnCount != Order || matrix.RowCount != Order) { throw new ArgumentException("matrix is not a 4 x 4 matrix"); } var columns = Enumerable.Range(0, Order).Select(matrix.GetColumn).ToArray(); var minimumX = new Plane((columns[3] + columns[0]).ToArray()).Normalize(); // Left-plane var maximumX = new Plane((columns[3] - columns[0]).ToArray()).Normalize(); // Right-plane var minimumY = new Plane((columns[3] + columns[1]).ToArray()).Normalize(); // Bottom-plane var maximumY = new Plane((columns[3] - columns[1]).ToArray()).Normalize(); // Top-plane var minimumZ = new Plane(columns[2].ToArray()).Normalize(); // Near-plane var maximumZ = new Plane((columns[3] - columns[2]).ToArray()).Normalize(); // Far-plane return new[] { minimumX, maximumX, minimumY, maximumY, minimumZ, maximumZ }; } public static Double Determinant(Matrix matrix) { if (matrix == null) { throw new ArgumentNullException(nameof(matrix)); } if (matrix.ColumnCount != Order || matrix.RowCount != Order) { throw new DimensionMismatchException(); } var num1 = (matrix[2, 2] * matrix[3, 3] - matrix[2, 3] * matrix[3, 2]); var num2 = (matrix[2, 1] * matrix[3, 3] - matrix[2, 3] * matrix[3, 1]); var num3 = (matrix[2, 1] * matrix[3, 2] - matrix[2, 2] * matrix[3, 1]); var num4 = (matrix[2, 0] * matrix[3, 3] - matrix[2, 3] * matrix[3, 0]); var num5 = (matrix[2, 0] * matrix[3, 2] - matrix[2, 2] * matrix[3, 0]); var num6 = (matrix[2, 0] * matrix[3, 1] - matrix[2, 1] * matrix[3, 0]); return matrix[0, 0] * (matrix[1, 1] * num1 - matrix[1, 2] * num2 + matrix[1, 3] * num3) - matrix[0, 1] * (matrix[1, 0] * num1 - matrix[1, 2] * num4 + matrix[1, 3] * num5) + matrix[0, 2] * (matrix[1, 0] * num2 - matrix[1, 1] * num4 + matrix[1, 3] * num6) - matrix[0, 3] * (matrix[1, 0] * num3 - matrix[1, 1] * num5 + matrix[1, 2] * num6); } /// <summary> /// Creates a 4 x 4 identity-matrix. /// </summary> public static Matrix Identity() { return Matrix.Build.DenseIdentity(Order); } public static Matrix Inverse(Matrix matrix) { if (matrix == null) { throw new ArgumentNullException(nameof(matrix)); } if (matrix.ColumnCount != Order || matrix.RowCount != Order) { throw new DimensionMismatchException(); } var num1 = (matrix[2, 0] * matrix[3, 1] - matrix[2, 1] * matrix[3, 0]); var num2 = (matrix[2, 0] * matrix[3, 2] - matrix[2, 2] * matrix[3, 0]); var num3 = (matrix[2, 3] * matrix[3, 0] - matrix[2, 0] * matrix[3, 3]); var num4 = (matrix[2, 1] * matrix[3, 2] - matrix[2, 2] * matrix[3, 1]); var num5 = (matrix[2, 3] * matrix[3, 1] - matrix[2, 1] * matrix[3, 3]); var num6 = (matrix[2, 2] * matrix[3, 3] - matrix[2, 3] * matrix[3, 2]); var num7 = (matrix[1, 1] * num6 + matrix[1, 2] * num5 + matrix[1, 3] * num4); var num8 = (matrix[1, 0] * num6 + matrix[1, 2] * num3 + matrix[1, 3] * num2); var num9 = (matrix[1, 0] * -num5 + matrix[1, 1] * num3 + matrix[1, 3] * num1); var num10 = (matrix[1, 0] * num4 + matrix[1, 1] * -num2 + matrix[1, 2] * num1); var num11 = (matrix[0, 0] * num7 - matrix[0, 1] * num8 + matrix[0, 2] * num9 - matrix[0, 3] * num10); if (Math.Abs(num11).CompareTo(0D) == 0) { return Matrix.Build.Dense(Order, Order); } var result = Matrix.Build.SameAs(matrix); var num12 = 1D / num11; var num13 = (matrix[0, 0] * matrix[1, 1] - matrix[0, 1] * matrix[1, 0]); var num14 = (matrix[0, 0] * matrix[1, 2] - matrix[0, 2] * matrix[1, 0]); var num15 = (matrix[0, 3] * matrix[1, 0] - matrix[0, 0] * matrix[1, 3]); var num16 = (matrix[0, 1] * matrix[1, 2] - matrix[0, 2] * matrix[1, 1]); var num17 = (matrix[0, 3] * matrix[1, 1] - matrix[0, 1] * matrix[1, 3]); var num18 = (matrix[0, 2] * matrix[1, 3] - matrix[0, 3] * matrix[1, 2]); var num19 = (matrix[0, 1] * num6 + matrix[0, 2] * num5 + matrix[0, 3] * num4); var num20 = (matrix[0, 0] * num6 + matrix[0, 2] * num3 + matrix[0, 3] * num2); var num21 = (matrix[0, 0] * -num5 + matrix[0, 1] * num3 + matrix[0, 3] * num1); var num22 = (matrix[0, 0] * num4 + matrix[0, 1] * -num2 + matrix[0, 2] * num1); var num23 = (matrix[3, 1] * num18 + matrix[3, 2] * num17 + matrix[3, 3] * num16); var num24 = (matrix[3, 0] * num18 + matrix[3, 2] * num15 + matrix[3, 3] * num14); var num25 = (matrix[3, 0] * -num17 + matrix[3, 1] * num15 + matrix[3, 3] * num13); var num26 = (matrix[3, 0] * num16 + matrix[3, 1] * -num14 + matrix[3, 2] * num13); var num27 = (matrix[2, 1] * num18 + matrix[2, 2] * num17 + matrix[2, 3] * num16); var num28 = (matrix[2, 0] * num18 + matrix[2, 2] * num15 + matrix[2, 3] * num14); var num29 = (matrix[2, 0] * -num17 + matrix[2, 1] * num15 + matrix[2, 3] * num13); var num30 = (matrix[2, 0] * num16 + matrix[2, 1] * -num14 + matrix[2, 2] * num13); result[0, 0] = num7 * num12; result[0, 1] = -num19 * num12; result[0, 2] = num23 * num12; result[0, 3] = -num27 * num12; result[1, 0] = -num8 * num12; result[1, 1] = num20 * num12; result[1, 2] = -num24 * num12; result[1, 3] = num28 * num12; result[2, 0] = num9 * num12; result[2, 1] = -num21 * num12; result[2, 2] = num25 * num12; result[2, 3] = -num29 * num12; result[3, 0] = -num10 * num12; result[3, 1] = num22 * num12; result[3, 2] = -num26 * num12; result[3, 3] = num30 * num12; return result; } public static Matrix PerspectiveFieldOfView(Double fieldOfView, Double aspectRatio, Double frontPlaneDistance, Double backPlaneDistance) { if (fieldOfView <= 0D || fieldOfView >= Math.PI) { throw new ArgumentOutOfRangeException(nameof(fieldOfView)); } if (frontPlaneDistance <= 0D) { throw new ArgumentOutOfRangeException(nameof(frontPlaneDistance)); } if (backPlaneDistance <= 0D) { throw new ArgumentOutOfRangeException(nameof(backPlaneDistance)); } if (frontPlaneDistance >= backPlaneDistance) { throw new ArgumentOutOfRangeException(nameof(frontPlaneDistance)); } var scaleY = 1D / Math.Tan(fieldOfView); var result = Matrix.Build.Dense(Order, Order); result[0, 0] = scaleY / aspectRatio; result[1, 1] = scaleY; result[2, 2] = backPlaneDistance / (backPlaneDistance - frontPlaneDistance); result[2, 3] = 1D; result[3, 2] = -frontPlaneDistance * backPlaneDistance / (backPlaneDistance - frontPlaneDistance); return result; } /// <summary> /// Creates a 4 x 4 left-handed projection matrix. /// </summary> public static Matrix Perspective(Double frontPlaneWidth, Double frontPlaneHeight, Double frontPlaneDistance, Double backPlaneDistance) { if (frontPlaneDistance <= 0D) { throw new ArgumentOutOfRangeException(nameof(frontPlaneDistance)); } if (backPlaneDistance <= 0D) { throw new ArgumentOutOfRangeException(nameof(backPlaneDistance)); } if (frontPlaneDistance >= backPlaneDistance) { throw new ArgumentOutOfRangeException(nameof(frontPlaneDistance)); } var result = new Matrix(Order, Order); result[0, 0] = 2D * frontPlaneDistance / frontPlaneWidth; result[1, 1] = 2D * frontPlaneDistance / frontPlaneHeight; result[2, 2] = backPlaneDistance / (backPlaneDistance - frontPlaneDistance); result[2, 3] = frontPlaneDistance * backPlaneDistance / (frontPlaneDistance - backPlaneDistance); result[3, 2] = 1D; return result; } /// <summary> /// Create a 4x4 rotation matrix, using a rotation-axis and an angle. /// </summary> public static Matrix Rotate(Vector axis, Double angle) { var sin = Math.Sin(angle); var cos = Math.Cos(angle); var x = axis[0]; var y = axis[1]; var z = axis[2]; var xx = x * x; var yy = y * y; var zz = z * z; var xy = x * y; var xz = x * z; var yz = y * z; var result = Identity.Clone(); result[0, 0] = xx + cos * (1D - xx); result[1, 0] = xy - cos * xy + sin * z; result[2, 0] = xz - cos * xz - sin * y; result[0, 1] = xy - cos * xy - sin * z; result[1, 1] = yy + cos * (1D - yy); result[2, 1] = yz - cos * yz + sin * x; result[0, 2] = xz - cos * xz + sin * y; result[1, 2] = yz - cos * yz - sin * x; result[2, 2] = zz + cos * (1D - zz); return result; } /// <summary> /// Create a 4x4 rotation matrix, using a quaternion. /// </summary> public static Matrix Rotate(Vector quaternion) { var xx = quaternion[0] * quaternion[0]; var xy = quaternion[0] * quaternion[1]; var xw = quaternion[0] * quaternion[3]; var yy = quaternion[1] * quaternion[1]; var yz = quaternion[1] * quaternion[2]; var yw = quaternion[1] * quaternion[3]; var zx = quaternion[2] * quaternion[0]; var zz = quaternion[2] * quaternion[2]; var zw = quaternion[2] * quaternion[3]; var result = Identity.Clone(); result[0, 0] = 1D - 2D * (yy + zz); result[1, 0] = 2D * (xy + zw); result[2, 0] = 2D * (zx - yw); result[0, 1] = 2D * (xy - zw); result[1, 1] = 1D - 2D * (zz + xx); result[2, 1] = 2D * (yz + xw); result[0, 2] = 2D * (zx + yw); result[1, 2] = 2D * (yz - xw); result[2, 2] = 1D - 2D * (yy + xx); return result; } /// <summary> /// Create a 4x4 scale matrix, using a value as scale-factor. /// </summary> public static Matrix Scale(Double scale) { return Scale(Vector3D.Create(scale)); } /// <summary> /// Create a 4x4 scale matrix, using a vector as scale-factor. /// </summary> public static Matrix Scale(Vector scale) { if (scale == null) { throw new ArgumentNullException("scale"); } if (scale.Count != Vector3D.Size) { throw new ArgumentDimensionMismatchException("scale", Vector3D.Size); } var result = Identity.Clone(); result[0, 0] = scale[0]; result[1, 1] = scale[1]; result[2, 2] = scale[2]; return result; } /// <summary> /// Create a 4x4 translation matrix, using a vector as offset. /// </summary> public static Matrix Translate(Vector translation) { var result = Identity.Clone(); for (var index = 0; index < translation.Count; index++) { result[index, Vector3D.Size] = translation[index]; } return result; } public static Matrix View(Vector position, Vector forward, Vector upward) { var axisZ = forward.Normalize(); var axisX = Vector3D.Cross(upward, axisZ).Normalize(); var axisY = Vector3D.Cross(axisZ, axisX); var result = Identity.Clone(); result[0, 0] = axisX[0]; result[1, 0] = axisY[0]; result[2, 0] = axisZ[0]; result[0, 1] = axisX[1]; result[1, 1] = axisY[1]; result[2, 1] = axisZ[1]; result[0, 2] = axisX[2]; result[1, 2] = axisY[2]; result[2, 2] = axisZ[2]; result[0, 3] = -axisX.DotProduct(position); result[1, 3] = -axisY.DotProduct(position); result[2, 3] = -axisZ.DotProduct(position); return result; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Reflection; using Nini.Config; using NUnit.Framework; using OpenMetaverse; using OpenMetaverse.Messages.Linden; using OpenMetaverse.Packets; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.ClientStack.Linden; using OpenSim.Region.CoreModules.Avatar.InstantMessage; using OpenSim.Region.CoreModules.Framework; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups; using OpenSim.Tests.Common; namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups.Tests { /// <summary> /// Basic groups module tests /// </summary> [TestFixture] public class GroupsModuleTests : OpenSimTestCase { [SetUp] public override void SetUp() { base.SetUp(); uint port = 9999; uint sslPort = 9998; // This is an unfortunate bit of clean up we have to do because MainServer manages things through static // variables and the VM is not restarted between tests. MainServer.RemoveHttpServer(port); BaseHttpServer server = new BaseHttpServer(port, false, sslPort, ""); MainServer.AddHttpServer(server); MainServer.Instance = server; } [Test] public void TestSendAgentGroupDataUpdate() { /* AgentGroupDataUpdate is udp TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestScene scene = new SceneHelpers().SetupScene(); IConfigSource configSource = new IniConfigSource(); IConfig config = configSource.AddConfig("Groups"); config.Set("Enabled", true); config.Set("Module", "GroupsModule"); config.Set("DebugEnabled", true); GroupsModule gm = new GroupsModule(); EventQueueGetModule eqgm = new EventQueueGetModule(); // We need a capabilities module active so that adding the scene presence creates an event queue in the // EventQueueGetModule SceneHelpers.SetupSceneModules( scene, configSource, gm, new MockGroupsServicesConnector(), new CapabilitiesModule(), eqgm); ScenePresence sp = SceneHelpers.AddScenePresence(scene, TestHelpers.ParseStem("1")); gm.SendAgentGroupDataUpdate(sp.ControllingClient); Hashtable eventsResponse = eqgm.GetEvents(UUID.Zero, sp.UUID); if((int)eventsResponse["int_response_code"] != (int)HttpStatusCode.OK) { eventsResponse = eqgm.GetEvents(UUID.Zero, sp.UUID); if((int)eventsResponse["int_response_code"] != (int)HttpStatusCode.OK) eventsResponse = eqgm.GetEvents(UUID.Zero, sp.UUID); } Assert.That((int)eventsResponse["int_response_code"], Is.EqualTo((int)HttpStatusCode.OK)); // Console.WriteLine("Response [{0}]", (string)eventsResponse["str_response_string"]); OSDMap rawOsd = (OSDMap)OSDParser.DeserializeLLSDXml((string)eventsResponse["str_response_string"]); OSDArray eventsOsd = (OSDArray)rawOsd["events"]; bool foundUpdate = false; foreach (OSD osd in eventsOsd) { OSDMap eventOsd = (OSDMap)osd; if (eventOsd["message"] == "AgentGroupDataUpdate") foundUpdate = true; } Assert.That(foundUpdate, Is.True, "Did not find AgentGroupDataUpdate in response"); // TODO: More checking of more actual event data. */ } [Test] public void TestSendGroupNotice() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestScene scene = new SceneHelpers().SetupScene(); MessageTransferModule mtm = new MessageTransferModule(); GroupsModule gm = new GroupsModule(); GroupsMessagingModule gmm = new GroupsMessagingModule(); MockGroupsServicesConnector mgsc = new MockGroupsServicesConnector(); IConfigSource configSource = new IniConfigSource(); { IConfig config = configSource.AddConfig("Messaging"); config.Set("MessageTransferModule", mtm.Name); } { IConfig config = configSource.AddConfig("Groups"); config.Set("Enabled", true); config.Set("Module", gm.Name); config.Set("DebugEnabled", true); config.Set("MessagingModule", gmm.Name); config.Set("MessagingEnabled", true); } SceneHelpers.SetupSceneModules(scene, configSource, mgsc, mtm, gm, gmm); UUID userId = TestHelpers.ParseTail(0x1); string subjectText = "newman"; string messageText = "Hello"; string combinedSubjectMessage = string.Format("{0}|{1}", subjectText, messageText); ScenePresence sp = SceneHelpers.AddScenePresence(scene, TestHelpers.ParseTail(0x1)); TestClient tc = (TestClient)sp.ControllingClient; UUID groupID = gm.CreateGroup(tc, "group1", null, true, UUID.Zero, 0, true, true, true); gm.JoinGroupRequest(tc, groupID); // Create a second user who doesn't want to receive notices ScenePresence sp2 = SceneHelpers.AddScenePresence(scene, TestHelpers.ParseTail(0x2)); TestClient tc2 = (TestClient)sp2.ControllingClient; gm.JoinGroupRequest(tc2, groupID); gm.SetGroupAcceptNotices(tc2, groupID, false, true); List<GridInstantMessage> spReceivedMessages = new List<GridInstantMessage>(); tc.OnReceivedInstantMessage += im => spReceivedMessages.Add(im); List<GridInstantMessage> sp2ReceivedMessages = new List<GridInstantMessage>(); tc2.OnReceivedInstantMessage += im => sp2ReceivedMessages.Add(im); GridInstantMessage noticeIm = new GridInstantMessage(); noticeIm.fromAgentID = userId.Guid; noticeIm.toAgentID = groupID.Guid; noticeIm.message = combinedSubjectMessage; noticeIm.dialog = (byte)InstantMessageDialog.GroupNotice; tc.HandleImprovedInstantMessage(noticeIm); Assert.That(spReceivedMessages.Count, Is.EqualTo(1)); Assert.That(spReceivedMessages[0].message, Is.EqualTo(combinedSubjectMessage)); List<GroupNoticeData> notices = mgsc.GetGroupNotices(UUID.Zero, groupID); Assert.AreEqual(1, notices.Count); // OpenSimulator (possibly also SL) transport the notice ID as the session ID! Assert.AreEqual(notices[0].NoticeID.Guid, spReceivedMessages[0].imSessionID); Assert.That(sp2ReceivedMessages.Count, Is.EqualTo(0)); } /// <summary> /// Run test with the MessageOnlineUsersOnly flag set. /// </summary> [Test] public void TestSendGroupNoticeOnlineOnly() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestScene scene = new SceneHelpers().SetupScene(); MessageTransferModule mtm = new MessageTransferModule(); GroupsModule gm = new GroupsModule(); GroupsMessagingModule gmm = new GroupsMessagingModule(); IConfigSource configSource = new IniConfigSource(); { IConfig config = configSource.AddConfig("Messaging"); config.Set("MessageTransferModule", mtm.Name); } { IConfig config = configSource.AddConfig("Groups"); config.Set("Enabled", true); config.Set("Module", gm.Name); config.Set("DebugEnabled", true); config.Set("MessagingModule", gmm.Name); config.Set("MessagingEnabled", true); config.Set("MessageOnlineUsersOnly", true); } SceneHelpers.SetupSceneModules(scene, configSource, new MockGroupsServicesConnector(), mtm, gm, gmm); UUID userId = TestHelpers.ParseTail(0x1); string subjectText = "newman"; string messageText = "Hello"; string combinedSubjectMessage = string.Format("{0}|{1}", subjectText, messageText); ScenePresence sp = SceneHelpers.AddScenePresence(scene, TestHelpers.ParseTail(0x1)); TestClient tc = (TestClient)sp.ControllingClient; UUID groupID = gm.CreateGroup(tc, "group1", null, true, UUID.Zero, 0, true, true, true); gm.JoinGroupRequest(tc, groupID); // Create a second user who doesn't want to receive notices ScenePresence sp2 = SceneHelpers.AddScenePresence(scene, TestHelpers.ParseTail(0x2)); TestClient tc2 = (TestClient)sp2.ControllingClient; gm.JoinGroupRequest(tc2, groupID); gm.SetGroupAcceptNotices(tc2, groupID, false, true); List<GridInstantMessage> spReceivedMessages = new List<GridInstantMessage>(); tc.OnReceivedInstantMessage += im => spReceivedMessages.Add(im); List<GridInstantMessage> sp2ReceivedMessages = new List<GridInstantMessage>(); tc2.OnReceivedInstantMessage += im => sp2ReceivedMessages.Add(im); GridInstantMessage noticeIm = new GridInstantMessage(); noticeIm.fromAgentID = userId.Guid; noticeIm.toAgentID = groupID.Guid; noticeIm.message = combinedSubjectMessage; noticeIm.dialog = (byte)InstantMessageDialog.GroupNotice; tc.HandleImprovedInstantMessage(noticeIm); Assert.That(spReceivedMessages.Count, Is.EqualTo(1)); Assert.That(spReceivedMessages[0].message, Is.EqualTo(combinedSubjectMessage)); Assert.That(sp2ReceivedMessages.Count, Is.EqualTo(0)); } } }
// <copyright file="IncompleteLU.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2010 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using MathNet.Numerics.LinearAlgebra.Solvers; using MathNet.Numerics.Properties; namespace MathNet.Numerics.LinearAlgebra.Complex32.Solvers { using Numerics; /// <summary> /// An incomplete, level 0, LU factorization preconditioner. /// </summary> /// <remarks> /// The ILU(0) algorithm was taken from: <br/> /// Iterative methods for sparse linear systems <br/> /// Yousef Saad <br/> /// Algorithm is described in Chapter 10, section 10.3.2, page 275 <br/> /// </remarks> public sealed class ILU0Preconditioner : IPreconditioner<Complex32> { /// <summary> /// The matrix holding the lower (L) and upper (U) matrices. The /// decomposition matrices are combined to reduce storage. /// </summary> SparseMatrix _decompositionLU; /// <summary> /// Returns the upper triagonal matrix that was created during the LU decomposition. /// </summary> /// <returns>A new matrix containing the upper triagonal elements.</returns> internal Matrix<Complex32> UpperTriangle() { var result = new SparseMatrix(_decompositionLU.RowCount); for (var i = 0; i < _decompositionLU.RowCount; i++) { for (var j = i; j < _decompositionLU.ColumnCount; j++) { result[i, j] = _decompositionLU[i, j]; } } return result; } /// <summary> /// Returns the lower triagonal matrix that was created during the LU decomposition. /// </summary> /// <returns>A new matrix containing the lower triagonal elements.</returns> internal Matrix<Complex32> LowerTriangle() { var result = new SparseMatrix(_decompositionLU.RowCount); for (var i = 0; i < _decompositionLU.RowCount; i++) { for (var j = 0; j <= i; j++) { if (i == j) { result[i, j] = 1.0f; } else { result[i, j] = _decompositionLU[i, j]; } } } return result; } /// <summary> /// Initializes the preconditioner and loads the internal data structures. /// </summary> /// <param name="matrix">The matrix upon which the preconditioner is based. </param> /// <exception cref="ArgumentNullException">If <paramref name="matrix"/> is <see langword="null" />.</exception> /// <exception cref="ArgumentException">If <paramref name="matrix"/> is not a square matrix.</exception> public void Initialize(Matrix<Complex32> matrix) { if (matrix == null) { throw new ArgumentNullException("matrix"); } if (matrix.RowCount != matrix.ColumnCount) { throw new ArgumentException(Resource.ArgumentMatrixSquare, "matrix"); } _decompositionLU = SparseMatrix.OfMatrix(matrix); // M == A // for i = 2, ... , n do // for k = 1, .... , i - 1 do // if (i,k) == NZ(Z) then // compute z(i,k) = z(i,k) / z(k,k); // for j = k + 1, ...., n do // if (i,j) == NZ(Z) then // compute z(i,j) = z(i,j) - z(i,k) * z(k,j) // end // end // end // end // end for (var i = 0; i < _decompositionLU.RowCount; i++) { for (var k = 0; k < i; k++) { if (_decompositionLU[i, k] != 0.0f) { var t = _decompositionLU[i, k]/_decompositionLU[k, k]; _decompositionLU[i, k] = t; if (_decompositionLU[k, i] != 0.0f) { _decompositionLU[i, i] = _decompositionLU[i, i] - (t*_decompositionLU[k, i]); } for (var j = k + 1; j < _decompositionLU.RowCount; j++) { if (j == i) { continue; } if (_decompositionLU[i, j] != 0.0f) { _decompositionLU[i, j] = _decompositionLU[i, j] - (t*_decompositionLU[k, j]); } } } } } } /// <summary> /// Approximates the solution to the matrix equation <b>Ax = b</b>. /// </summary> /// <param name="rhs">The right hand side vector.</param> /// <param name="lhs">The left hand side vector. Also known as the result vector.</param> public void Approximate(Vector<Complex32> rhs, Vector<Complex32> lhs) { if (_decompositionLU == null) { throw new ArgumentException(Resource.ArgumentMatrixDoesNotExist); } if ((lhs.Count != rhs.Count) || (lhs.Count != _decompositionLU.RowCount)) { throw new ArgumentException(Resource.ArgumentVectorsSameLength); } // Solve: // Lz = y // Which gives // for (int i = 1; i < matrix.RowLength; i++) // { // z_i = l_ii^-1 * (y_i - SUM_(j<i) l_ij * z_j) // } // NOTE: l_ii should be 1 because u_ii has to be the value var rowValues = new DenseVector(_decompositionLU.RowCount); for (var i = 0; i < _decompositionLU.RowCount; i++) { // Clear the rowValues rowValues.Clear(); _decompositionLU.Row(i, rowValues); var sum = Complex32.Zero; for (var j = 0; j < i; j++) { sum += rowValues[j]*lhs[j]; } lhs[i] = rhs[i] - sum; } // Solve: // Ux = z // Which gives // for (int i = matrix.RowLength - 1; i > -1; i--) // { // x_i = u_ii^-1 * (z_i - SUM_(j > i) u_ij * x_j) // } for (var i = _decompositionLU.RowCount - 1; i > -1; i--) { _decompositionLU.Row(i, rowValues); var sum = Complex32.Zero; for (var j = _decompositionLU.RowCount - 1; j > i; j--) { sum += rowValues[j]*lhs[j]; } lhs[i] = 1/rowValues[i]*(lhs[i] - sum); } } } }
#region Copyright notice and license // Copyright 2015, Google Inc. // 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Google.Apis.Auth.OAuth2; using Google.Protobuf; using Grpc.Auth; using Grpc.Core; using Grpc.Core.Utils; using Grpc.Testing; using NUnit.Framework; namespace Grpc.IntegrationTesting { public class InteropClient { private const string ServiceAccountUser = "155450119199-3psnrh1sdr3d8cpj1v46naggf81mhdnk@developer.gserviceaccount.com"; private const string ComputeEngineUser = "155450119199-r5aaqa2vqoa9g5mv2m6s3m1l293rlmel@developer.gserviceaccount.com"; private const string AuthScope = "https://www.googleapis.com/auth/xapi.zoo"; private const string AuthScopeResponse = "xapi.zoo"; private class ClientOptions { public bool help; public string serverHost = "127.0.0.1"; public string serverHostOverride = TestCredentials.DefaultHostOverride; public int? serverPort; public string testCase = "large_unary"; public bool useTls; public bool useTestCa; } ClientOptions options; private InteropClient(ClientOptions options) { this.options = options; } public static void Run(string[] args) { Console.WriteLine("gRPC C# interop testing client"); ClientOptions options = ParseArguments(args); if (options.serverHost == null || !options.serverPort.HasValue || options.testCase == null) { Console.WriteLine("Missing required argument."); Console.WriteLine(); options.help = true; } if (options.help) { Console.WriteLine("Usage:"); Console.WriteLine(" --server_host=HOSTNAME"); Console.WriteLine(" --server_host_override=HOSTNAME"); Console.WriteLine(" --server_port=PORT"); Console.WriteLine(" --test_case=TESTCASE"); Console.WriteLine(" --use_tls=BOOLEAN"); Console.WriteLine(" --use_test_ca=BOOLEAN"); Console.WriteLine(); Environment.Exit(1); } var interopClient = new InteropClient(options); interopClient.Run().Wait(); } private async Task Run() { Credentials credentials = null; if (options.useTls) { credentials = TestCredentials.CreateTestClientCredentials(options.useTestCa); } List<ChannelOption> channelOptions = null; if (!string.IsNullOrEmpty(options.serverHostOverride)) { channelOptions = new List<ChannelOption> { new ChannelOption(ChannelOptions.SslTargetNameOverride, options.serverHostOverride) }; } var channel = new Channel(options.serverHost, options.serverPort.Value, credentials, channelOptions); TestService.TestServiceClient client = new TestService.TestServiceClient(channel); await RunTestCaseAsync(options.testCase, client); channel.ShutdownAsync().Wait(); } private async Task RunTestCaseAsync(string testCase, TestService.TestServiceClient client) { switch (testCase) { case "empty_unary": RunEmptyUnary(client); break; case "large_unary": RunLargeUnary(client); break; case "client_streaming": await RunClientStreamingAsync(client); break; case "server_streaming": await RunServerStreamingAsync(client); break; case "ping_pong": await RunPingPongAsync(client); break; case "empty_stream": await RunEmptyStreamAsync(client); break; case "service_account_creds": await RunServiceAccountCredsAsync(client); break; case "compute_engine_creds": await RunComputeEngineCredsAsync(client); break; case "jwt_token_creds": await RunJwtTokenCredsAsync(client); break; case "oauth2_auth_token": await RunOAuth2AuthTokenAsync(client); break; case "per_rpc_creds": await RunPerRpcCredsAsync(client); break; case "cancel_after_begin": await RunCancelAfterBeginAsync(client); break; case "cancel_after_first_response": await RunCancelAfterFirstResponseAsync(client); break; case "timeout_on_sleeping_server": await RunTimeoutOnSleepingServerAsync(client); break; case "benchmark_empty_unary": RunBenchmarkEmptyUnary(client); break; default: throw new ArgumentException("Unknown test case " + testCase); } } public static void RunEmptyUnary(TestService.ITestServiceClient client) { Console.WriteLine("running empty_unary"); var response = client.EmptyCall(new Empty()); Assert.IsNotNull(response); Console.WriteLine("Passed!"); } public static void RunLargeUnary(TestService.ITestServiceClient client) { Console.WriteLine("running large_unary"); var request = new SimpleRequest { ResponseType = PayloadType.COMPRESSABLE, ResponseSize = 314159, Payload = CreateZerosPayload(271828) }; var response = client.UnaryCall(request); Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type); Assert.AreEqual(314159, response.Payload.Body.Length); Console.WriteLine("Passed!"); } public static async Task RunClientStreamingAsync(TestService.ITestServiceClient client) { Console.WriteLine("running client_streaming"); var bodySizes = new List<int> { 27182, 8, 1828, 45904 }.ConvertAll((size) => new StreamingInputCallRequest { Payload = CreateZerosPayload(size) }); using (var call = client.StreamingInputCall()) { await call.RequestStream.WriteAllAsync(bodySizes); var response = await call.ResponseAsync; Assert.AreEqual(74922, response.AggregatedPayloadSize); } Console.WriteLine("Passed!"); } public static async Task RunServerStreamingAsync(TestService.ITestServiceClient client) { Console.WriteLine("running server_streaming"); var bodySizes = new List<int> { 31415, 9, 2653, 58979 }; var request = new StreamingOutputCallRequest { ResponseType = PayloadType.COMPRESSABLE, ResponseParameters = { bodySizes.ConvertAll((size) => new ResponseParameters { Size = size }) } }; using (var call = client.StreamingOutputCall(request)) { var responseList = await call.ResponseStream.ToListAsync(); foreach (var res in responseList) { Assert.AreEqual(PayloadType.COMPRESSABLE, res.Payload.Type); } CollectionAssert.AreEqual(bodySizes, responseList.ConvertAll((item) => item.Payload.Body.Length)); } Console.WriteLine("Passed!"); } public static async Task RunPingPongAsync(TestService.ITestServiceClient client) { Console.WriteLine("running ping_pong"); using (var call = client.FullDuplexCall()) { await call.RequestStream.WriteAsync(new StreamingOutputCallRequest { ResponseType = PayloadType.COMPRESSABLE, ResponseParameters = { new ResponseParameters { Size = 31415 } }, Payload = CreateZerosPayload(27182) }); Assert.IsTrue(await call.ResponseStream.MoveNext()); Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type); Assert.AreEqual(31415, call.ResponseStream.Current.Payload.Body.Length); await call.RequestStream.WriteAsync(new StreamingOutputCallRequest { ResponseType = PayloadType.COMPRESSABLE, ResponseParameters = { new ResponseParameters { Size = 9 } }, Payload = CreateZerosPayload(8) }); Assert.IsTrue(await call.ResponseStream.MoveNext()); Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type); Assert.AreEqual(9, call.ResponseStream.Current.Payload.Body.Length); await call.RequestStream.WriteAsync(new StreamingOutputCallRequest { ResponseType = PayloadType.COMPRESSABLE, ResponseParameters = { new ResponseParameters { Size = 2653 } }, Payload = CreateZerosPayload(1828) }); Assert.IsTrue(await call.ResponseStream.MoveNext()); Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type); Assert.AreEqual(2653, call.ResponseStream.Current.Payload.Body.Length); await call.RequestStream.WriteAsync(new StreamingOutputCallRequest { ResponseType = PayloadType.COMPRESSABLE, ResponseParameters = { new ResponseParameters { Size = 58979 } }, Payload = CreateZerosPayload(45904) }); Assert.IsTrue(await call.ResponseStream.MoveNext()); Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type); Assert.AreEqual(58979, call.ResponseStream.Current.Payload.Body.Length); await call.RequestStream.CompleteAsync(); Assert.IsFalse(await call.ResponseStream.MoveNext()); } Console.WriteLine("Passed!"); } public static async Task RunEmptyStreamAsync(TestService.ITestServiceClient client) { Console.WriteLine("running empty_stream"); using (var call = client.FullDuplexCall()) { await call.RequestStream.CompleteAsync(); var responseList = await call.ResponseStream.ToListAsync(); Assert.AreEqual(0, responseList.Count); } Console.WriteLine("Passed!"); } public static async Task RunServiceAccountCredsAsync(TestService.TestServiceClient client) { Console.WriteLine("running service_account_creds"); var credential = await GoogleCredential.GetApplicationDefaultAsync(); credential = credential.CreateScoped(new[] { AuthScope }); client.HeaderInterceptor = AuthInterceptors.FromCredential(credential); var request = new SimpleRequest { ResponseType = PayloadType.COMPRESSABLE, ResponseSize = 314159, Payload = CreateZerosPayload(271828), FillUsername = true, FillOauthScope = true }; var response = client.UnaryCall(request); Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type); Assert.AreEqual(314159, response.Payload.Body.Length); Assert.AreEqual(AuthScopeResponse, response.OauthScope); Assert.AreEqual(ServiceAccountUser, response.Username); Console.WriteLine("Passed!"); } public static async Task RunComputeEngineCredsAsync(TestService.TestServiceClient client) { Console.WriteLine("running compute_engine_creds"); var credential = await GoogleCredential.GetApplicationDefaultAsync(); Assert.IsFalse(credential.IsCreateScopedRequired); client.HeaderInterceptor = AuthInterceptors.FromCredential(credential); var request = new SimpleRequest { ResponseType = PayloadType.COMPRESSABLE, ResponseSize = 314159, Payload = CreateZerosPayload(271828), FillUsername = true, FillOauthScope = true }; var response = client.UnaryCall(request); Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type); Assert.AreEqual(314159, response.Payload.Body.Length); Assert.AreEqual(AuthScopeResponse, response.OauthScope); Assert.AreEqual(ComputeEngineUser, response.Username); Console.WriteLine("Passed!"); } public static async Task RunJwtTokenCredsAsync(TestService.TestServiceClient client) { Console.WriteLine("running jwt_token_creds"); var credential = await GoogleCredential.GetApplicationDefaultAsync(); // check this a credential with scope support, but don't add the scope. Assert.IsTrue(credential.IsCreateScopedRequired); client.HeaderInterceptor = AuthInterceptors.FromCredential(credential); var request = new SimpleRequest { ResponseType = PayloadType.COMPRESSABLE, ResponseSize = 314159, Payload = CreateZerosPayload(271828), FillUsername = true, FillOauthScope = true }; var response = client.UnaryCall(request); Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type); Assert.AreEqual(314159, response.Payload.Body.Length); Assert.AreEqual(ServiceAccountUser, response.Username); Console.WriteLine("Passed!"); } public static async Task RunOAuth2AuthTokenAsync(TestService.TestServiceClient client) { Console.WriteLine("running oauth2_auth_token"); ITokenAccess credential = (await GoogleCredential.GetApplicationDefaultAsync()).CreateScoped(new[] { AuthScope }); string oauth2Token = await credential.GetAccessTokenForRequestAsync(); client.HeaderInterceptor = AuthInterceptors.FromAccessToken(oauth2Token); var request = new SimpleRequest { FillUsername = true, FillOauthScope = true }; var response = client.UnaryCall(request); Assert.AreEqual(AuthScopeResponse, response.OauthScope); Assert.AreEqual(ServiceAccountUser, response.Username); Console.WriteLine("Passed!"); } public static async Task RunPerRpcCredsAsync(TestService.TestServiceClient client) { Console.WriteLine("running per_rpc_creds"); ITokenAccess credential = (await GoogleCredential.GetApplicationDefaultAsync()).CreateScoped(new[] { AuthScope }); string oauth2Token = await credential.GetAccessTokenForRequestAsync(); var headerInterceptor = AuthInterceptors.FromAccessToken(oauth2Token); var request = new SimpleRequest { FillUsername = true, FillOauthScope = true }; var headers = new Metadata(); headerInterceptor(null, "", headers); var response = client.UnaryCall(request, headers: headers); Assert.AreEqual(AuthScopeResponse, response.OauthScope); Assert.AreEqual(ServiceAccountUser, response.Username); Console.WriteLine("Passed!"); } public static async Task RunCancelAfterBeginAsync(TestService.ITestServiceClient client) { Console.WriteLine("running cancel_after_begin"); var cts = new CancellationTokenSource(); using (var call = client.StreamingInputCall(cancellationToken: cts.Token)) { // TODO(jtattermusch): we need this to ensure call has been initiated once we cancel it. await Task.Delay(1000); cts.Cancel(); var ex = Assert.Throws<RpcException>(async () => await call.ResponseAsync); Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode); } Console.WriteLine("Passed!"); } public static async Task RunCancelAfterFirstResponseAsync(TestService.ITestServiceClient client) { Console.WriteLine("running cancel_after_first_response"); var cts = new CancellationTokenSource(); using (var call = client.FullDuplexCall(cancellationToken: cts.Token)) { await call.RequestStream.WriteAsync(new StreamingOutputCallRequest { ResponseType = PayloadType.COMPRESSABLE, ResponseParameters = { new ResponseParameters { Size = 31415 } }, Payload = CreateZerosPayload(27182) }); Assert.IsTrue(await call.ResponseStream.MoveNext()); Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type); Assert.AreEqual(31415, call.ResponseStream.Current.Payload.Body.Length); cts.Cancel(); var ex = Assert.Throws<RpcException>(async () => await call.ResponseStream.MoveNext()); Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode); } Console.WriteLine("Passed!"); } public static async Task RunTimeoutOnSleepingServerAsync(TestService.ITestServiceClient client) { Console.WriteLine("running timeout_on_sleeping_server"); var deadline = DateTime.UtcNow.AddMilliseconds(1); using (var call = client.FullDuplexCall(deadline: deadline)) { try { await call.RequestStream.WriteAsync(new StreamingOutputCallRequest { Payload = CreateZerosPayload(27182) }); } catch (InvalidOperationException) { // Deadline was reached before write has started. Eat the exception and continue. } var ex = Assert.Throws<RpcException>(async () => await call.ResponseStream.MoveNext()); Assert.AreEqual(StatusCode.DeadlineExceeded, ex.Status.StatusCode); } Console.WriteLine("Passed!"); } // This is not an official interop test, but it's useful. public static void RunBenchmarkEmptyUnary(TestService.ITestServiceClient client) { BenchmarkUtil.RunBenchmark(10000, 10000, () => { client.EmptyCall(new Empty()); }); } private static Payload CreateZerosPayload(int size) { return new Payload { Body = ByteString.CopyFrom(new byte[size]) }; } private static ClientOptions ParseArguments(string[] args) { var options = new ClientOptions(); foreach (string arg in args) { ParseArgument(arg, options); if (options.help) { break; } } return options; } private static void ParseArgument(string arg, ClientOptions options) { Match match; match = Regex.Match(arg, "--server_host=(.*)"); if (match.Success) { options.serverHost = match.Groups[1].Value.Trim(); return; } match = Regex.Match(arg, "--server_host_override=(.*)"); if (match.Success) { options.serverHostOverride = match.Groups[1].Value.Trim(); return; } match = Regex.Match(arg, "--server_port=(.*)"); if (match.Success) { options.serverPort = int.Parse(match.Groups[1].Value.Trim()); return; } match = Regex.Match(arg, "--test_case=(.*)"); if (match.Success) { options.testCase = match.Groups[1].Value.Trim(); return; } match = Regex.Match(arg, "--use_tls=(.*)"); if (match.Success) { options.useTls = bool.Parse(match.Groups[1].Value.Trim()); return; } match = Regex.Match(arg, "--use_test_ca=(.*)"); if (match.Success) { options.useTestCa = bool.Parse(match.Groups[1].Value.Trim()); return; } Console.WriteLine(string.Format("Unrecognized argument \"{0}\"", arg)); options.help = 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.Threading.Tasks; using System.Threading; using System.Runtime.ExceptionServices; using Xunit; namespace System.Data.SqlClient.ManualTesting.Tests { public class ConnectionPoolTest { private readonly string _nwnd9Tcp = null; private readonly string _nwnd9TcpMars = null; private readonly string _nwnd9Np = null; private readonly string _nwnd9NpMars = null; private readonly string _nwnd10Tcp = null; private readonly string _nwnd10TcpMars = null; private readonly string _nwnd10Np = null; private readonly string _nwnd10NpMars = null; public ConnectionPoolTest() { PrepareConnectionStrings(DataTestClass.SQL2005_Northwind, out _nwnd9Tcp, out _nwnd9TcpMars, out _nwnd9Np, out _nwnd9NpMars); PrepareConnectionStrings(DataTestClass.SQL2008_Northwind, out _nwnd10Tcp, out _nwnd10TcpMars, out _nwnd10Np, out _nwnd10NpMars); } [Fact] public void ConnectionPool_Nwnd9() { RunDataTestForSingleConnString(_nwnd9Tcp, _nwnd9Np, false); } [Fact] public void ConnectionPool_Nwnd9Mars() { RunDataTestForSingleConnString(_nwnd9TcpMars, _nwnd9NpMars, false); } [Fact] public void ConnectionPool_Nwnd10() { RunDataTestForSingleConnString(_nwnd10Tcp, _nwnd10Np, true); } [Fact] public void ConnectionPool_Nwnd10Mars() { RunDataTestForSingleConnString(_nwnd10TcpMars, _nwnd10NpMars, true); } private static void RunDataTestForSingleConnString(string tcpConnectionString, string npConnectionString, bool serverIsKatmaiOrLater) { BasicConnectionPoolingTest(tcpConnectionString); ClearAllPoolsTest(tcpConnectionString); #if MANAGED_SNI && DEBUG KillConnectionTest(tcpConnectionString); #endif ReclaimEmancipatedOnOpenTest(tcpConnectionString); } /// <summary> /// Tests that using the same connection string results in the same pool\internal connection and a different string results in a different pool\internal connection /// </summary> /// <param name="connectionString"></param> private static void BasicConnectionPoolingTest(string connectionString) { SqlConnection connection = new SqlConnection(connectionString); connection.Open(); InternalConnectionWrapper internalConnection = new InternalConnectionWrapper(connection); ConnectionPoolWrapper connectionPool = new ConnectionPoolWrapper(connection); connection.Close(); SqlConnection connection2 = new SqlConnection(connectionString); connection2.Open(); Assert.True(internalConnection.IsInternalConnectionOf(connection2), "New connection does not use same internal connection"); Assert.True(connectionPool.ContainsConnection(connection2), "New connection is in a different pool"); connection2.Close(); SqlConnection connection3 = new SqlConnection(connectionString + ";App=SqlConnectionPoolUnitTest;"); connection3.Open(); Assert.False(internalConnection.IsInternalConnectionOf(connection3), "Connection with different connection string uses same internal connection"); Assert.False(connectionPool.ContainsConnection(connection3), "Connection with different connection string uses same connection pool"); connection3.Close(); connectionPool.Cleanup(); SqlConnection connection4 = new SqlConnection(connectionString); connection4.Open(); Assert.True(internalConnection.IsInternalConnectionOf(connection4), "New connection does not use same internal connection"); Assert.True(connectionPool.ContainsConnection(connection4), "New connection is in a different pool"); connection4.Close(); } #if MANAGED_SNI && DEBUG /// <summary> /// Tests if killing the connection using the InternalConnectionWrapper is working /// </summary> /// <param name="connectionString"></param> private static void KillConnectionTest(string connectionString) { InternalConnectionWrapper wrapper = null; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); wrapper = new InternalConnectionWrapper(connection); using (SqlCommand command = new SqlCommand("SELECT 5;", connection)) { DataTestClass.AssertEqualsWithDescription(5, command.ExecuteScalar(), "Incorrect scalar result."); } wrapper.KillConnection(); } using (SqlConnection connection2 = new SqlConnection(connectionString)) { connection2.Open(); Assert.False(wrapper.IsInternalConnectionOf(connection2), "New connection has internal connection that was just killed"); using (SqlCommand command = new SqlCommand("SELECT 5;", connection2)) { DataTestClass.AssertEqualsWithDescription(5, command.ExecuteScalar(), "Incorrect scalar result."); } } } #endif /// <summary> /// Tests if clearing all of the pools does actually remove the pools /// </summary> /// <param name="connectionString"></param> private static void ClearAllPoolsTest(string connectionString) { SqlConnection.ClearAllPools(); Assert.True(0 == ConnectionPoolWrapper.AllConnectionPools().Length, "Pools exist after clearing all pools"); SqlConnection connection = new SqlConnection(connectionString); connection.Open(); ConnectionPoolWrapper pool = new ConnectionPoolWrapper(connection); connection.Close(); ConnectionPoolWrapper[] allPools = ConnectionPoolWrapper.AllConnectionPools(); DataTestClass.AssertEqualsWithDescription(1, allPools.Length, "Incorrect number of pools exist."); Assert.True(allPools[0].Equals(pool), "Saved pool is not in the list of all pools"); DataTestClass.AssertEqualsWithDescription(1, pool.ConnectionCount, "Saved pool has incorrect number of connections"); SqlConnection.ClearAllPools(); Assert.True(0 == ConnectionPoolWrapper.AllConnectionPools().Length, "Pools exist after clearing all pools"); DataTestClass.AssertEqualsWithDescription(0, pool.ConnectionCount, "Saved pool has incorrect number of connections."); } /// <summary> /// Checks if an 'emancipated' internal connection is reclaimed when a new connection is opened AND we hit max pool size /// NOTE: 'emancipated' means that the internal connection's SqlConnection has fallen out of scope and has no references, but was not explicitly disposed\closed /// </summary> /// <param name="connectionString"></param> private static void ReclaimEmancipatedOnOpenTest(string connectionString) { string newConnectionString = connectionString + ";Max Pool Size=1"; SqlConnection.ClearAllPools(); InternalConnectionWrapper internalConnection = CreateEmancipatedConnection(newConnectionString); ConnectionPoolWrapper connectionPool = internalConnection.ConnectionPool; GC.Collect(); GC.WaitForPendingFinalizers(); DataTestClass.AssertEqualsWithDescription(1, connectionPool.ConnectionCount, "Wrong number of connections in the pool."); DataTestClass.AssertEqualsWithDescription(0, connectionPool.FreeConnectionCount, "Wrong number of free connections in the pool."); using (SqlConnection connection = new SqlConnection(newConnectionString)) { connection.Open(); Assert.True(internalConnection.IsInternalConnectionOf(connection), "Connection has wrong internal connection"); Assert.True(connectionPool.ContainsConnection(connection), "Connection is in wrong connection pool"); } } private static void ReplacementConnectionUsesSemaphoreTest(string connectionString) { string newConnectionString = (new SqlConnectionStringBuilder(connectionString) { MaxPoolSize = 2, ConnectTimeout = 5 }).ConnectionString; SqlConnection.ClearAllPools(); SqlConnection liveConnection = new SqlConnection(newConnectionString); SqlConnection deadConnection = new SqlConnection(newConnectionString); liveConnection.Open(); deadConnection.Open(); InternalConnectionWrapper deadConnectionInternal = new InternalConnectionWrapper(deadConnection); InternalConnectionWrapper liveConnectionInternal = new InternalConnectionWrapper(liveConnection); deadConnectionInternal.KillConnection(); deadConnection.Close(); liveConnection.Close(); Task<InternalConnectionWrapper>[] tasks = new Task<InternalConnectionWrapper>[3]; Barrier syncBarrier = new Barrier(tasks.Length); Func<InternalConnectionWrapper> taskFunction = (() => ReplacementConnectionUsesSemaphoreTask(newConnectionString, syncBarrier)); for (int i = 0; i < tasks.Length; i++) { tasks[i] = Task.Factory.StartNew<InternalConnectionWrapper>(taskFunction); } bool taskWithLiveConnection = false; bool taskWithNewConnection = false; bool taskWithCorrectException = false; Task waitAllTask = Task.Factory.ContinueWhenAll(tasks, (completedTasks) => { foreach (var item in completedTasks) { if (item.Status == TaskStatus.Faulted) { // One task should have a timeout exception if ((!taskWithCorrectException) && (item.Exception.InnerException is InvalidOperationException) && (item.Exception.InnerException.Message.StartsWith(SystemDataResourceManager.Instance.ADP_PooledOpenTimeout))) taskWithCorrectException = true; else if (!taskWithCorrectException) { // Rethrow the unknown exception ExceptionDispatchInfo exceptionInfo = ExceptionDispatchInfo.Capture(item.Exception); exceptionInfo.Throw(); } } else if (item.Status == TaskStatus.RanToCompletion) { // One task should get the live connection if (item.Result.Equals(liveConnectionInternal)) { if (!taskWithLiveConnection) taskWithLiveConnection = true; } else if (!item.Result.Equals(deadConnectionInternal) && !taskWithNewConnection) taskWithNewConnection = true; } else Console.WriteLine("ERROR: Task in unknown state: {0}", item.Status); } }); waitAllTask.Wait(); Assert.True(taskWithLiveConnection && taskWithNewConnection && taskWithCorrectException, string.Format("Tasks didn't finish as expected.\nTask with live connection: {0}\nTask with new connection: {1}\nTask with correct exception: {2}\n", taskWithLiveConnection, taskWithNewConnection, taskWithCorrectException)); } private static InternalConnectionWrapper ReplacementConnectionUsesSemaphoreTask(string connectionString, Barrier syncBarrier) { InternalConnectionWrapper internalConnection = null; using (SqlConnection connection = new SqlConnection(connectionString)) { try { connection.Open(); internalConnection = new InternalConnectionWrapper(connection); } catch { syncBarrier.SignalAndWait(); throw; } syncBarrier.SignalAndWait(); } return internalConnection; } private static InternalConnectionWrapper CreateEmancipatedConnection(string connectionString) { SqlConnection connection = new SqlConnection(connectionString); connection.Open(); return new InternalConnectionWrapper(connection); } private static void PrepareConnectionStrings(string originalString, out string tcpString, out string tcpMarsString, out string npString, out string npMarsString) { SqlConnectionStringBuilder connBuilder = new SqlConnectionStringBuilder(originalString); DataSourceBuilder sourceBuilder = new DataSourceBuilder(connBuilder.DataSource); sourceBuilder.Protocol = null; // TCP connBuilder.DataSource = sourceBuilder.ToString(); connBuilder.MultipleActiveResultSets = false; tcpString = connBuilder.ConnectionString; // TCP + MARS connBuilder.MultipleActiveResultSets = true; tcpMarsString = connBuilder.ConnectionString; // Named Pipes sourceBuilder.Port = null; connBuilder.DataSource = "np:" + sourceBuilder.ToString(); connBuilder.MultipleActiveResultSets = false; npString = connBuilder.ConnectionString; // Named Pipes + MARS connBuilder.MultipleActiveResultSets = true; npMarsString = connBuilder.ConnectionString; } } }
using Edu.Wisc.Forest.Flel.Util; using Landis.Extensions.BiomassHarvest; using Landis.Harvest; using NUnit.Framework; namespace Landis.Tests.BiomassHarvest { [TestFixture] public class PartialThinning_Test { private bool eventHandlerCalled; private AgeRange expectedRange; private Percentage expectedPercentage; //--------------------------------------------------------------------- [TestFixtureSetUp] public void Init() { PartialThinning.ReadAgeOrRangeEvent += AgeOrRangeWasRead; } //--------------------------------------------------------------------- [TestFixtureTearDown] public void TearDown() { PartialThinning.ReadAgeOrRangeEvent -= AgeOrRangeWasRead; } //--------------------------------------------------------------------- public void AgeOrRangeWasRead(AgeRange ageRange, Percentage percentage) { Assert.AreEqual(expectedRange, ageRange); if (expectedPercentage == null) Assert.IsNull(percentage); else Assert.AreEqual((double) expectedPercentage, (double) percentage); eventHandlerCalled = true; } //--------------------------------------------------------------------- [Test] public void ReadAgeOrRange_RangePercentage() { StringReader reader = new StringReader("30-75(10%)"); int index; eventHandlerCalled = false; expectedRange = new AgeRange(30, 75); expectedPercentage = Percentage.Parse("10%"); InputValue<AgeRange> ageRange = PartialThinning.ReadAgeOrRange(reader, out index); Assert.IsTrue(eventHandlerCalled); Assert.AreEqual(0, index); Assert.AreEqual(-1, reader.Peek()); } //--------------------------------------------------------------------- [Test] public void ReadAgeOrRange_RangeWhitespacePercentage() { StringReader reader = new StringReader(" 1-100 (22.2%)Hi"); int index; eventHandlerCalled = false; expectedRange = new AgeRange(1, 100); expectedPercentage = Percentage.Parse("22.2%"); InputValue<AgeRange> ageRange = PartialThinning.ReadAgeOrRange(reader, out index); Assert.IsTrue(eventHandlerCalled); Assert.AreEqual(1, index); Assert.AreEqual('H', reader.Peek()); } //--------------------------------------------------------------------- [Test] public void ReadAgeOrRange_AgeWhitespacePercentage() { StringReader reader = new StringReader("66 ( 50% )\t"); int index; eventHandlerCalled = false; expectedRange = new AgeRange(66, 66); expectedPercentage = Percentage.Parse("50%"); InputValue<AgeRange> ageRange = PartialThinning.ReadAgeOrRange(reader, out index); Assert.IsTrue(eventHandlerCalled); Assert.AreEqual(0, index); Assert.AreEqual('\t', reader.Peek()); } //--------------------------------------------------------------------- [Test] public void ReadAgeOrRange_Multiple() { StringReader reader = new StringReader(" 1-40 (50%) 50(65%)\t 65-70 71-107 ( 15% ) 109"); int index; //0123456789_123456789_^123456789_123456789_12345678 eventHandlerCalled = false; expectedRange = new AgeRange(1, 40); expectedPercentage = Percentage.Parse("50%"); InputValue<AgeRange> ageRange = PartialThinning.ReadAgeOrRange(reader, out index); Assert.IsTrue(eventHandlerCalled); Assert.AreEqual(1, index); Assert.AreEqual(' ', reader.Peek()); eventHandlerCalled = false; expectedRange = new AgeRange(50, 50); expectedPercentage = Percentage.Parse("65%"); ageRange = PartialThinning.ReadAgeOrRange(reader, out index); Assert.IsTrue(eventHandlerCalled); Assert.AreEqual(13, index); Assert.AreEqual('\t', reader.Peek()); eventHandlerCalled = false; expectedRange = new AgeRange(65, 70); expectedPercentage = null; ageRange = PartialThinning.ReadAgeOrRange(reader, out index); Assert.IsTrue(eventHandlerCalled); Assert.AreEqual(22, index); Assert.AreEqual('7', reader.Peek()); eventHandlerCalled = false; expectedRange = new AgeRange(71, 107); expectedPercentage = Percentage.Parse("15%"); ageRange = PartialThinning.ReadAgeOrRange(reader, out index); Assert.IsTrue(eventHandlerCalled); Assert.AreEqual(29, index); Assert.AreEqual(' ', reader.Peek()); eventHandlerCalled = false; expectedRange = new AgeRange(109, 109); expectedPercentage = null; ageRange = PartialThinning.ReadAgeOrRange(reader, out index); Assert.IsTrue(eventHandlerCalled); Assert.AreEqual(45, index); Assert.AreEqual(-1, reader.Peek()); } //--------------------------------------------------------------------- [Test] public void ReadPercentage_NoWhitespace() { StringReader reader = new StringReader("(10%)"); int index; InputValue<Percentage> percentage = PartialThinning.ReadPercentage(reader, out index); Assert.IsNotNull(percentage); Assert.AreEqual("(10%)", percentage.String); Assert.AreEqual(0.10, (double) (percentage.Actual)); Assert.AreEqual(0, index); Assert.AreEqual(-1, reader.Peek()); } //--------------------------------------------------------------------- [Test] public void ReadPercentage_LeadingWhitespace() { StringReader reader = new StringReader(" \t (10%)"); int index; InputValue<Percentage> percentage = PartialThinning.ReadPercentage(reader, out index); Assert.IsNotNull(percentage); Assert.AreEqual("(10%)", percentage.String); Assert.AreEqual(0.10, (double) (percentage.Actual)); Assert.AreEqual(3, index); Assert.AreEqual(-1, reader.Peek()); } //--------------------------------------------------------------------- [Test] public void ReadPercentage_WhitespaceAfterLParen() { StringReader reader = new StringReader("( 8%)a"); int index; InputValue<Percentage> percentage = PartialThinning.ReadPercentage(reader, out index); Assert.IsNotNull(percentage); Assert.AreEqual("( 8%)", percentage.String); Assert.AreEqual(0.08, (double) (percentage.Actual)); Assert.AreEqual(0, index); Assert.AreEqual('a', reader.Peek()); } //--------------------------------------------------------------------- [Test] public void ReadPercentage_Whitespace() { StringReader reader = new StringReader("( 55.5%\t)"); int index; InputValue<Percentage> percentage = PartialThinning.ReadPercentage(reader, out index); Assert.IsNotNull(percentage); Assert.AreEqual("( 55.5%\t)", percentage.String); Assert.AreEqual(0.555, (double) (percentage.Actual)); Assert.AreEqual(0, index); Assert.AreEqual(-1, reader.Peek()); } //--------------------------------------------------------------------- private void TryReadPercentage(string input, string expectedValue, string expectedError) { StringReader reader = new StringReader(input); int index; try { InputValue<Percentage> percentage = PartialThinning.ReadPercentage(reader, out index); } catch (InputValueException exc) { Data.Output.WriteLine(); Data.Output.WriteLine(exc.Message); Assert.AreEqual(expectedValue, exc.Value); MultiLineText multiLineMesg = exc.MultiLineMessage; string lastLine = multiLineMesg[multiLineMesg.Count - 1]; Assert.AreEqual(expectedError, lastLine.Trim()); throw exc; } } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(InputValueException))] public void ReadPercentage_Empty() { TryReadPercentage("", null, "Missing value"); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(InputValueException))] public void ReadPercentage_Missing() { TryReadPercentage(" \t", null, "Missing value"); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(InputValueException))] public void ReadPercentage_1stCharNotLeftParen() { TryReadPercentage(" 50% )", "50%", "Value does not start with \"(\""); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(InputValueException))] public void ReadPercentage_NoPercentage() { TryReadPercentage(" ( \t", "( \t", "No percentage after \"(\""); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(InputValueException))] public void ReadPercentage_BadNumber() { TryReadPercentage(" ( 50a%)", "( 50a%", "\"50a\" is not a valid number"); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(InputValueException))] public void ReadPercentage_BelowMin() { TryReadPercentage("( -1.2%)", "( -1.2%", "-1.2% is not between 0% and 100%"); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(InputValueException))] public void ReadPercentage_AboveMax() { TryReadPercentage("(123%)", "(123%", "123% is not between 0% and 100%"); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(InputValueException))] public void ReadPercentage_MissingPercent() { TryReadPercentage(" ( 25 %)", "( 25", "Missing \"%\" at end of percentage value"); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(InputValueException))] public void ReadPercentage_NoRightParen() { TryReadPercentage("( 22% ", "( 22% ", "Missing \")\""); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(InputValueException))] public void ReadPercentage_LastCharNotRightParen() { TryReadPercentage(" ( 8% XYZ", "( 8% X", "Value ends with \"X\" instead of \")\""); } //--------------------------------------------------------------------- [Test] public void ReadWord_Empty() { StringReader reader = new StringReader(""); string word = PartialThinning.ReadWord(reader, '('); Assert.AreEqual("", word); Assert.AreEqual(-1, reader.Peek()); Assert.AreEqual(0, reader.Index); } //--------------------------------------------------------------------- [Test] public void ReadWord_Whitespace() { StringReader reader = new StringReader(" \t "); string word = PartialThinning.ReadWord(reader, '('); Assert.AreEqual("", word); Assert.AreEqual(' ', reader.Peek()); Assert.AreEqual(0, reader.Index); } //--------------------------------------------------------------------- [Test] public void ReadWord_Age() { StringReader reader = new StringReader("150"); string word = PartialThinning.ReadWord(reader, '('); Assert.AreEqual("150", word); Assert.AreEqual(-1, reader.Peek()); Assert.AreEqual(3, reader.Index); } //--------------------------------------------------------------------- [Test] public void ReadWord_AgeWhiteSpace() { StringReader reader = new StringReader("70 "); string word = PartialThinning.ReadWord(reader, '('); Assert.AreEqual("70", word); Assert.AreEqual(' ', reader.Peek()); Assert.AreEqual(2, reader.Index); } //--------------------------------------------------------------------- [Test] public void ReadWord_AgeLeftParen() { StringReader reader = new StringReader("200(75%)"); string word = PartialThinning.ReadWord(reader, '('); Assert.AreEqual("200", word); Assert.AreEqual('(', reader.Peek()); Assert.AreEqual(3, reader.Index); } //--------------------------------------------------------------------- [Test] public void ReadWord_Range() { StringReader reader = new StringReader("40-110"); string word = PartialThinning.ReadWord(reader, '('); Assert.AreEqual("40-110", word); Assert.AreEqual(-1, reader.Peek()); Assert.AreEqual(6, reader.Index); } //--------------------------------------------------------------------- [Test] public void ReadWord_RangeWhitespace() { StringReader reader = new StringReader("1-35\t"); string word = PartialThinning.ReadWord(reader, '('); Assert.AreEqual("1-35", word); Assert.AreEqual('\t', reader.Peek()); Assert.AreEqual(4, reader.Index); } //--------------------------------------------------------------------- [Test] public void ReadWord_RangeLeftParen() { StringReader reader = new StringReader("55-90( 10%)\t"); string word = PartialThinning.ReadWord(reader, '('); Assert.AreEqual("55-90", word); Assert.AreEqual('(', reader.Peek()); Assert.AreEqual(5, reader.Index); } //--------------------------------------------------------------------- [Test] public void ReadWord_PercentageRightParen() { StringReader reader = new StringReader("10.5%)\t"); string word = PartialThinning.ReadWord(reader, ')'); Assert.AreEqual("10.5%", word); Assert.AreEqual(')', reader.Peek()); Assert.AreEqual(5, reader.Index); } //--------------------------------------------------------------------- [Test] public void ReadWord_RightParen() { StringReader reader = new StringReader(")"); string word = PartialThinning.ReadWord(reader, ')'); Assert.AreEqual("", word); Assert.AreEqual(')', reader.Peek()); Assert.AreEqual(0, reader.Index); } } }
// 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.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace System.Diagnostics { // Overview // -------- // We have a few constraints we're working under here: // - waitpid is used on Unix to get the exit status (including exit code) of a child process, but the first call // to it after the child has completed will reap the child removing the chance of subsequent calls getting status. // - The Process design allows for multiple indendent Process objects to be handed out, and each of those // objects may be used concurrently with each other, even if they refer to the same underlying process. // Same with ProcessWaitHandle objects. This is based on the Windows design where anyone with a handle to the // process can retrieve completion information about that process. // - There is no good Unix equivalent to a process handle nor to being able to asynchronously be notified // of a process' exit (without more intrusive mechanisms like ptrace), which means such support // needs to be layered on top of waitpid. // // As a result, we have the following scheme: // - We maintain a static/shared table that maps process ID to ProcessWaitState objects. // Access to this table requires taking a global lock, so we try to minimize the number of // times we need to access the table, primarily just the first time a Process object needs // access to process exit/wait information and subsequently when that Process object gets GC'd. // - Each process holds a ProcessWaitState.Holder object; when that object is constructed, // it ensures there's an appropriate entry in the mapping table and increments that entry's ref count. // - When a Process object is dropped and its ProcessWaitState.Holder is finalized, it'll // decrement the ref count, and when no more process objects exist for a particular process ID, // that entry in the table will be cleaned up. // - This approach effectively allows for multiple independent Process objects for the same process ID to all // share the same ProcessWaitState. And since they are sharing the same wait state object, // the wait state object uses its own lock to protect the per-process state. This includes // caching exit / exit code / exit time information so that a Process object for a process that's already // had waitpid called for it can get at its exit information. // // A negative ramification of this is that if a process exits, but there are outstanding wait handles // handed out (and rooted, so they can't be GC'd), and then a new process is created and the pid is recycled, // new calls to get that process's wait state will get the old processe's wait state. However, pid recycling // will be a more general issue, since pids are the only identifier we have to a process, so if a Process // object is created for a particular pid, then that process goes away and a new one comes in with the same pid, // our Process object will silently switch to referring to the new pid. Unix systems typically have a simple // policy for pid recycling, which is that they start at a low value, increment up to a system maximum (e.g. // 32768), and then wrap around and start reusing value that aren't currently in use. On Linux, // proc/sys/kernel/pid_max defines the max pid value. Given the conditions that would be required for this // to happen, it's possible but unlikely. /// <summary>Exit information and waiting capabilities for a process.</summary> internal sealed class ProcessWaitState : IDisposable { /// <summary> /// Finalizable holder for a process wait state. Instantiating one /// will ensure that a wait state object exists for a process, will /// grab it, and will increment its ref count. Dropping or disposing /// one will decrement the ref count and clean up after it if the ref /// count hits zero. /// </summary> internal sealed class Holder : IDisposable { internal ProcessWaitState _state; internal Holder(int processId) { _state = ProcessWaitState.AddRef(processId); } ~Holder() { if (_state != null) { _state.ReleaseRef(); } } public void Dispose() { if (_state != null) { _state.ReleaseRef(); _state = null; GC.SuppressFinalize(this); } } } /// <summary> /// Global table that maps process IDs to the associated shared wait state information. /// </summary> private static readonly Dictionary<int, ProcessWaitState> s_processWaitStates = new Dictionary<int, ProcessWaitState>(); /// <summary> /// Ensures that the mapping table contains an entry for the process ID, /// increments its ref count, and returns it. /// </summary> /// <param name="processId">The process ID for which we need wait state.</param> /// <returns>The wait state object.</returns> internal static ProcessWaitState AddRef(int processId) { lock (s_processWaitStates) { ProcessWaitState pws; if (!s_processWaitStates.TryGetValue(processId, out pws)) { pws = new ProcessWaitState(processId); s_processWaitStates.Add(processId, pws); } pws._outstandingRefCount++; return pws; } } /// <summary> /// Decrements the ref count on the wait state object, and if it's the last one, /// removes it from the table. /// </summary> internal void ReleaseRef() { lock (ProcessWaitState.s_processWaitStates) { ProcessWaitState pws; bool foundState = ProcessWaitState.s_processWaitStates.TryGetValue(_processId, out pws); Debug.Assert(foundState); if (foundState) { --pws._outstandingRefCount; if (pws._outstandingRefCount == 0) { ProcessWaitState.s_processWaitStates.Remove(_processId); pws.Dispose(); } } } } /// <summary> /// Synchroniation object used to protect all instance state. Any number of /// Process and ProcessWaitHandle objects may be using a ProcessWaitState /// instance concurrently. /// </summary> private readonly object _gate = new object(); /// <summary>ID of the associated process.</summary> private readonly int _processId; /// <summary>If a wait operation is in progress, the Task that represents it; otherwise, null.</summary> private Task _waitInProgress; /// <summary>The number of alive users of this object.</summary> private int _outstandingRefCount; /// <summary>Whether the associated process exited.</summary> private bool _exited; /// <summary>If the process exited, it's exit code, or null if we were unable to determine one.</summary> private int? _exitCode; /// <summary> /// The approximate time the process exited. We do not have the ability to know exact time a process /// exited, so we approximate it by storing the time that we discovered it exited. /// </summary> private DateTime _exitTime; /// <summary>A lazily-initialized event set when the process exits.</summary> private ManualResetEvent _exitedEvent; /// <summary>Initialize the wait state object.</summary> /// <param name="processId">The associated process' ID.</param> private ProcessWaitState(int processId) { Debug.Assert(processId >= 0); _processId = processId; } /// <summary>Releases managed resources used by the ProcessWaitState.</summary> public void Dispose() { Debug.Assert(!Monitor.IsEntered(_gate)); lock (_gate) { if (_exitedEvent != null) { _exitedEvent.Dispose(); _exitedEvent = null; } } } /// <summary>Notes that the process has exited.</summary> private void SetExited() { Debug.Assert(Monitor.IsEntered(_gate)); _exited = true; _exitTime = DateTime.Now; if (_exitedEvent != null) { _exitedEvent.Set(); } } /// <summary>Ensures an exited event has been initialized and returns it.</summary> /// <returns></returns> internal ManualResetEvent EnsureExitedEvent() { Debug.Assert(!Monitor.IsEntered(_gate)); lock (_gate) { // If we already have an initialized event, just return it. if (_exitedEvent == null) { // If we don't, create one, and if the process hasn't yet exited, // make sure we have a task that's actively monitoring the completion state. _exitedEvent = new ManualResetEvent(initialState: _exited); if (!_exited) { // If we haven't exited, we need to spin up an asynchronous operation that // will completed the exitedEvent when the other process exits. If there's already // another operation underway, then we'll just tack ours onto the end of it. _waitInProgress = _waitInProgress == null ? WaitForExitAsync() : _waitInProgress.ContinueWith((_, state) => ((ProcessWaitState)state).WaitForExitAsync(), this, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default).Unwrap(); } } return _exitedEvent; } } internal DateTime ExitTime { get { lock (_gate) { Debug.Assert(_exited); return _exitTime; } } } internal bool HasExited { get { int? ignored; return GetExited(out ignored); } } internal bool GetExited(out int? exitCode) { lock (_gate) { // Have we already exited? If so, return the cached results. if (_exited) { exitCode = _exitCode; return true; } // Is another wait operation in progress? If so, then we haven't exited, // and that task owns the right to call CheckForExit. if (_waitInProgress != null) { exitCode = null; return false; } // We don't know if we've exited, but no one else is currently // checking, so check. CheckForExit(); // We now have an up-to-date snapshot for whether we've exited, // and if we have, what the exit code is (if we were able to find out). exitCode = _exitCode; return _exited; } } private void CheckForExit(bool blockingAllowed = false) { Debug.Assert(Monitor.IsEntered(_gate)); Debug.Assert(!blockingAllowed); // see "PERF NOTE" comment in WaitForExit while (true) // in case of EINTR during system call { // Try to get the state of the (child) process int status; int waitResult = Interop.libc.waitpid(_processId, out status, blockingAllowed ? Interop.libc.WaitPidOptions.None : Interop.libc.WaitPidOptions.WNOHANG); if (waitResult == _processId) { // Process has exited if (Interop.libc.WIFEXITED(status)) { _exitCode = Interop.libc.WEXITSTATUS(status); } else if (Interop.libc.WIFSIGNALED(status)) { const int ExitCodeSignalOffset = 128; _exitCode = ExitCodeSignalOffset + Interop.libc.WTERMSIG(status); } SetExited(); return; } else if (waitResult == 0) { // Process is still running return; } else if (waitResult == -1) { // Something went wrong, e.g. it's not a child process, // or waitpid was already called for this child, or // that the call was interrupted by a signal. int errno = Marshal.GetLastWin32Error(); if (errno == Interop.Errors.EINTR) { // waitpid was interrupted. Try again. continue; } else if (errno == Interop.Errors.ECHILD) { // waitpid was used with a non-child process. We won't be // able to get an exit code, but we'll at least be able // to determine if the process is still running (assuming // there's not a race on its id). int killResult = Interop.libc.kill(_processId, 0); // 0 means don't send a signal if (killResult == 0) { // Process is still running return; } else // error from kill { errno = Marshal.GetLastWin32Error(); if (errno == Interop.Errors.ESRCH) { // Couldn't find the process; assume it's exited SetExited(); return; } else if (errno == Interop.Errors.EPERM) { // Don't have permissions to the process; assume it's alive return; } else Debug.Fail("Unexpected errno value from kill"); } } else Debug.Fail("Unexpected errno value from waitpid"); } else Debug.Fail("Unexpected process ID from waitpid."); SetExited(); return; } } /// <summary>Waits for the associated process to exit.</summary> /// <param name="millisecondsTimeout">The amount of time to wait, or -1 to wait indefinitely.</param> /// <returns>true if the process exited; false if the timeout occurred.</returns> internal bool WaitForExit(int millisecondsTimeout) { Debug.Assert(!Monitor.IsEntered(_gate)); // Track the time the we start waiting. long startTime = GetTimestamp(); // Polling loop while (true) { bool createdTask = false; CancellationTokenSource cts = null; Task waitTask; // We're in a polling loop... determine how much time remains int remainingTimeout = millisecondsTimeout == Timeout.Infinite ? Timeout.Infinite : (int)Math.Max(millisecondsTimeout - (GetTimestamp() - startTime), 0); lock (_gate) { // If we already know that the process exited, we're done. if (_exited) { return true; } // If a timeout of 0 was supplied, then we simply need to poll // to see if the process has already exited. if (remainingTimeout == 0) { // If there's currently a wait-in-progress, then we know the other process // hasn't exited (barring races and the polling interval). if (_waitInProgress != null) { return false; } // No one else is checking for the process' exit... so check. // We're currently holding the _gate lock, so we don't want to // allow CheckForExit to block indefinitely. CheckForExit(); return _exited; } // The process has not yet exited (or at least we don't know it yet) // so we need to wait for it to exit, outside of the lock. // If there's already a wait in progress, we'll do so later // by waiting on that existing task. Otherwise, we'll spin up // such a task. if (_waitInProgress != null) { waitTask = _waitInProgress; } else { createdTask = true; CancellationToken token = remainingTimeout == Timeout.Infinite ? CancellationToken.None : (cts = new CancellationTokenSource(remainingTimeout)).Token; waitTask = WaitForExitAsync(token); // PERF NOTE: // At the moment, we never call CheckForExit(true) (which in turn allows // waitpid to block until the child has completed) because we currently call it while // holdling the _gate lock. This is probably unnecessary in some situations, and in particular // here if remainingTimeout == Timeout.Infinite. In that case, we should be able to set // _waitInProgress to be a TaskCompletionSource task, and then below outside of the lock // we could do a CheckForExit(blockingAllowed:true) and complete the TaskCompletionSource // after that. We would just need to make sure that there's no risk of the other state // on this instance experiencing torn reads. } } // lock(_gate) if (createdTask) { // We created this task, and it'll get canceled automatically after our timeout. // This Wait should only wake up when either the process has exited or the timeout // has expired. Either way, we'll loop around again; if the process exited, that'll // be caught first thing in the loop where we check _exited, and if it didn't exit, // our remaining time will be zero, so we'll do a quick remaining check and bail. waitTask.Wait(); if (cts != null) { cts.Dispose(); } } else { // It's someone else's task. We'll wait for it to complete. This could complete // either because our remainingTimeout expired or because the task completed, // which could happen because the process exited or because whoever created // that task gave it a timeout. In any case, we'll loop around again, and the loop // will catch these cases, potentially issuing another wait to make up any // remaining time. waitTask.Wait(remainingTimeout); } } } /// <summary>Spawns an asynchronous polling loop for process completion.</summary> /// <param name="cancellationToken">A token to monitor to exit the polling loop.</param> /// <returns>The task representing the loop.</returns> private Task WaitForExitAsync(CancellationToken cancellationToken = default(CancellationToken)) { Debug.Assert(Monitor.IsEntered(_gate)); Debug.Assert(_waitInProgress == null); return _waitInProgress = Task.Run(async delegate // Task.Run used because of potential blocking in CheckForExit { try { // While we're not canceled while (!cancellationToken.IsCancellationRequested) { // Poll lock (_gate) { if (!_exited) { CheckForExit(); } if (_exited) // may have been updated by CheckForExit { return; } } // Wait try { const int PollingIntervalMs = 100; // arbitrary value chosen to balance delays with polling overhead await Task.Delay(PollingIntervalMs, cancellationToken); } catch (OperationCanceledException) { } } } finally { // Task is no longer active lock (_gate) { _waitInProgress = null; } } }); } /// <summary>Gets a current time stamp.</summary> private static long GetTimestamp() { return Stopwatch.GetTimestamp(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.IO; using System.Linq; using Xamarin.Forms.GoogleMaps.Internals; using Xamarin.Forms.GoogleMaps.Helpers; using System.Threading.Tasks; using Xamarin.Forms.GoogleMaps.Extensions; using System.ComponentModel; using System.Windows.Input; namespace Xamarin.Forms.GoogleMaps { public class Map : View, IEnumerable<Pin> { public static readonly BindableProperty ItemsSourceProperty = BindableProperty.Create(nameof(IEnumerable), typeof(IEnumerable), typeof(Map), default(IEnumerable), propertyChanged: (b, o, n) => ((Map)b).OnItemsSourcePropertyChanged((IEnumerable)o, (IEnumerable)n)); public static readonly BindableProperty ItemTemplateProperty = BindableProperty.Create(nameof(ItemTemplate), typeof(DataTemplate), typeof(Map), default(DataTemplate), propertyChanged: (b, o, n) => ((Map)b).OnItemTemplatePropertyChanged((DataTemplate)o, (DataTemplate)n)); public static readonly BindableProperty ItemTemplateSelectorProperty = BindableProperty.Create(nameof(ItemTemplateSelector), typeof(DataTemplateSelector), typeof(Map), default(DataTemplateSelector), propertyChanged: (b, o, n) => ((Map)b).OnItemTemplateSelectorPropertyChanged()); public static readonly BindableProperty MapTypeProperty = BindableProperty.Create(nameof(MapType), typeof(MapType), typeof(Map), default(MapType)); #pragma warning disable CS0618 // Type or member is obsolete public static readonly BindableProperty IsShowingUserProperty = BindableProperty.Create(nameof(IsShowingUser), typeof(bool), typeof(Map), default(bool)); public static readonly BindableProperty MyLocationEnabledProperty = BindableProperty.Create(nameof(MyLocationEnabled), typeof(bool), typeof(Map), default(bool)); public static readonly BindableProperty HasScrollEnabledProperty = BindableProperty.Create(nameof(HasScrollEnabled), typeof(bool), typeof(Map), true); public static readonly BindableProperty HasZoomEnabledProperty = BindableProperty.Create(nameof(HasZoomEnabled), typeof(bool), typeof(Map), true); public static readonly BindableProperty HasRotationEnabledProperty = BindableProperty.Create(nameof(HasRotationEnabled), typeof(bool), typeof(Map), true); #pragma warning restore CS0618 // Type or member is obsolete public static readonly BindableProperty SelectedPinProperty = BindableProperty.Create(nameof(SelectedPin), typeof(Pin), typeof(Map), default(Pin), defaultBindingMode: BindingMode.TwoWay); public static readonly BindableProperty IsTrafficEnabledProperty = BindableProperty.Create(nameof(IsTrafficEnabled), typeof(bool), typeof(Map), false); public static readonly BindableProperty IndoorEnabledProperty = BindableProperty.Create(nameof(IsIndoorEnabled), typeof(bool), typeof(Map), true); public static readonly BindableProperty InitialCameraUpdateProperty = BindableProperty.Create( nameof(InitialCameraUpdate), typeof(CameraUpdate), typeof(Map), CameraUpdateFactory.NewPositionZoom(new Position(41.89, 12.49), 10), // center on Rome by default propertyChanged: (bindable, oldValue, newValue) => { ((Map)bindable)._useMoveToRegisonAsInitialBounds = false; }); public static readonly BindableProperty PaddingProperty = BindableProperty.Create(nameof(PaddingProperty), typeof(Thickness), typeof(Map), default(Thickness)); bool _useMoveToRegisonAsInitialBounds = true; public static readonly BindableProperty CameraPositionProperty = BindableProperty.Create( nameof(CameraPosition), typeof(CameraPosition), typeof(Map), defaultValueCreator: (bindable) => new CameraPosition(((Map)bindable).InitialCameraUpdate.Position, 10), defaultBindingMode: BindingMode.TwoWay); public static readonly BindableProperty MapStyleProperty = BindableProperty.Create(nameof(MapStyle), typeof(MapStyle), typeof(Map), null); readonly ObservableCollection<Pin> _pins = new ObservableCollection<Pin>(); readonly ObservableCollection<Polyline> _polylines = new ObservableCollection<Polyline>(); readonly ObservableCollection<Polygon> _polygons = new ObservableCollection<Polygon>(); readonly ObservableCollection<Circle> _circles = new ObservableCollection<Circle>(); readonly ObservableCollection<TileLayer> _tileLayers = new ObservableCollection<TileLayer>(); readonly ObservableCollection<GroundOverlay> _groundOverlays = new ObservableCollection<GroundOverlay>(); public event EventHandler<PinClickedEventArgs> PinClicked; public event EventHandler<SelectedPinChangedEventArgs> SelectedPinChanged; public event EventHandler<InfoWindowClickedEventArgs> InfoWindowClicked; public event EventHandler<InfoWindowLongClickedEventArgs> InfoWindowLongClicked; public event EventHandler<PinDragEventArgs> PinDragStart; public event EventHandler<PinDragEventArgs> PinDragEnd; public event EventHandler<PinDragEventArgs> PinDragging; public event EventHandler<MapClickedEventArgs> MapClicked; public event EventHandler<MapLongClickedEventArgs> MapLongClicked; public event EventHandler<MyLocationButtonClickedEventArgs> MyLocationButtonClicked; [Obsolete("Please use Map.CameraIdled instead of this")] public event EventHandler<CameraChangedEventArgs> CameraChanged; public event EventHandler<CameraMoveStartedEventArgs> CameraMoveStarted; public event EventHandler<CameraMovingEventArgs> CameraMoving; public event EventHandler<CameraIdledEventArgs> CameraIdled; internal Action<MoveToRegionMessage> OnMoveToRegion { get; set; } internal Action<CameraUpdateMessage> OnMoveCamera { get; set; } internal Action<CameraUpdateMessage> OnAnimateCamera { get; set; } internal Action<TakeSnapshotMessage> OnSnapshot{ get; set; } MapSpan _visibleRegion; MapRegion _region; //// Simone Marra //public static Position _TopLeft = new Position(); //public static Position _TopRight = new Position(); //public static Position _BottomLeft = new Position(); //public static Position _BottomRight = new Position(); //// End Simone Marra public Map() { VerticalOptions = HorizontalOptions = LayoutOptions.FillAndExpand; _pins.CollectionChanged += PinsOnCollectionChanged; _polylines.CollectionChanged += PolylinesOnCollectionChanged; _polygons.CollectionChanged += PolygonsOnCollectionChanged; _circles.CollectionChanged += CirclesOnCollectionChanged; _tileLayers.CollectionChanged += TileLayersOnCollectionChanged; _groundOverlays.CollectionChanged += GroundOverlays_CollectionChanged; } [Obsolete("Please use Map.UiSettings.ScrollGesturesEnabled instead of this")] public bool HasScrollEnabled { get { return (bool)GetValue(HasScrollEnabledProperty); } set { SetValue(HasScrollEnabledProperty, value); } } [Obsolete("Please use Map.UiSettings.ZoomGesturesEnabled and ZoomControlsEnabled instead of this")] public bool HasZoomEnabled { get { return (bool)GetValue(HasZoomEnabledProperty); } set { SetValue(HasZoomEnabledProperty, value); } } [Obsolete("Please use Map.UiSettings.RotateGesturesEnabled instead of this")] public bool HasRotationEnabled { get { return (bool)GetValue(HasRotationEnabledProperty); } set { SetValue(HasRotationEnabledProperty, value); } } public bool IsTrafficEnabled { get { return (bool)GetValue(IsTrafficEnabledProperty); } set { SetValue(IsTrafficEnabledProperty, value); } } public bool IsIndoorEnabled { get { return (bool) GetValue(IndoorEnabledProperty); } set { SetValue(IndoorEnabledProperty, value);} } [Obsolete("Please use Map.MyLocationEnabled and Map.UiSettings.MyLocationButtonEnabled instead of this")] public bool IsShowingUser { get { return (bool)GetValue(IsShowingUserProperty); } set { SetValue(IsShowingUserProperty, value); } } public bool MyLocationEnabled { get { return (bool)GetValue(MyLocationEnabledProperty); } set { SetValue(MyLocationEnabledProperty, value); } } public MapType MapType { get { return (MapType)GetValue(MapTypeProperty); } set { SetValue(MapTypeProperty, value); } } public Pin SelectedPin { get { return (Pin)GetValue(SelectedPinProperty); } set { SetValue(SelectedPinProperty, value); } } [TypeConverter(typeof(CameraUpdateConverter))] public CameraUpdate InitialCameraUpdate { get { return (CameraUpdate)GetValue(InitialCameraUpdateProperty); } set { SetValue(InitialCameraUpdateProperty, value); } } public CameraPosition CameraPosition { get { return (CameraPosition)GetValue(CameraPositionProperty); } internal set { SetValue(CameraPositionProperty, value); } } public Thickness Padding { get { return (Thickness)GetValue(PaddingProperty); } set { SetValue(PaddingProperty, value); } } public MapStyle MapStyle { get { return (MapStyle)GetValue(MapStyleProperty); } set { SetValue(MapStyleProperty, value); } } public IEnumerable ItemsSource { get => (IEnumerable)GetValue(ItemsSourceProperty); set => SetValue(ItemsSourceProperty, value); } public DataTemplate ItemTemplate { get => (DataTemplate)GetValue(ItemTemplateProperty); set => SetValue(ItemTemplateProperty, value); } public DataTemplateSelector ItemTemplateSelector { get { return (DataTemplateSelector)GetValue(ItemTemplateSelectorProperty); } set { SetValue(ItemTemplateSelectorProperty, value); } } public IList<Pin> Pins { get { return _pins; } } public IList<Polyline> Polylines { get { return _polylines; } } public IList<Polygon> Polygons { get { return _polygons; } } public IList<Circle> Circles { get { return _circles; } } public IList<TileLayer> TileLayers { get { return _tileLayers; } } public IList<GroundOverlay> GroundOverlays { get { return _groundOverlays; } } [Obsolete("Please use Map.Region instead of this")] public MapSpan VisibleRegion { get { return _visibleRegion; } internal set { if (_visibleRegion == value) return; if (value == null) throw new ArgumentNullException(nameof(value)); OnPropertyChanging(); _visibleRegion = value; OnPropertyChanged(); } } public MapRegion Region { get { return _region; } internal set { if (_region == value) return; if (value == null) throw new ArgumentNullException(nameof(value)); OnPropertyChanging(); _region = value; OnPropertyChanged(); } } public UiSettings UiSettings { get; } = new UiSettings(); IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public IEnumerator<Pin> GetEnumerator() { return _pins.GetEnumerator(); } public void MoveToRegion(MapSpan mapSpan, bool animate = true) { if (mapSpan == null) throw new ArgumentNullException(nameof(mapSpan)); if (_useMoveToRegisonAsInitialBounds) { InitialCameraUpdate = CameraUpdateFactory.NewBounds(mapSpan.ToBounds(), 0); _useMoveToRegisonAsInitialBounds = false; } SendMoveToRegion(new MoveToRegionMessage(mapSpan, animate)); } public Task<AnimationStatus> MoveCamera(CameraUpdate cameraUpdate) { var comp = new TaskCompletionSource<AnimationStatus>(); SendMoveCamera(new CameraUpdateMessage(cameraUpdate, null, new DelegateAnimationCallback( () => comp.SetResult(AnimationStatus.Finished), () => comp.SetResult(AnimationStatus.Canceled)))); return comp.Task; } public Task<AnimationStatus> AnimateCamera(CameraUpdate cameraUpdate, TimeSpan? duration = null) { var comp = new TaskCompletionSource<AnimationStatus>(); SendAnimateCamera(new CameraUpdateMessage(cameraUpdate, duration, new DelegateAnimationCallback( () => comp.SetResult(AnimationStatus.Finished), () => comp.SetResult(AnimationStatus.Canceled)))); return comp.Task; } public Task<Stream> TakeSnapshot() { var comp = new TaskCompletionSource<Stream>(); SendTakeSnapshot(new TakeSnapshotMessage(image => comp.SetResult(image))); return comp.Task; } void PinsOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.NewItems != null && e.NewItems.Cast<Pin>().Any(pin => pin.Label == null)) throw new ArgumentException("Pin must have a Label to be added to a map"); } void PolylinesOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.NewItems != null && e.NewItems.Cast<Polyline>().Any(polyline => polyline.Positions.Count < 2)) throw new ArgumentException("Polyline must have a 2 positions to be added to a map"); } void PolygonsOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.NewItems != null && e.NewItems.Cast<Polygon>().Any(polygon => polygon.Positions.Count < 3)) throw new ArgumentException("Polygon must have a 3 positions to be added to a map"); } void CirclesOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.NewItems != null && e.NewItems.Cast<Circle>().Any(circle => ( circle?.Center == null || circle?.Radius == null || circle.Radius.Meters <= 0f))) throw new ArgumentException("Circle must have a center and radius"); } void TileLayersOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { //if (e.NewItems != null && e.NewItems.Cast<ITileLayer>().Any(tileLayer => (circle.Center == null || circle.Radius == null || circle.Radius.Meters <= 0f))) // throw new ArgumentException("Circle must have a center and radius"); } void GroundOverlays_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { } internal void SendSelectedPinChanged(Pin selectedPin) { SelectedPinChanged?.Invoke(this, new SelectedPinChangedEventArgs(selectedPin)); } void OnItemTemplateSelectorPropertyChanged() { _pins.Clear(); CreatePinItems(); } internal bool SendPinClicked(Pin pin) { var args = new PinClickedEventArgs(pin); PinClicked?.Invoke(this, args); return args.Handled; } internal void SendInfoWindowClicked(Pin pin) { var args = new InfoWindowClickedEventArgs(pin); InfoWindowClicked?.Invoke(this, args); } internal void SendInfoWindowLongClicked(Pin pin) { var args = new InfoWindowLongClickedEventArgs(pin); InfoWindowLongClicked?.Invoke(this, args); } internal void SendPinDragStart(Pin pin) { PinDragStart?.Invoke(this, new PinDragEventArgs(pin)); } internal void SendPinDragEnd(Pin pin) { PinDragEnd?.Invoke(this, new PinDragEventArgs(pin)); } internal void SendPinDragging(Pin pin) { PinDragging?.Invoke(this, new PinDragEventArgs(pin)); } internal void SendMapClicked(Position point) { MapClicked?.Invoke(this, new MapClickedEventArgs(point)); } internal void SendMapLongClicked(Position point) { MapLongClicked?.Invoke(this, new MapLongClickedEventArgs(point)); } internal bool SendMyLocationClicked() { var args = new MyLocationButtonClickedEventArgs(); MyLocationButtonClicked?.Invoke(this, args); return args.Handled; } internal void SendCameraChanged(CameraPosition position) { CameraChanged?.Invoke(this, new CameraChangedEventArgs(position)); } internal void SendCameraMoveStarted(bool isGesture) { CameraMoveStarted?.Invoke(this, new CameraMoveStartedEventArgs(isGesture)); } internal void SendCameraMoving(CameraPosition position) { CameraMoving?.Invoke(this, new CameraMovingEventArgs(position)); } internal void SendCameraIdled(CameraPosition position) { CameraIdled?.Invoke(this, new CameraIdledEventArgs(position)); } private void SendMoveToRegion(MoveToRegionMessage message) { OnMoveToRegion?.Invoke(message); } void SendMoveCamera(CameraUpdateMessage message) { OnMoveCamera?.Invoke(message); } void SendAnimateCamera(CameraUpdateMessage message) { OnAnimateCamera?.Invoke(message); } void SendTakeSnapshot(TakeSnapshotMessage message) { OnSnapshot?.Invoke(message); } void OnItemsSourcePropertyChanged(IEnumerable oldItemsSource, IEnumerable newItemsSource) { if (oldItemsSource is INotifyCollectionChanged ncc) { ncc.CollectionChanged -= OnItemsSourceCollectionChanged; } if (newItemsSource is INotifyCollectionChanged ncc1) { ncc1.CollectionChanged += OnItemsSourceCollectionChanged; } _pins.Clear(); CreatePinItems(); } void OnItemTemplatePropertyChanged(DataTemplate oldItemTemplate, DataTemplate newItemTemplate) { if (newItemTemplate is DataTemplateSelector) { throw new NotSupportedException($"You are using an instance of {nameof(DataTemplateSelector)} to set the {nameof(Map)}.{ItemTemplateProperty.PropertyName} property. Use an instance of a {nameof(DataTemplate)} property instead to set an item template."); } _pins.Clear(); CreatePinItems(); } void OnItemsSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: if (e.NewStartingIndex == -1) goto case NotifyCollectionChangedAction.Reset; foreach (object item in e.NewItems) CreatePin(item); break; case NotifyCollectionChangedAction.Move: if (e.OldStartingIndex == -1 || e.NewStartingIndex == -1) goto case NotifyCollectionChangedAction.Reset; // Not tracking order break; case NotifyCollectionChangedAction.Remove: if (e.OldStartingIndex == -1) goto case NotifyCollectionChangedAction.Reset; foreach (object item in e.OldItems) RemovePin(item); break; case NotifyCollectionChangedAction.Replace: if (e.OldStartingIndex == -1) goto case NotifyCollectionChangedAction.Reset; foreach (object item in e.OldItems) RemovePin(item); foreach (object item in e.NewItems) CreatePin(item); break; case NotifyCollectionChangedAction.Reset: _pins.Clear(); break; } } void CreatePinItems() { if (ItemsSource == null || (ItemTemplate == null && ItemTemplateSelector == null)) { return; } foreach (object item in ItemsSource) { CreatePin(item); } } void CreatePin(object newItem) { DataTemplate itemTemplate = ItemTemplate; if (itemTemplate == null) itemTemplate = ItemTemplateSelector?.SelectTemplate(newItem, this); if (itemTemplate == null) return; var pin = (Pin)itemTemplate.CreateContent(); pin.BindingContext = newItem; _pins.Add(pin); } void RemovePin(object itemToRemove) { Pin pinToRemove = _pins.FirstOrDefault(pin => pin.BindingContext?.Equals(itemToRemove) == true); if (pinToRemove != null) { _pins.Remove(pinToRemove); } } } }
/************************************************************************* This file is a part of ALGLIB project. >>> SOURCE LICENSE >>> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation (www.fsf.org); either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. A copy of the GNU General Public License is available at http://www.fsf.org/licensing/licenses >>> END OF LICENSE >>> *************************************************************************/ using System; namespace FuncLib.Mathematics.LinearAlgebra.AlgLib { internal class safesolve { /************************************************************************* Real implementation of CMatrixScaledTRSafeSolve -- ALGLIB routine -- 21.01.2010 Bochkanov Sergey *************************************************************************/ public static bool rmatrixscaledtrsafesolve(ref double[,] a, double sa, int n, ref double[] x, bool isupper, int trans, bool isunit, double maxgrowth) { bool result = new bool(); double lnmax = 0; double nrmb = 0; double nrmx = 0; int i = 0; AP.Complex alpha = 0; AP.Complex beta = 0; double vr = 0; AP.Complex cx = 0; double[] tmp = new double[0]; int i_ = 0; System.Diagnostics.Debug.Assert(n > 0, "RMatrixTRSafeSolve: incorrect N!"); System.Diagnostics.Debug.Assert(trans == 0 | trans == 1, "RMatrixTRSafeSolve: incorrect Trans!"); result = true; lnmax = Math.Log(AP.Math.MaxRealNumber); // // Quick return if possible // if (n <= 0) { return result; } // // Load norms: right part and X // nrmb = 0; for (i = 0; i <= n - 1; i++) { nrmb = Math.Max(nrmb, Math.Abs(x[i])); } nrmx = 0; // // Solve // tmp = new double[n]; result = true; if (isupper & trans == 0) { // // U*x = b // for (i = n - 1; i >= 0; i--) { // // Task is reduced to alpha*x[i] = beta // if (isunit) { alpha = sa; } else { alpha = a[i, i] * sa; } if (i < n - 1) { for (i_ = i + 1; i_ <= n - 1; i_++) { tmp[i_] = sa * a[i, i_]; } vr = 0.0; for (i_ = i + 1; i_ <= n - 1; i_++) { vr += tmp[i_] * x[i_]; } beta = x[i] - vr; } else { beta = x[i]; } // // solve alpha*x[i] = beta // result = cbasicsolveandupdate(alpha, beta, lnmax, nrmb, maxgrowth, ref nrmx, ref cx); if (!result) { return result; } x[i] = cx.x; } return result; } if (!isupper & trans == 0) { // // L*x = b // for (i = 0; i <= n - 1; i++) { // // Task is reduced to alpha*x[i] = beta // if (isunit) { alpha = sa; } else { alpha = a[i, i] * sa; } if (i > 0) { for (i_ = 0; i_ <= i - 1; i_++) { tmp[i_] = sa * a[i, i_]; } vr = 0.0; for (i_ = 0; i_ <= i - 1; i_++) { vr += tmp[i_] * x[i_]; } beta = x[i] - vr; } else { beta = x[i]; } // // solve alpha*x[i] = beta // result = cbasicsolveandupdate(alpha, beta, lnmax, nrmb, maxgrowth, ref nrmx, ref cx); if (!result) { return result; } x[i] = cx.x; } return result; } if (isupper & trans == 1) { // // U^T*x = b // for (i = 0; i <= n - 1; i++) { // // Task is reduced to alpha*x[i] = beta // if (isunit) { alpha = sa; } else { alpha = a[i, i] * sa; } beta = x[i]; // // solve alpha*x[i] = beta // result = cbasicsolveandupdate(alpha, beta, lnmax, nrmb, maxgrowth, ref nrmx, ref cx); if (!result) { return result; } x[i] = cx.x; // // update the rest of right part // if (i < n - 1) { vr = cx.x; for (i_ = i + 1; i_ <= n - 1; i_++) { tmp[i_] = sa * a[i, i_]; } for (i_ = i + 1; i_ <= n - 1; i_++) { x[i_] = x[i_] - vr * tmp[i_]; } } } return result; } if (!isupper & trans == 1) { // // L^T*x = b // for (i = n - 1; i >= 0; i--) { // // Task is reduced to alpha*x[i] = beta // if (isunit) { alpha = sa; } else { alpha = a[i, i] * sa; } beta = x[i]; // // solve alpha*x[i] = beta // result = cbasicsolveandupdate(alpha, beta, lnmax, nrmb, maxgrowth, ref nrmx, ref cx); if (!result) { return result; } x[i] = cx.x; // // update the rest of right part // if (i > 0) { vr = cx.x; for (i_ = 0; i_ <= i - 1; i_++) { tmp[i_] = sa * a[i, i_]; } for (i_ = 0; i_ <= i - 1; i_++) { x[i_] = x[i_] - vr * tmp[i_]; } } } return result; } result = false; return result; } /************************************************************************* Internal subroutine for safe solution of SA*op(A)=b where A is NxN upper/lower triangular/unitriangular matrix, op(A) is either identity transform, transposition or Hermitian transposition, SA is a scaling factor such that max(|SA*A[i,j]|) is close to 1.0 in magnutude. This subroutine limits relative growth of solution (in inf-norm) by MaxGrowth, returning False if growth exceeds MaxGrowth. Degenerate or near-degenerate matrices are handled correctly (False is returned) as long as MaxGrowth is significantly less than MaxRealNumber/norm(b). -- ALGLIB routine -- 21.01.2010 Bochkanov Sergey *************************************************************************/ public static bool cmatrixscaledtrsafesolve(ref AP.Complex[,] a, double sa, int n, ref AP.Complex[] x, bool isupper, int trans, bool isunit, double maxgrowth) { bool result = new bool(); double lnmax = 0; double nrmb = 0; double nrmx = 0; int i = 0; AP.Complex alpha = 0; AP.Complex beta = 0; AP.Complex vc = 0; AP.Complex[] tmp = new AP.Complex[0]; int i_ = 0; System.Diagnostics.Debug.Assert(n > 0, "CMatrixTRSafeSolve: incorrect N!"); System.Diagnostics.Debug.Assert(trans == 0 | trans == 1 | trans == 2, "CMatrixTRSafeSolve: incorrect Trans!"); result = true; lnmax = Math.Log(AP.Math.MaxRealNumber); // // Quick return if possible // if (n <= 0) { return result; } // // Load norms: right part and X // nrmb = 0; for (i = 0; i <= n - 1; i++) { nrmb = Math.Max(nrmb, AP.Math.AbsComplex(x[i])); } nrmx = 0; // // Solve // tmp = new AP.Complex[n]; result = true; if (isupper & trans == 0) { // // U*x = b // for (i = n - 1; i >= 0; i--) { // // Task is reduced to alpha*x[i] = beta // if (isunit) { alpha = sa; } else { alpha = a[i, i] * sa; } if (i < n - 1) { for (i_ = i + 1; i_ <= n - 1; i_++) { tmp[i_] = sa * a[i, i_]; } vc = 0.0; for (i_ = i + 1; i_ <= n - 1; i_++) { vc += tmp[i_] * x[i_]; } beta = x[i] - vc; } else { beta = x[i]; } // // solve alpha*x[i] = beta // result = cbasicsolveandupdate(alpha, beta, lnmax, nrmb, maxgrowth, ref nrmx, ref vc); if (!result) { return result; } x[i] = vc; } return result; } if (!isupper & trans == 0) { // // L*x = b // for (i = 0; i <= n - 1; i++) { // // Task is reduced to alpha*x[i] = beta // if (isunit) { alpha = sa; } else { alpha = a[i, i] * sa; } if (i > 0) { for (i_ = 0; i_ <= i - 1; i_++) { tmp[i_] = sa * a[i, i_]; } vc = 0.0; for (i_ = 0; i_ <= i - 1; i_++) { vc += tmp[i_] * x[i_]; } beta = x[i] - vc; } else { beta = x[i]; } // // solve alpha*x[i] = beta // result = cbasicsolveandupdate(alpha, beta, lnmax, nrmb, maxgrowth, ref nrmx, ref vc); if (!result) { return result; } x[i] = vc; } return result; } if (isupper & trans == 1) { // // U^T*x = b // for (i = 0; i <= n - 1; i++) { // // Task is reduced to alpha*x[i] = beta // if (isunit) { alpha = sa; } else { alpha = a[i, i] * sa; } beta = x[i]; // // solve alpha*x[i] = beta // result = cbasicsolveandupdate(alpha, beta, lnmax, nrmb, maxgrowth, ref nrmx, ref vc); if (!result) { return result; } x[i] = vc; // // update the rest of right part // if (i < n - 1) { for (i_ = i + 1; i_ <= n - 1; i_++) { tmp[i_] = sa * a[i, i_]; } for (i_ = i + 1; i_ <= n - 1; i_++) { x[i_] = x[i_] - vc * tmp[i_]; } } } return result; } if (!isupper & trans == 1) { // // L^T*x = b // for (i = n - 1; i >= 0; i--) { // // Task is reduced to alpha*x[i] = beta // if (isunit) { alpha = sa; } else { alpha = a[i, i] * sa; } beta = x[i]; // // solve alpha*x[i] = beta // result = cbasicsolveandupdate(alpha, beta, lnmax, nrmb, maxgrowth, ref nrmx, ref vc); if (!result) { return result; } x[i] = vc; // // update the rest of right part // if (i > 0) { for (i_ = 0; i_ <= i - 1; i_++) { tmp[i_] = sa * a[i, i_]; } for (i_ = 0; i_ <= i - 1; i_++) { x[i_] = x[i_] - vc * tmp[i_]; } } } return result; } if (isupper & trans == 2) { // // U^H*x = b // for (i = 0; i <= n - 1; i++) { // // Task is reduced to alpha*x[i] = beta // if (isunit) { alpha = sa; } else { alpha = AP.Math.Conj(a[i, i]) * sa; } beta = x[i]; // // solve alpha*x[i] = beta // result = cbasicsolveandupdate(alpha, beta, lnmax, nrmb, maxgrowth, ref nrmx, ref vc); if (!result) { return result; } x[i] = vc; // // update the rest of right part // if (i < n - 1) { for (i_ = i + 1; i_ <= n - 1; i_++) { tmp[i_] = sa * AP.Math.Conj(a[i, i_]); } for (i_ = i + 1; i_ <= n - 1; i_++) { x[i_] = x[i_] - vc * tmp[i_]; } } } return result; } if (!isupper & trans == 2) { // // L^T*x = b // for (i = n - 1; i >= 0; i--) { // // Task is reduced to alpha*x[i] = beta // if (isunit) { alpha = sa; } else { alpha = AP.Math.Conj(a[i, i]) * sa; } beta = x[i]; // // solve alpha*x[i] = beta // result = cbasicsolveandupdate(alpha, beta, lnmax, nrmb, maxgrowth, ref nrmx, ref vc); if (!result) { return result; } x[i] = vc; // // update the rest of right part // if (i > 0) { for (i_ = 0; i_ <= i - 1; i_++) { tmp[i_] = sa * AP.Math.Conj(a[i, i_]); } for (i_ = 0; i_ <= i - 1; i_++) { x[i_] = x[i_] - vc * tmp[i_]; } } } return result; } result = false; return result; } /************************************************************************* complex basic solver-updater for reduced linear system alpha*x[i] = beta solves this equation and updates it in overlfow-safe manner (keeping track of relative growth of solution). Parameters: Alpha - alpha Beta - beta LnMax - precomputed Ln(MaxRealNumber) BNorm - inf-norm of b (right part of original system) MaxGrowth- maximum growth of norm(x) relative to norm(b) XNorm - inf-norm of other components of X (which are already processed) it is updated by CBasicSolveAndUpdate. X - solution -- ALGLIB routine -- 26.01.2009 Bochkanov Sergey *************************************************************************/ private static bool cbasicsolveandupdate(AP.Complex alpha, AP.Complex beta, double lnmax, double bnorm, double maxgrowth, ref double xnorm, ref AP.Complex x) { bool result = new bool(); double v = 0; result = false; if (alpha == 0) { return result; } if (beta != 0) { // // alpha*x[i]=beta // v = Math.Log(AP.Math.AbsComplex(beta)) - Math.Log(AP.Math.AbsComplex(alpha)); if ((double)(v) > (double)(lnmax)) { return result; } x = beta / alpha; } else { // // alpha*x[i]=0 // x = 0; } // // update NrmX, test growth limit // xnorm = Math.Max(xnorm, AP.Math.AbsComplex(x)); if ((double)(xnorm) > (double)(maxgrowth * bnorm)) { return result; } result = true; return result; } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Runtime.Serialization; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Orleans; using Orleans.Concurrency; using Orleans.Configuration; using Orleans.GrainDirectory; using Orleans.Runtime; using Orleans.Serialization; using Orleans.Serialization.TypeSystem; using Orleans.ServiceBus.Providers; using Orleans.Streams; using Orleans.Utilities; using TestExtensions; using TestGrainInterfaces; using UnitTests.GrainInterfaces; using UnitTests.Grains; using Xunit; using Xunit.Abstractions; // ReSharper disable NotAccessedVariable namespace UnitTests.Serialization { /// <summary> /// Test the built-in serializers /// </summary> [Collection(TestEnvironmentFixture.DefaultCollection), TestCategory("Serialization")] public class BuiltInSerializerTests { private readonly ITestOutputHelper output; private readonly TestEnvironmentFixture environment; public BuiltInSerializerTests(ITestOutputHelper output, TestEnvironmentFixture fixture) { this.output = output; this.environment = fixture; } [Fact, TestCategory("BVT"), TestCategory("CodeGen")] public void InternalSerializableTypesHaveSerializers() { Assert.True( environment.Serializer.CanSerialize<int>(), $"Should be able to serialize internal type {nameof(Int32)}."); Assert.True( environment.Serializer.CanSerialize(typeof(List<int>)), $"Should be able to serialize internal type {nameof(List<int>)}."); Assert.True( environment.Serializer.CanSerialize(typeof(PubSubGrainState)), $"Should be able to serialize internal type {nameof(PubSubGrainState)}."); Assert.True( environment.Serializer.CanSerialize(typeof(EventHubBatchContainer)), $"Should be able to serialize internal type {nameof(EventHubBatchContainer)}."); Assert.True( environment.Serializer.CanSerialize(typeof(EventHubSequenceTokenV2)), $"Should be able to serialize internal type {nameof(EventHubSequenceTokenV2)}."); } [Fact(Skip = "See https://github.com/dotnet/orleans/issues/3531"), TestCategory("BVT"), TestCategory("CodeGen")] public void ValueTupleTypesHasSerializer() { Assert.True( environment.Serializer.CanSerialize(typeof(ValueTuple<int, AddressAndTag>)), $"Should be able to serialize internal type {nameof(ValueTuple<int, AddressAndTag>)}."); } /// <summary> /// Tests that the default (non-fallback) serializer can handle complex classes. /// </summary> /// <param name="serializerToUse"></param> [Fact, TestCategory("BVT")] public void Serialize_ComplexAccessibleClass() { var expected = new AnotherConcreteClass { Int = 89, AnotherString = Guid.NewGuid().ToString(), NonSerializedInt = 39, Enum = SomeAbstractClass.SomeEnum.Something, }; expected.Classes = new SomeAbstractClass[] { expected, new AnotherConcreteClass { AnotherString = "hi", Interfaces = new List<ISomeInterface> { expected } } }; expected.Interfaces = new List<ISomeInterface> { expected.Classes[1] }; expected.SetObsoleteInt(38); var actual = (AnotherConcreteClass)OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, expected); Assert.Equal(expected.Int, actual.Int); Assert.Equal(expected.Enum, actual.Enum); Assert.Equal(expected.AnotherString, actual.AnotherString); Assert.Equal(expected.Classes.Length, actual.Classes.Length); Assert.Equal(expected.Classes[1].Interfaces[0].Int, actual.Classes[1].Interfaces[0].Int); Assert.Equal(expected.Interfaces[0].Int, actual.Interfaces[0].Int); Assert.Equal(actual.Interfaces[0], actual.Classes[1]); Assert.NotEqual(expected.NonSerializedInt, actual.NonSerializedInt); Assert.Equal(0, actual.NonSerializedInt); Assert.Equal(expected.GetObsoleteInt(), actual.GetObsoleteInt()); Assert.Null(actual.SomeGrainReference); } [Fact, TestCategory("BVT")] public void Serialize_Type() { // Test serialization of Type. var expected = typeof(int); var actual = (Type)OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, expected); Assert.Equal(expected.AssemblyQualifiedName, actual.AssemblyQualifiedName); // Test serialization of RuntimeType. expected = 8.GetType(); actual = (Type)OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, expected); Assert.Equal(expected.AssemblyQualifiedName, actual.AssemblyQualifiedName); } [Fact, TestCategory("BVT")] public void Serialize_ComplexStruct() { // Test struct serialization. var expected = new SomeStruct(10) { Id = Guid.NewGuid(), PublicValue = 6, ValueWithPrivateGetter = 7 }; expected.SetValueWithPrivateSetter(8); expected.SetPrivateValue(9); var actual = (SomeStruct)OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, expected); Assert.Equal(expected.Id, actual.Id); Assert.Equal(expected.ReadonlyField, actual.ReadonlyField); Assert.Equal(expected.PublicValue, actual.PublicValue); Assert.Equal(expected.ValueWithPrivateSetter, actual.ValueWithPrivateSetter); Assert.Null(actual.SomeGrainReference); Assert.Equal(expected.GetPrivateValue(), actual.GetPrivateValue()); Assert.Equal(expected.GetValueWithPrivateGetter(), actual.GetValueWithPrivateGetter()); } [Fact, TestCategory("Functional")] public void Serialize_ActivationAddress() { GrainId grain = LegacyGrainId.NewId(); var addr = ActivationAddress.GetAddress(null, grain, default); object deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, addr, false); Assert.IsAssignableFrom<ActivationAddress>(deserialized); Assert.Null(((ActivationAddress)deserialized).Activation); //Activation no longer null after copy Assert.Null(((ActivationAddress)deserialized).Silo); //Silo no longer null after copy Assert.Equal(grain, ((ActivationAddress)deserialized).Grain); //Grain different after copy deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, addr); Assert.IsAssignableFrom<ActivationAddress>(deserialized); //ActivationAddress full serialization loop as wrong type Assert.Null(((ActivationAddress)deserialized).Activation); //Activation no longer null after full serialization loop Assert.Null(((ActivationAddress)deserialized).Silo); //Silo no longer null after full serialization loop Assert.Equal(grain, ((ActivationAddress)deserialized).Grain); //Grain different after copy } [Fact, TestCategory("Functional")] public void Serialize_EmptyList() { var list = new List<int>(); var deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, list, false); Assert.IsAssignableFrom<List<int>>(deserialized); //Empty list of integers copied as wrong type" ValidateList(list, (List<int>)deserialized, "int (empty, copy)"); deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, list); Assert.IsAssignableFrom<List<int>>(deserialized); //Empty list of integers full serialization loop as wrong type ValidateList(list, (List<int>)deserialized, "int (empty)"); } [Fact, TestCategory("Functional")] public void Serialize_BasicDictionaries() { Dictionary<string, string> source1 = new Dictionary<string, string>(); source1["Hello"] = "Yes"; source1["Goodbye"] = "No"; var deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, source1); ValidateDictionary<string, string>(source1, deserialized, "string/string"); Dictionary<int, DateTime> source2 = new Dictionary<int, DateTime>(); source2[3] = DateTime.Now; source2[27] = DateTime.Now.AddHours(2); deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, source2); ValidateDictionary<int, DateTime>(source2, deserialized, "int/date"); } [Fact, TestCategory("Functional")] public void Serialize_ReadOnlyDictionary() { Dictionary<string, string> source1 = new Dictionary<string, string>(); source1["Hello"] = "Yes"; source1["Goodbye"] = "No"; var readOnlySource1 = new ReadOnlyDictionary<string, string>(source1); var deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, readOnlySource1); ValidateReadOnlyDictionary(readOnlySource1, deserialized, "string/string"); Dictionary<int, DateTime> source2 = new Dictionary<int, DateTime>(); source2[3] = DateTime.Now; source2[27] = DateTime.Now.AddHours(2); var readOnlySource2 = new ReadOnlyDictionary<int, DateTime>(source2); deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, readOnlySource2); ValidateReadOnlyDictionary(readOnlySource2, deserialized, "int/date"); } [Fact, TestCategory("Functional")] public void Serialize_DictionaryWithComparer() { Dictionary<string, string> source1 = new Dictionary<string, string>(new CaseInsensitiveStringEquality()); source1["Hello"] = "Yes"; source1["Goodbye"] = "No"; var deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, source1); ValidateDictionary<string, string>(source1, deserialized, "case-insensitive string/string"); Dictionary<string, string> result1 = deserialized as Dictionary<string, string>; Assert.Equal(source1["Hello"], result1["hElLo"]); //Round trip for case insensitive string/string dictionary lost the custom comparer Dictionary<int, DateTime> source2 = new Dictionary<int, DateTime>(new Mod5IntegerComparer()); source2[3] = DateTime.Now; source2[27] = DateTime.Now.AddHours(2); deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, source2); ValidateDictionary<int, DateTime>(source2, deserialized, "int/date"); Dictionary<int, DateTime> result2 = (Dictionary<int, DateTime>)deserialized; Assert.Equal<DateTime>(source2[3], result2[13]); //Round trip for case insensitive int/DateTime dictionary lost the custom comparer" } [Fact, TestCategory("Functional")] public void Serialize_SortedDictionaryWithComparer() { var source1 = new SortedDictionary<string, string>(new CaseInsensitiveStringComparer()); source1["Hello"] = "Yes"; source1["Goodbye"] = "No"; object deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, source1); ValidateSortedDictionary<string, string>(source1, deserialized, "string/string"); } [Fact, TestCategory("Functional")] public void Serialize_SortedListWithComparer() { var source1 = new SortedList<string, string>(new CaseInsensitiveStringComparer()); source1["Hello"] = "Yes"; source1["Goodbye"] = "No"; object deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, source1); ValidateSortedList<string, string>(source1, deserialized, "string/string"); } [Fact, TestCategory("Functional")] public void Serialize_HashSetWithComparer() { var source1 = new HashSet<string>(new CaseInsensitiveStringEquality()); source1.Add("one"); source1.Add("two"); source1.Add("three"); var deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, source1); Assert.IsAssignableFrom(source1.GetType(), deserialized); //Type is wrong after round-trip of string hash set with comparer var result = deserialized as HashSet<string>; Assert.Equal(source1.Count, result.Count); //Count is wrong after round-trip of string hash set with comparer #pragma warning disable xUnit2017 // Do not use Contains() to check if a value exists in a collection foreach (var key in source1) { Assert.True(result.Contains(key)); //key is missing after round-trip of string hash set with comparer } Assert.True(result.Contains("One")); //Comparer is wrong after round-trip of string hash set with comparer #pragma warning restore xUnit2017 // Do not use Contains() to check if a value exists in a collection } [Fact, TestCategory("Functional")] public void Serialize_Stack() { var source1 = new Stack<string>(); source1.Push("one"); source1.Push("two"); source1.Push("three"); object deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, source1); Assert.IsAssignableFrom(source1.GetType(), deserialized); //Type is wrong after round-trip of string stack var result = deserialized as Stack<string>; Assert.Equal(source1.Count, result.Count); //Count is wrong after round-trip of string stack var srcIter = source1.GetEnumerator(); var resIter = result.GetEnumerator(); while (srcIter.MoveNext() && resIter.MoveNext()) { Assert.Equal(srcIter.Current, resIter.Current); //Data is wrong after round-trip of string stack } } /// <summary> /// Tests that the <see cref="IOnDeserialized"/> callback is invoked after deserialization. /// </summary> /// <param name="serializerToUse"></param> [Fact, TestCategory("Functional")] public void Serialize_TypeWithOnDeserializedHook() { var input = new TypeWithOnDeserializedHook { Int = 5 }; var deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, input); var result = Assert.IsType<TypeWithOnDeserializedHook>(deserialized); Assert.Equal(input.Int, result.Int); Assert.Null(input.Context); Assert.NotNull(result.Context); } [Fact, TestCategory("Functional")] public void Serialize_SortedSetWithComparer() { var source1 = new SortedSet<string>(new CaseInsensitiveStringComparer()); source1.Add("one"); source1.Add("two"); source1.Add("three"); object deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, source1); Assert.IsAssignableFrom(source1.GetType(), deserialized); //Type is wrong after round-trip of string sorted set with comparer var result = (SortedSet<string>)deserialized; Assert.Equal(source1.Count, result.Count); //Count is wrong after round-trip of string sorted set with comparer #pragma warning disable xUnit2017 // Do not use Contains() to check if a value exists in a collection foreach (var key in source1) { Assert.True(result.Contains(key)); //key is missing after round-trip of string sorted set with comparer } Assert.True(result.Contains("One")); //Comparer is wrong after round-trip of string sorted set with comparer #pragma warning restore xUnit2017 // Do not use Contains() to check if a value exists in a collection } [Fact, TestCategory("Functional")] public void Serialize_Array() { var source1 = new int[] { 1, 3, 5 }; object deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, source1); ValidateArray<int>(source1, deserialized, "int"); var source2 = new string[] { "hello", "goodbye", "yes", "no", "", "I don't know" }; deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, source2); ValidateArray<string>(source2, deserialized, "string"); var source3 = new sbyte[] { 1, 3, 5 }; deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, source3); ValidateArray<sbyte>(source3, deserialized, "sbyte"); var source4 = new byte[] { 1, 3, 5 }; deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, source4); ValidateArray<byte>(source4, deserialized, "byte"); } [Fact, TestCategory("Functional")] public void Serialize_ArrayOfArrays() { var source1 = new[] { new[] { 1, 3, 5 }, new[] { 10, 20, 30 }, new[] { 17, 13, 11, 7, 5, 3, 2 } }; object deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, source1); ValidateArrayOfArrays(source1, deserialized, "int"); var source2 = new[] { new[] { "hello", "goodbye", "yes", "no", "", "I don't know" }, new[] { "yes" } }; deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, source2); ValidateArrayOfArrays(source2, deserialized, "string"); var source3 = new HashSet<string>[3][]; source3[0] = new HashSet<string>[2]; source3[1] = new HashSet<string>[3]; source3[2] = new HashSet<string>[1]; source3[0][0] = new HashSet<string>(); source3[0][1] = new HashSet<string>(); source3[1][0] = new HashSet<string>(); source3[1][1] = null; source3[1][2] = new HashSet<string>(); source3[2][0] = new HashSet<string>(); source3[0][0].Add("this"); source3[0][0].Add("that"); source3[1][0].Add("the other"); source3[1][2].Add("and another"); source3[2][0].Add("but not yet another"); deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, source3); var result = Assert.IsAssignableFrom<HashSet<string>[][]>(deserialized); //Array of arrays of hash sets type is wrong on deserialization Assert.Equal(3, result.Length); //Outer array size wrong on array of array of sets Assert.Equal(2, result[0][0].Count); //Inner set size wrong on array of array of sets, element 0,0 Assert.Empty(result[0][1]); //Inner set size wrong on array of array of sets, element 0,1 Assert.Single(result[1][0]); //Inner set size wrong on array of array of sets, element 1,0 Assert.Null(result[1][1]); //Inner set not null on array of array of sets, element 1, 1 Assert.Single(result[1][2]); //Inner set size wrong on array of array of sets, element 1,2 Assert.Single(result[2][0]); //Inner set size wrong on array of array of sets, element 2,0 var source4 = new GrainReference[3][]; source4[0] = new GrainReference[2]; source4[1] = new GrainReference[3]; source4[2] = new GrainReference[1]; source4[0][0] = (GrainReference)environment.InternalGrainFactory.GetGrain(LegacyGrainId.NewId()); source4[0][1] = (GrainReference)environment.InternalGrainFactory.GetGrain(LegacyGrainId.NewId()); source4[1][0] = (GrainReference)environment.InternalGrainFactory.GetGrain(LegacyGrainId.NewId()); source4[1][1] = (GrainReference)environment.InternalGrainFactory.GetGrain(LegacyGrainId.NewId()); source4[1][2] = (GrainReference)environment.InternalGrainFactory.GetGrain(LegacyGrainId.NewId()); source4[2][0] = (GrainReference)environment.InternalGrainFactory.GetGrain(LegacyGrainId.NewId()); deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, source4); ValidateArrayOfArrays(source4, deserialized, "grain reference"); var source5 = new GrainReference[32][]; for (int i = 0; i < source5.Length; i++) { source5[i] = new GrainReference[64]; for (int j = 0; j < source5[i].Length; j++) { source5[i][j] = (GrainReference)environment.InternalGrainFactory.GetGrain(LegacyGrainId.NewId()); } } deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, source5); ValidateArrayOfArrays(source5, deserialized, "grain reference (large)"); } [Fact, TestCategory("Functional")] public void Serialize_ArrayOfArrayOfArrays() { var source1 = new[] { new[] { 1, 3, 5 }, new[] { 10, 20, 30 }, new[] { 17, 13, 11, 7, 5, 3, 2 } }; var source2 = new[] { new[] { 1, 3 }, new[] { 10, 20 }, new[] { 17, 13, 11, 7, 5 } }; var source3 = new[] { new[] { 1, 3, 5 }, new[] { 10, 20, 30 } }; var source = new[] { source1, source2, source3 }; object deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, source); ValidateArrayOfArrayOfArrays(source, deserialized, "int"); } [Fact, TestCategory("Functional")] public void Serialize_ReadOnlyCollection() { var source1 = new List<string> { "Yes", "No" }; var collection = new ReadOnlyCollection<string>(source1); var deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, collection); ValidateReadOnlyCollectionList(collection, deserialized, "string/string"); } private class BanningTypeResolver : TypeResolver { private readonly CachedTypeResolver _resolver = new CachedTypeResolver(); private readonly HashSet<Type> _blockedTypes; public BanningTypeResolver(params Type[] blockedTypes) { _blockedTypes = new HashSet<Type>(); foreach (var type in blockedTypes ?? Array.Empty<Type>()) { _blockedTypes.Add(type); } } public override Type ResolveType(string name) { var result = _resolver.ResolveType(name); if (_blockedTypes.Contains(result)) { result = null; } return result; } public override bool TryResolveType(string name, out Type type) { if (_resolver.TryResolveType(name, out type)) { if (_blockedTypes.Contains(type)) { type = null; return false; } return true; } return false; } } [Fact, TestCategory("Functional")] public void Serialize_ObjectIdentity() { var val = new List<string> { "first", "second" }; var val2 = new List<string> { "first", "second" }; var source = new Dictionary<string, List<string>>(); source["one"] = val; source["two"] = val; source["three"] = val2; Assert.Same(source["one"], source["two"]); //Object identity lost before round trip of string/list dict!!! var deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, source); var result = Assert.IsAssignableFrom<Dictionary<string, List<string>>>(deserialized); //Type is wrong after round-trip of string/list dict Assert.Equal(source.Count, result.Count); //Count is wrong after round-trip of string/list dict List<string> list1; List<string> list2; List<string> list3; Assert.True(result.TryGetValue("one", out list1)); //Key 'one' not found after round trip of string/list dict Assert.True(result.TryGetValue("two", out list2)); //Key 'two' not found after round trip of string/list dict Assert.True(result.TryGetValue("three", out list3)); //Key 'three' not found after round trip of string/list dict ValidateList<string>(val, list1, "string"); ValidateList<string>(val, list2, "string"); ValidateList<string>(val2, list3, "string"); Assert.Same(list1, list2); //Object identity lost after round trip of string/list dict Assert.NotSame(list2, list3); //Object identity gained after round trip of string/list dict Assert.NotSame(list1, list3); //Object identity gained after round trip of string/list dict } [Fact, TestCategory("Functional")] public void Serialize_Unrecognized() { var test1 = new Unrecognized { A = 3, B = 27 }; var raw = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, test1, false); var result = Assert.IsAssignableFrom<Unrecognized>(raw); //Type is wrong after deep copy of unrecognized Assert.Equal(3, result.A); //Property A is wrong after deep copy of unrecognized" Assert.Equal(27, result.B); //Property B is wrong after deep copy of unrecognized" var test2 = new Unrecognized[3]; for (int i = 0; i < 3; i++) { test2[i] = new Unrecognized { A = i, B = 2 * i }; } raw = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, test2); Assert.IsAssignableFrom<Unrecognized[]>(raw); //Type is wrong after round trip of array of unrecognized var result2 = (Unrecognized[])raw; Assert.Equal(3, result2.Length); //Array length is wrong after round trip of array of unrecognized for (int j = 0; j < 3; j++) { Assert.Equal(j, result2[j].A); //Property A at index " + j + "is wrong after round trip of array of unrecognized Assert.Equal(2 * j, result2[j].B); //Property B at index " + j + "is wrong after round trip of array of unrecognized } } [Fact, TestCategory("Functional")] public void Serialize_Immutable() { var test1 = new ImmutableType(3, 27); var raw = environment.DeepCopier.Copy<object>(test1); Assert.IsAssignableFrom<ImmutableType>(raw); //Type is wrong after deep copy of [Immutable] type Assert.Same(test1, raw); //Deep copy of [Immutable] object made a copy instead of just copying the pointer var test2list = new List<int>(); for (int i = 0; i < 3; i++) { test2list.Add(i); } var test2 = new Immutable<List<int>>(test2list); raw = environment.DeepCopier.Copy<object>(test2); Assert.IsAssignableFrom<Immutable<List<int>>>(raw); //Type is wrong after round trip of array of Immutable<> Assert.Same(test2.Value, ((Immutable<List<int>>)raw).Value); //Deep copy of Immutable<> object made a copy instead of just copying the pointer var test3 = new EmbeddedImmutable("test", 1, 2, 3, 4); raw = environment.DeepCopier.Copy<object>(test3); Assert.IsAssignableFrom<EmbeddedImmutable>(raw); //Type is wrong after deep copy of type containing an Immutable<> field Assert.Same(test3.B.Value, ((EmbeddedImmutable)raw).B.Value); //Deep copy of embedded [Immutable] object made a copy instead of just copying the pointer } [Fact, TestCategory("Functional")] public void Serialize_GrainReference() { GrainId grainId = LegacyGrainId.NewId(); GrainReference input = (GrainReference)environment.InternalGrainFactory.GetGrain(grainId); object deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, input); var grainRef = Assert.IsAssignableFrom<GrainReference>(deserialized); //GrainReference copied as wrong type Assert.Equal(grainId, grainRef.GrainId); //GrainId different after copy Assert.Equal(input, grainRef); //Wrong contents after round-trip of input } internal bool AreByteArraysAreEqual(byte[] array1, byte[] array2) { if (array1.Length != array2.Length) return false; for (int i = 0; i < array1.Length; i++) { if (array1[i] != array2[i]) return false; } return true; } internal static object OrleansSerializationLoop(Serializer serializer, DeepCopier copier, object input, bool includeWire = true) { var copy = copier.Copy(input); if (includeWire) { copy = serializer.RoundTripSerializationForTesting(copy); } return copy; } private void ValidateDictionary<K, V>(Dictionary<K, V> source, object deserialized, string type) { var result = Assert.IsAssignableFrom<Dictionary<K, V>>(deserialized); //Type is wrong after round-trip of dict ValidateDictionaryContent(source, result, type); } private void ValidateDictionaryContent<K, V>(IDictionary<K, V> source, IDictionary<K, V> result, string type) { Assert.Equal(source.Count, result.Count); //Count is wrong after round-trip of " + type + " dict" foreach (var pair in source) { Assert.True(result.ContainsKey(pair.Key), "Key " + pair.Key.ToString() + " is missing after round-trip of " + type + " dict"); Assert.Equal<V>(pair.Value, result[pair.Key]); //Key has wrong value after round-trip } } private void ValidateReadOnlyDictionary<K, V>(ReadOnlyDictionary<K, V> source, object deserialized, string type) { var result = Assert.IsAssignableFrom<ReadOnlyDictionary<K, V>>(deserialized); //Type is wrong after round-trip ValidateDictionaryContent(source, result, type); } private void ValidateSortedDictionary<K, V>(SortedDictionary<K, V> source, object deserialized, string type) { Assert.IsAssignableFrom<SortedDictionary<K, V>>(deserialized); SortedDictionary<K, V> result = deserialized as SortedDictionary<K, V>; Assert.Equal(source.Count, result.Count); //Count is wrong after round-trip of " + type + " sorted dict foreach (var pair in source) { Assert.True(result.ContainsKey(pair.Key)); //Key " + pair.Key.ToString() + " is missing after round-trip of " + type + " sorted dict Assert.Equal<V>(pair.Value, result[pair.Key]); //Key " + pair.Key.ToString() + " has wrong value after round-trip of " + type + " sorted dict } var sourceKeys = source.Keys.GetEnumerator(); var resultKeys = result.Keys.GetEnumerator(); while (sourceKeys.MoveNext() && resultKeys.MoveNext()) { Assert.Equal<K>(sourceKeys.Current, resultKeys.Current); //Keys out of order after round-trip of " + type + " sorted dict } } private void ValidateSortedList<K, V>(SortedList<K, V> source, object deserialized, string type) { Assert.IsAssignableFrom<SortedList<K, V>>(deserialized); SortedList<K, V> result = deserialized as SortedList<K, V>; Assert.Equal(source.Count, result.Count); //Count is wrong after round-trip of " + type + " sorted list" foreach (var pair in source) { Assert.True(result.ContainsKey(pair.Key)); //Key " + pair.Key.ToString() + " is missing after round-trip of " + type + " sorted list Assert.Equal<V>(pair.Value, result[pair.Key]); //Key " + pair.Key.ToString() + " has wrong value after round-trip of " + type + " sorted list } var sourceKeys = source.Keys.GetEnumerator(); var resultKeys = result.Keys.GetEnumerator(); while (sourceKeys.MoveNext() && resultKeys.MoveNext()) { Assert.Equal<K>(sourceKeys.Current, resultKeys.Current); //Keys out of order after round-trip of " + type + " sorted list } } private void ValidateReadOnlyCollectionList<T>(ReadOnlyCollection<T> expected, object deserialized, string type) { Assert.IsAssignableFrom<ReadOnlyCollection<T>>(deserialized); //Type is wrong after round-trip of " + type + " array ValidateList(expected, deserialized as IList<T>, type); } private void ValidateList<T>(IList<T> expected, IList<T> result, string type) { Assert.Equal(expected.Count, result.Count); for (int i = 0; i < expected.Count; i++) { Assert.Equal<T>(expected[i], result[i]); //Item " + i + " is wrong after round trip of " + type + " list } } private void ValidateArray<T>(T[] expected, object deserialized, string type) { var result = Assert.IsAssignableFrom<T[]>(deserialized); Assert.Equal(expected.Length, result.Length); //Length is wrong after round-trip of " + type + " array" for (int i = 0; i < expected.Length; i++) { Assert.Equal<T>(expected[i], result[i]); //Item " + i + " is wrong after round trip of " + type + " array" } } private void ValidateArrayOfArrays<T>(T[][] expected, object deserialized, string type) { var result = Assert.IsAssignableFrom<T[][]>(deserialized); //Type is wrong after round-trip of " + type + " array of arrays" Assert.Equal(expected.Length, result.Length); //Length is wrong after round-trip of " + type + " array of arrays" for (int i = 0; i < expected.Length; i++) { ValidateArray<T>(expected[i], result[i], "Array of " + type + "[" + i + "] "); } } private void ValidateArrayOfArrayOfArrays<T>(T[][][] expected, object deserialized, string type) { var result = Assert.IsAssignableFrom<T[][][]>(deserialized); //Type is wrong after round-trip of " + type + " array of arrays" Assert.Equal(expected.Length, result.Length); //Length is wrong after round-trip of " + type + " array of arrays" for (int i = 0; i < expected.Length; i++) { ValidateArrayOfArrays<T>(expected[i], result[i], "Array of " + type + "[" + i + "][]"); } } [Fact, TestCategory("Functional")] public void Serialize_CircularReference() { var c1 = new CircularTest1(); var c2 = new CircularTest2(); c2.CircularTest1List.Add(c1); c1.CircularTest2 = c2; var deserialized = (CircularTest1)OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, c1); Assert.Equal(c1.CircularTest2.CircularTest1List.Count, deserialized.CircularTest2.CircularTest1List.Count); Assert.Same(deserialized, deserialized.CircularTest2.CircularTest1List[0]); deserialized = (CircularTest1)OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, c1, true); Assert.Equal(c1.CircularTest2.CircularTest1List.Count, deserialized.CircularTest2.CircularTest1List.Count); Assert.Same(deserialized, deserialized.CircularTest2.CircularTest1List[0]); } [Fact, TestCategory("Functional")] public void Serialize_Enums() { var result = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, IntEnum.Value2); var typedResult = Assert.IsType<IntEnum>(result); Assert.Equal(IntEnum.Value2, typedResult); var result2 = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, UShortEnum.Value3); var typedResult2 = Assert.IsType<UShortEnum>(result2); Assert.Equal(UShortEnum.Value3, typedResult2); var test = new ClassWithEnumTestData { EnumValue = TestEnum.Third, Enemy = CampaignEnemyTestType.Enemy3 }; var result3 = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, test); var typedResult3 = Assert.IsType<ClassWithEnumTestData>(result3); Assert.Equal(TestEnum.Third, typedResult3.EnumValue); Assert.Equal(CampaignEnemyTestType.Enemy3, typedResult3.Enemy); var result4 = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, CampaignEnemyType.Enemy3); var typedResult4 = Assert.IsType<CampaignEnemyType>(result4); Assert.Equal(CampaignEnemyType.Enemy3, typedResult4); } } } // ReSharper restore NotAccessedVariable
#region License // Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk) // // 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. // // The latest version of this file can be found at https://github.com/jeremyskinner/FluentValidation #endregion using System.Linq; namespace FluentValidation.Tests { using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Xunit; public class CollectionValidatorWithParentTests { Person person; public CollectionValidatorWithParentTests() { person = new Person() { AnotherInt = 99, Children = new List<Person>() { new Person() { Email = "[email protected]"} }, Orders = new List<Order>() { new Order { ProductName = "email_that_does_not_belong_to_a_person", Amount = 99}, new Order { ProductName = "[email protected]", Amount = 1}, new Order { ProductName = "another_email_that_does_not_belong_to_a_person", Amount = 1}, } }; } [Fact] public void Validates_collection() { var validator = new TestValidator { v => v.RuleFor(x => x.Surname).NotNull(), v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderValidator(y)) }; var results = validator.Validate(person); results.Errors.Count.ShouldEqual(3); results.Errors[1].PropertyName.ShouldEqual("Orders[0].ProductName"); results.Errors[2].PropertyName.ShouldEqual("Orders[2].ProductName"); } [Fact] public void Validates_collection_asynchronously() { var validator = new TestValidator { v => v.RuleFor(x => x.Surname).NotNull(), v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new AsyncOrderValidator(y)) }; var results = validator.ValidateAsync(person).Result; results.Errors.Count.ShouldEqual(3); results.Errors[1].PropertyName.ShouldEqual("Orders[0].ProductName"); results.Errors[2].PropertyName.ShouldEqual("Orders[2].ProductName"); } [Fact] public void Collection_should_be_explicitly_included_with_expression() { var validator = new TestValidator { v => v.RuleFor(x => x.Surname).NotNull(), v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderValidator(y)) }; var results = validator.Validate(person, x => x.Orders); results.Errors.Count.ShouldEqual(2); } [Fact] public void Collection_should_be_explicitly_included_with_string() { var validator = new TestValidator { v => v.RuleFor(x => x.Surname).NotNull(), v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderValidator(y)) }; var results = validator.Validate(person, "Orders"); results.Errors.Count.ShouldEqual(2); } [Fact] public void Collection_should_be_excluded() { var validator = new TestValidator { v => v.RuleFor(x => x.Surname).NotNull(), v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderValidator(y)) }; var results = validator.Validate(person, x => x.Forename); results.Errors.Count.ShouldEqual(0); } [Fact] public void Condition_should_work_with_child_collection() { var validator = new TestValidator() { v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderValidator(y)).When(x => x.Orders.Count == 4 /*there are only 3*/) }; var result = validator.Validate(person); result.IsValid.ShouldBeTrue(); } [Fact] public void Async_condition_should_work_with_child_collection() { var validator = new TestValidator() { v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderValidator(y)).WhenAsync(async x => x.Orders.Count == 4 /*there are only 3*/) }; var result = validator.ValidateAsync(person).Result; result.IsValid.ShouldBeTrue(); } [Fact] public void Skips_null_items() { var validator = new TestValidator { v => v.RuleFor(x => x.Surname).NotNull(), v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderValidator(y)) }; person.Orders[0] = null; var results = validator.Validate(person); results.Errors.Count.ShouldEqual(2); //2 errors - 1 for person, 1 for 3rd Order. } [Fact] public void Can_validate_collection_using_validator_for_base_type() { var validator = new TestValidator() { v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderInterfaceValidator(y)) }; var result = validator.Validate(person); result.IsValid.ShouldBeFalse(); } [Fact] public void Can_specifiy_condition_for_individual_collection_elements() { var validator = new TestValidator { v => v.RuleFor(x => x.Orders) .SetCollectionValidator(y => new OrderValidator(y)) .Where(x => x.Amount != 1) }; var results = validator.Validate(person); results.Errors.Count.ShouldEqual(1); } [Fact] public void Should_override_property_name() { var validator = new TestValidator { v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderValidator(y)) .OverridePropertyName("Orders2") }; var results = validator.Validate(person); results.Errors[0].PropertyName.ShouldEqual("Orders2[0].ProductName"); } [Fact] public void Should_work_with_top_level_collection_validator() { var personValidator = new InlineValidator<Person>(); personValidator.RuleFor(x => x.Surname).NotNull(); var validator = new InlineValidator<List<Person>>(); validator.RuleFor(x => x).SetCollectionValidator(personValidator); var results = validator.Validate(new List<Person> { new Person(), new Person(), new Person { Surname = "Bishop"} }); results.Errors.Count.ShouldEqual(2); results.Errors[0].PropertyName.ShouldEqual("x[0].Surname"); } [Fact] public void Should_work_with_top_level_collection_validator_and_overriden_name() { var personValidator = new InlineValidator<Person>(); personValidator.RuleFor(x => x.Surname).NotNull(); var validator = new InlineValidator<List<Person>>(); validator.RuleFor(x => x).SetCollectionValidator(personValidator).OverridePropertyName("test"); var results = validator.Validate(new List<Person> { new Person(), new Person(), new Person { Surname = "Bishop" } }); results.Errors.Count.ShouldEqual(2); results.Errors[0].PropertyName.ShouldEqual("test[0].Surname"); } public class OrderValidator : AbstractValidator<Order> { public OrderValidator(Person person) { RuleFor(x => x.ProductName).Must(BeOneOfTheChildrensEmailAddress(person)); } private Func<string, bool> BeOneOfTheChildrensEmailAddress(Person person) { return productName => person.Children.Any(child => child.Email == productName); } } public class OrderInterfaceValidator : AbstractValidator<IOrder> { public OrderInterfaceValidator(Person person) { RuleFor(x => x.Amount).NotEqual(person.AnotherInt); } } public class AsyncOrderValidator : AbstractValidator<Order> { public AsyncOrderValidator(Person person) { RuleFor(x => x.ProductName).MustAsync(BeOneOfTheChildrensEmailAddress(person)); } private Func<string, CancellationToken, Task<bool>> BeOneOfTheChildrensEmailAddress(Person person) { return async (productName, cancel) => person.Children.Any(child => child.Email == productName); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using SAASKit.Api.Areas.HelpPage.Models; namespace SAASKit.Api.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Sandbox.Common; using Sandbox.Common.ObjectBuilders; using Sandbox.Definitions; using Sandbox.Engine; using Sandbox.Game; using Sandbox.ModAPI; using VRage.Game.ModAPI.Interfaces; using VRage; using VRage.ObjectBuilders; using VRage.Game; using VRage.ModAPI; using VRage.Game.Components; using VRageMath; using Sandbox.Engine.Multiplayer; using Sandbox.ModAPI.Interfaces.Terminal; using VRage.Game.ModAPI; namespace LSE { [MyEntityComponentDescriptor(typeof(MyObjectBuilder_OreDetector), true, new string[] { "TransportJammer" })] class Jammer : GameLogicComponent { public static HashSet<Jammer> ScramblerList = new HashSet<Jammer>(); static public bool IsProtected(Vector3D position, IMyCubeBlock transporterBlock) { foreach (var scrambler in ScramblerList) { var scramblerBlock = scrambler.CubeBlock; bool friendlyScrambler = transporterBlock.GetUserRelationToOwner(scramblerBlock.OwnerId).IsFriendly(); if (scrambler.IsProtecting(position) && !friendlyScrambler) { return true; } } return false; } public bool Initialized = true; public RangeSlider<Sandbox.ModAPI.Ingame.IMyOreDetector> Slider; public Sandbox.Game.EntityComponents.MyResourceSinkComponent Sink; public MyDefinitionId PowerDefinitionId = new VRage.Game.MyDefinitionId(typeof(VRage.Game.ObjectBuilders.Definitions.MyObjectBuilder_GasProperties), "Electricity"); public IMyCubeBlock CubeBlock; public override void Init(MyObjectBuilder_EntityBase objectBuilder) { base.Init(objectBuilder); Entity.Components.TryGet<Sandbox.Game.EntityComponents.MyResourceSinkComponent>(out Sink); Sink.SetRequiredInputFuncByType(PowerDefinitionId, CalcRequiredPower); this.NeedsUpdate |= MyEntityUpdateEnum.EACH_100TH_FRAME; CubeBlock = (IMyCubeBlock)Entity; } public float CalcRequiredPower() { float power = 0.0001f; if (!Initialized && CubeBlock.IsWorking) { var radius = Slider.Getter((IMyFunctionalBlock)CubeBlock); power = (float)(4.0 * Math.PI * Math.Pow(radius, 3) / 3.0 / 1000.0 / 1000.0); } return power; } public override void Close() { try { Jammer.ScramblerList.Remove(this); } catch { } base.Close(); } public override void MarkForClose() { try { Jammer.ScramblerList.Remove(this); } catch { } base.MarkForClose(); } public override void UpdateBeforeSimulation100() { if (Initialized) { CreateUI(); ((IMyFunctionalBlock)CubeBlock).AppendingCustomInfo += AppendingCustomInfo; Initialized = false; } ScramblerList.Add(this); } void AppendingCustomInfo(IMyTerminalBlock block, StringBuilder stringBuilder) { var jammer = block.GameLogic.GetAs<Jammer>(); if (jammer == null) { return; } stringBuilder.Clear(); stringBuilder.Append("Required Power: " + jammer.CalcRequiredPower().ToString("0.00") + "MW"); } public bool IsProtecting(Vector3D postion) { if (((IMyFunctionalBlock)CubeBlock).IsWorking && ((IMyFunctionalBlock)CubeBlock).IsFunctional) { return Math.Pow(GetRadius(), 2) > (CubeBlock.GetPosition() - postion).LengthSquared(); } return false; } float GetRadius() { return Slider.Getter((IMyTerminalBlock)CubeBlock); } void RemoveOreUI() { List<IMyTerminalAction> actions = new List<IMyTerminalAction>(); MyAPIGateway.TerminalControls.GetActions<Sandbox.ModAPI.Ingame.IMyOreDetector>(out actions); var actionAntenna = actions.First((x) => x.Id.ToString() == "BroadcastUsingAntennas"); actionAntenna.Enabled = ShowControlOreDetectorControls; List<IMyTerminalControl> controls = new List<IMyTerminalControl>(); MyAPIGateway.TerminalControls.GetControls<Sandbox.ModAPI.Ingame.IMyOreDetector>(out controls); var antennaControl = controls.First((x) => x.Id.ToString() == "BroadcastUsingAntennas"); antennaControl.Visible = ShowControlOreDetectorControls; // var radiusControl = controls.First((x) => x.Id.ToString() == "Range"); // radiusControl.Visible = ShowControlOreDetectorControls; } bool ShowControlOreDetectorControls(IMyTerminalBlock block) { return block.BlockDefinition.SubtypeName.Contains("OreDetector"); } public void CreateUI() { RemoveOreUI(); Slider = new RangeSlider<Sandbox.ModAPI.Ingame.IMyOreDetector>((IMyFunctionalBlock)CubeBlock, "RadiusSlider", "Transporter Jammer Radius", 10, 500, 50); } } class RangeSlider<T> : Control.Slider<T> { public RangeSlider( IMyTerminalBlock block, string internalName, string title, float min = 0.0f, float max = 100.0f, float standard = 10.0f) : base(block, internalName, title, min, max, standard) { } public override void Writer(IMyTerminalBlock block, StringBuilder builder) { try { builder.Clear(); var distanceString = Getter(block).ToString("0") + "m"; builder.Append(distanceString); block.RefreshCustomInfo(); } catch { } } public void SetterOutside(IMyTerminalBlock block, float value) { base.Setter(block, value); var jammer = block.GameLogic.GetAs<Jammer>(); if (jammer == null) { return; } jammer.Sink.Update(); } public override void Setter(IMyTerminalBlock block, float value) { base.Setter(block, value); var message = new JammerNetwork.MessageSync() { Value = value, EntityId = block.EntityId }; JammerNetwork.MessageUtils.SendMessageToAll(message); var jammer = block.GameLogic.GetAs<Jammer>(); if (jammer == null) { return; } jammer.Sink.Update(); } } }
//------------------------------------------------------------------------------ // <copyright file="TraceContext.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* * The context for outputting trace information in the page. * * Copyright (c) 1999 Microsoft Corporation */ namespace System.Web { using System; // using System.Web.UI; using System.Web.Handlers; using System.Web.Util; using System.Web.SessionState; using System.Text; using System.Data; using System.Globalization; using System.Collections; using System.Collections.Specialized; using System.Diagnostics; using System.Security.Permissions; using System.Web.Configuration; using System.Threading; using System.ComponentModel; /// <devdoc> /// <para>Captures and presents execution details about a Web request.</para> /// <para>Use the TraceContext /// class by appending trace messages to specific trace categories. For example, a /// calendar class might append the message ?Calendar1-&gt;Starting /// To Render? within the Render category, and append the message ?Calendar1-&gt;Firing OnChange Event? within /// the Events category. Tracing is enabled by setting the <see topic='cpdirSystem.Web.UI.PageDirectives'/> /// Trace attribute or the System.Web.UI.TraceContext.IsEnabled /// property.</para> /// <para>When tracing is enabled, In addition to showing /// user-provided trace content, the <see cref='System.Web.UI.Page'/> class not only shows user-provided trace content, it automatically includes /// performance data, tree-structure information, and state management content.</para> /// </devdoc> public sealed class TraceContext { private static DataSet _masterRequest; private static bool _writeToDiagnosticsTrace = false; private static readonly object EventTraceFinished = new object(); private EventHandlerList _events = new EventHandlerList(); private TraceMode _traceMode; private TraceEnable _isEnabled; private HttpContext _context; private DataSet _requestData; private long _firstTime; private long _lastTime; private int _uniqueIdCounter = 0; private const string PAGEKEYNAME = "__PAGE"; private const string NULLSTRING = "<null>"; // this will get HtmlEncoded later... private const string NULLIDPREFIX = "__UnassignedID"; private ArrayList _traceRecords; private bool _endDataCollected; private bool _writing = false; /// <devdoc> /// <para>Initializes a new instance of the <see cref='System.Web.TraceContext'/> class.</para> /// </devdoc> public TraceContext(HttpContext context) { _traceMode = TraceMode.Default; // Always disable trace in retail deployment mode (DevDiv 36396) _isEnabled = DeploymentSection.RetailInternal ? TraceEnable.Disable : TraceEnable.Default; _context = context; _firstTime = -1; _lastTime = -1; _endDataCollected = false; _traceRecords = new ArrayList(); } /// <devdoc> /// <para>Indicates the order in which trace messages should be /// output to a requesting browser. Trace messages can be sorted in the order they /// were processed, or alphabetically by user-defined category.</para> /// </devdoc> public TraceMode TraceMode { get { if (_traceMode == TraceMode.Default) return HttpRuntime.Profile.OutputMode; return _traceMode; } set { if (value < TraceMode.SortByTime || value > TraceMode.Default) { throw new ArgumentOutOfRangeException("value"); } _traceMode = value; if (IsEnabled) ApplyTraceMode(); } } /// <devdoc> /// <para>Indicates whether tracing is enabled for the current Web request. /// Use this flag to check whether you should output tracing information before /// writing anything to the trace log.</para> /// </devdoc> public bool IsEnabled { get { if (_isEnabled == TraceEnable.Default) return HttpRuntime.Profile.IsEnabled; else { return (_isEnabled == TraceEnable.Enable) ? true : false; } } set { // Always disable trace in retail deployment mode (DevDiv 36396) if (DeploymentSection.RetailInternal) { System.Web.Util.Debug.Assert(_isEnabled == TraceEnable.Disable); return; } if (value) _isEnabled = TraceEnable.Enable; else _isEnabled = TraceEnable.Disable; } } /// <devdoc> /// <para>Indicates whether trace information should be output to a Web Forms /// page. This property is used only in application-level tracing situations. You /// can set this property in your application's config.web configuration file which /// resides in the root directory of the application. </para> /// </devdoc> internal bool PageOutput { get { if (_isEnabled == TraceEnable.Default) return HttpRuntime.Profile.PageOutput; else { return (_isEnabled == TraceEnable.Enable) ? true : false; } } } // this is used only for error pages, called from Page.HandleError. internal int StatusCode { set { VerifyStart(); DataRow row = _requestData.Tables[SR.Trace_Request].Rows[0]; row[SR.Trace_Status_Code] = value; } } /// <devdoc> /// Raised after the trace has been finished /// </devdoc> public event TraceContextEventHandler TraceFinished { add { _events.AddHandler(EventTraceFinished, value); } remove { _events.RemoveHandler(EventTraceFinished, value); } } private void ApplyTraceMode() { VerifyStart(); if (TraceMode == TraceMode.SortByCategory) _requestData.Tables[SR.Trace_Trace_Information].DefaultView.Sort = SR.Trace_Category; else _requestData.Tables[SR.Trace_Trace_Information].DefaultView.Sort = SR.Trace_From_First; } internal void CopySettingsTo(TraceContext tc) { tc._traceMode = this._traceMode; tc._isEnabled = this._isEnabled; } internal void OnTraceFinished(TraceContextEventArgs e) { TraceContextEventHandler handler = (TraceContextEventHandler)_events[EventTraceFinished]; if (handler != null) { handler(this, e); } } internal static void SetWriteToDiagnosticsTrace(bool value) { _writeToDiagnosticsTrace = value; } /// <devdoc> /// <para>Writes trace information to the trace log including any /// user defined categories and trace messages.</para> /// </devdoc> public void Write(string message) { Write(String.Empty, message, null, false, _writeToDiagnosticsTrace); } /// <devdoc> /// <para>Writes trace information to the trace log including any /// user defined categories and trace messages.</para> /// </devdoc> public void Write(string category, string message) { Write(category, message, null, false, _writeToDiagnosticsTrace); } /// <devdoc> /// <para>Writes trace information to the trace log including any user defined /// categories,trace messages and error information.</para> /// </devdoc> public void Write(string category, string message, Exception errorInfo) { Write(category, message, errorInfo, false, _writeToDiagnosticsTrace); } internal void WriteInternal(string message, bool writeToDiagnostics) { Write(String.Empty, message, null, false, writeToDiagnostics); } internal void WriteInternal(string category, string message, bool writeToDiagnostics) { Write(category, message, null, false, writeToDiagnostics); } /// <devdoc> /// <para>Writes trace information to the trace log including any /// user defined categories and trace messages. All warnings appear as red text.</para> /// </devdoc> public void Warn(string message) { Write(String.Empty, message, null, true, _writeToDiagnosticsTrace); } /// <devdoc> /// <para>Writes trace information to the trace log including any /// user defined categories and trace messages. All warnings appear as red text.</para> /// </devdoc> public void Warn(string category, string message) { Write(category, message, null, true, _writeToDiagnosticsTrace); } /// <devdoc> /// <para>Writes trace information to the trace log including any user defined categories,trace messages and error information. All /// warnings appear as red text. </para> /// </devdoc> public void Warn(string category, string message, Exception errorInfo) { Write(category, message, errorInfo, true, _writeToDiagnosticsTrace); } internal void WarnInternal(string category, string message, bool writeToDiagnostics) { Write(category, message, null, true, writeToDiagnostics); } void Write(string category, string message, Exception errorInfo, bool isWarning, bool writeToDiagnostics) { // Guard against lock(this) { // Bail if trace isn't enabled or this is from our call to System.Diagonostics.Trace below if (!IsEnabled || _writing || _endDataCollected) return; VerifyStart(); if (category == null) category = String.Empty; if (message == null) message = String.Empty; long messagetime = Counter.Value; DataRow row = NewRow(_requestData, SR.Trace_Trace_Information); row[SR.Trace_Category] = category; row[SR.Trace_Message] = message; row[SR.Trace_Warning] = isWarning ? "yes" : "no"; if (errorInfo != null) { row["ErrorInfoMessage"] = errorInfo.Message; row["ErrorInfoStack"] = errorInfo.StackTrace; } if (_firstTime != -1) { row[SR.Trace_From_First] = (((double)(messagetime - _firstTime)) / Counter.Frequency); } else _firstTime = messagetime; if (_lastTime != -1) { row[SR.Trace_From_Last] = (((double)(messagetime - _lastTime)) / Counter.Frequency); } _lastTime = messagetime; AddRow(_requestData, SR.Trace_Trace_Information, row); string msg = message; if (errorInfo != null) { string eMsg = errorInfo.Message; if (eMsg == null) eMsg = String.Empty; string eTrace = errorInfo.StackTrace; if (eTrace == null) eTrace = String.Empty; StringBuilder str = new StringBuilder(message.Length + eMsg.Length + eTrace.Length); str.Append(message); str.Append(" -- "); str.Append(eMsg); str.Append(": "); str.Append(eTrace); msg = str.ToString(); } if (writeToDiagnostics) { _writing = true; System.Diagnostics.Trace.WriteLine(msg, category); _writing = false; } // Send to IIS tracing if (_context != null && _context.WorkerRequest != null) { _context.WorkerRequest.RaiseTraceEvent(isWarning ? IntegratedTraceType.TraceWarn : IntegratedTraceType.TraceWrite, msg); } } // Add the trace record to our collection _traceRecords.Add(new TraceContextRecord(category, message, isWarning, errorInfo)); } internal void AddNewControl(string id, string parentId, string type, int viewStateSize, int controlStateSize) { VerifyStart(); DataRow row = NewRow(_requestData, SR.Trace_Control_Tree); if (id == null) id = NULLIDPREFIX+(_uniqueIdCounter++); row[SR.Trace_Control_Id] = id; if (parentId == null) parentId = PAGEKEYNAME; row[SR.Trace_Parent_Id] = parentId; row[SR.Trace_Type] = type; row[SR.Trace_Viewstate_Size] = viewStateSize; row[SR.Trace_Controlstate_Size] = controlStateSize; row[SR.Trace_Render_Size] = 0; try { AddRow(_requestData, SR.Trace_Control_Tree, row); } catch (ConstraintException) { throw new HttpException(SR.GetString(SR.Duplicate_id_used, id, "Trace")); } } /* * Add the render size to the control */ internal void AddControlSize(String controlId, int renderSize) { VerifyStart(); DataTable dt = _requestData.Tables[SR.Trace_Control_Tree]; // find the row for this control if (controlId == null) controlId = PAGEKEYNAME; DataRow row = dt.Rows.Find((object) controlId); // if the row is null, we couldn't find it, so we'll just skip this control if (row != null) row[SR.Trace_Render_Size] = renderSize; } internal void AddControlStateSize(String controlId, int viewstateSize, int controlstateSize) { VerifyStart(); DataTable dt = _requestData.Tables[SR.Trace_Control_Tree]; // find the row for this control if (controlId == null) controlId = PAGEKEYNAME; DataRow row = dt.Rows.Find((object) controlId); // if the row is null, we couldn't find it, so we'll just skip this control if (row != null) { row[SR.Trace_Viewstate_Size] = viewstateSize; row[SR.Trace_Controlstate_Size] = controlstateSize; } } internal void Render(HtmlTextWriter output) { if (PageOutput && _requestData != null) { TraceEnable oldEnabled = _isEnabled; _isEnabled = TraceEnable.Disable; Control table; output.Write("<div id=\"__asptrace\">\r\n"); output.Write(TraceHandler.StyleSheet); output.Write("<span class=\"tracecontent\">\r\n"); table = TraceHandler.CreateDetailsTable(_requestData.Tables[SR.Trace_Request]); if (table != null) table.RenderControl(output); table = TraceHandler.CreateTraceTable(_requestData.Tables[SR.Trace_Trace_Information]); if (table != null) table.RenderControl(output); table = TraceHandler.CreateControlTable(_requestData.Tables[SR.Trace_Control_Tree]); if (table != null) table.RenderControl(output); table = TraceHandler.CreateTable(_requestData.Tables[SR.Trace_Session_State], true /*encodeSpaces*/); if (table != null) table.RenderControl(output); table = TraceHandler.CreateTable(_requestData.Tables[SR.Trace_Application_State], true /*encodeSpaces*/); if (table != null) table.RenderControl(output); table = TraceHandler.CreateTable(_requestData.Tables[SR.Trace_Request_Cookies_Collection], true /*encodeSpaces*/); if (table != null) table.RenderControl(output); table = TraceHandler.CreateTable(_requestData.Tables[SR.Trace_Response_Cookies_Collection], true /*encodeSpaces*/); if (table != null) table.RenderControl(output); table = TraceHandler.CreateTable(_requestData.Tables[SR.Trace_Headers_Collection], true /*encodeSpaces*/); if (table != null) table.RenderControl(output); table = TraceHandler.CreateTable(_requestData.Tables[SR.Trace_Response_Headers_Collection], true /*encodeSpaces*/); if (table != null) table.RenderControl(output); table = TraceHandler.CreateTable(_requestData.Tables[SR.Trace_Form_Collection]); if (table != null) table.RenderControl(output); table = TraceHandler.CreateTable(_requestData.Tables[SR.Trace_Querystring_Collection]); if (table != null) table.RenderControl(output); table = TraceHandler.CreateTable(_requestData.Tables[SR.Trace_Server_Variables], true /*encodeSpaces*/); if (table != null) table.RenderControl(output); output.Write("<hr width=100% size=1 color=silver>\r\n\r\n"); output.Write(SR.GetString(SR.Error_Formatter_CLR_Build) + VersionInfo.ClrVersion + SR.GetString(SR.Error_Formatter_ASPNET_Build) + VersionInfo.EngineVersion + "\r\n\r\n"); output.Write("</font>\r\n\r\n"); output.Write("</span>\r\n</div>\r\n"); _isEnabled = oldEnabled; } } internal DataSet GetData() { return _requestData; } internal void VerifyStart() { // if we have already started, we can skip the lock if (_masterRequest == null) { // otherwise we need to make sure two // requests don't try to call InitMaster at the same time lock(this) { if (_masterRequest == null) InitMaster(); } } if (_requestData == null) { InitRequest(); } } internal void StopTracing() { _endDataCollected = true; } /* * Finalize the request */ internal void EndRequest() { VerifyStart(); if (_endDataCollected) return; // add some more information about the reponse DataRow row = _requestData.Tables[SR.Trace_Request].Rows[0]; row[SR.Trace_Status_Code] = _context.Response.StatusCode; row[SR.Trace_Response_Encoding] = _context.Response.ContentEncoding.EncodingName; IEnumerator en; string temp; object obj; int i; // Application State info _context.Application.Lock(); try { en = _context.Application.GetEnumerator(); while (en.MoveNext()) { row = NewRow(_requestData, SR.Trace_Application_State); temp = (string) en.Current; //the key might be null row[SR.Trace_Application_Key] = (temp != null) ? temp : NULLSTRING; obj = _context.Application[temp]; // the value could also be null if (obj != null) { row[SR.Trace_Type] = obj.GetType(); row[SR.Trace_Value] = obj.ToString(); } else { row[SR.Trace_Type] = NULLSTRING; row[SR.Trace_Value] = NULLSTRING; } AddRow(_requestData, SR.Trace_Application_State, row); } } finally { _context.Application.UnLock(); } // request cookie info HttpCookieCollection cookieCollection = new HttpCookieCollection(); _context.Request.FillInCookiesCollection(cookieCollection, false /*includeResponse */); HttpCookie[] cookies = new HttpCookie[cookieCollection.Count]; cookieCollection.CopyTo(cookies, 0); for (i = 0; i<cookies.Length; i++) { row = NewRow(_requestData, SR.Trace_Request_Cookies_Collection); row[SR.Trace_Name] = cookies[i].Name; if (cookies[i].Values.HasKeys()) { NameValueCollection subvalues = cookies[i].Values; StringBuilder sb = new StringBuilder(); en = subvalues.GetEnumerator(); while (en.MoveNext()) { temp = (string) en.Current; sb.Append("("); sb.Append(temp + "="); sb.Append(cookies[i][temp] + ") "); } row[SR.Trace_Value] = sb.ToString(); } else row[SR.Trace_Value] = cookies[i].Value; int size = (cookies[i].Name == null) ? 0 : cookies[i].Name.Length; size += (cookies[i].Value == null) ? 0 : cookies[i].Value.Length; row[SR.Trace_Size] = size + 1; // plus 1 for = AddRow(_requestData, SR.Trace_Request_Cookies_Collection, row); } // response cookie info cookies = new HttpCookie[_context.Response.Cookies.Count]; _context.Response.Cookies.CopyTo(cookies, 0); for (i = 0; i<cookies.Length; i++) { row = NewRow(_requestData, SR.Trace_Response_Cookies_Collection); row[SR.Trace_Name] = cookies[i].Name; if (cookies[i].Values.HasKeys()) { NameValueCollection subvalues = cookies[i].Values; StringBuilder sb = new StringBuilder(); en = subvalues.GetEnumerator(); while (en.MoveNext()) { temp = (string) en.Current; sb.Append("("); sb.Append(temp + "="); sb.Append(cookies[i][temp] + ") "); } row[SR.Trace_Value] = sb.ToString(); } else row[SR.Trace_Value] = cookies[i].Value; int size = (cookies[i].Name == null) ? 0 : cookies[i].Name.Length; size += (cookies[i].Value == null) ? 0 : cookies[i].Value.Length; row[SR.Trace_Size] = size + 1; // plus 1 for = AddRow(_requestData, SR.Trace_Response_Cookies_Collection, row); } HttpSessionState session = _context.Session; // session state info if (session != null) { row = _requestData.Tables[SR.Trace_Request].Rows[0]; try { row[SR.Trace_Session_Id] = HttpUtility.UrlEncode(session.SessionID); } catch { // VSWhidbey 527536 // Accessing SessionID can cause creation of the session id, this will throw in the // cross page post scenario, as the response has already been flushed when we try // to add the session cookie, since this is just trace output, we can just not set a session ID. // } en = session.GetEnumerator(); while (en.MoveNext()) { row = NewRow(_requestData, SR.Trace_Session_State); temp = (string) en.Current; // the key could be null row[SR.Trace_Session_Key] = (temp != null) ? temp : NULLSTRING; obj = session[temp]; // the value could also be null if (obj != null) { row[SR.Trace_Type] = obj.GetType(); row[SR.Trace_Value] = obj.ToString(); } else { row[SR.Trace_Type] = NULLSTRING; row[SR.Trace_Value] = NULLSTRING; } AddRow(_requestData, SR.Trace_Session_State, row); } } ApplyTraceMode(); OnTraceFinished(new TraceContextEventArgs(_traceRecords)); } /* InitMaster * Initialize the _masterRequest dataset with the schema we use * to store profiling information */ private void InitMaster() { DataSet tempset = new DataSet(); tempset.Locale = CultureInfo.InvariantCulture; // populate the _masterRequest's schema DataTable tab; Type strtype = typeof(string); Type inttype = typeof(int); Type doubletype = typeof(double); // request table tab = tempset.Tables.Add(SR.Trace_Request); tab.Columns.Add(SR.Trace_No, inttype); tab.Columns.Add(SR.Trace_Time_of_Request, strtype); tab.Columns.Add(SR.Trace_Url, strtype); tab.Columns.Add(SR.Trace_Request_Type, strtype); tab.Columns.Add(SR.Trace_Status_Code, inttype); tab.Columns.Add(SR.Trace_Session_Id, strtype); tab.Columns.Add(SR.Trace_Request_Encoding, strtype); tab.Columns.Add(SR.Trace_Response_Encoding, strtype); // control heirarchy table tab = tempset.Tables.Add(SR.Trace_Control_Tree); tab.Columns.Add(SR.Trace_Parent_Id, strtype); DataColumn[] col = new DataColumn[1]; col[0] = new DataColumn(SR.Trace_Control_Id, strtype); tab.Columns.Add(col[0]); tab.PrimaryKey = col; // set the control id to be the primary key tab.Columns.Add(SR.Trace_Type, strtype); tab.Columns.Add(SR.Trace_Render_Size, inttype); tab.Columns.Add(SR.Trace_Viewstate_Size, inttype); tab.Columns.Add(SR.Trace_Controlstate_Size, inttype); // session state table tab = tempset.Tables.Add(SR.Trace_Session_State); tab.Columns.Add(SR.Trace_Session_Key, strtype); tab.Columns.Add(SR.Trace_Type, strtype); tab.Columns.Add(SR.Trace_Value, strtype); // application state table tab = tempset.Tables.Add(SR.Trace_Application_State); tab.Columns.Add(SR.Trace_Application_Key, strtype); tab.Columns.Add(SR.Trace_Type, strtype); tab.Columns.Add(SR.Trace_Value, strtype); // request cookies table tab = tempset.Tables.Add(SR.Trace_Request_Cookies_Collection); tab.Columns.Add(SR.Trace_Name, strtype); tab.Columns.Add(SR.Trace_Value, strtype); tab.Columns.Add(SR.Trace_Size, inttype); // resposne cookies table tab = tempset.Tables.Add(SR.Trace_Response_Cookies_Collection); tab.Columns.Add(SR.Trace_Name, strtype); tab.Columns.Add(SR.Trace_Value, strtype); tab.Columns.Add(SR.Trace_Size, inttype); // header table tab = tempset.Tables.Add(SR.Trace_Headers_Collection); tab.Columns.Add(SR.Trace_Name, strtype); tab.Columns.Add(SR.Trace_Value, strtype); // response header table tab = tempset.Tables.Add(SR.Trace_Response_Headers_Collection); tab.Columns.Add(SR.Trace_Name, strtype); tab.Columns.Add(SR.Trace_Value, strtype); // form variables table tab = tempset.Tables.Add(SR.Trace_Form_Collection); tab.Columns.Add(SR.Trace_Name, strtype); tab.Columns.Add(SR.Trace_Value, strtype); // querystring table tab = tempset.Tables.Add(SR.Trace_Querystring_Collection); tab.Columns.Add(SR.Trace_Name, strtype); tab.Columns.Add(SR.Trace_Value, strtype); // trace info tab = tempset.Tables.Add(SR.Trace_Trace_Information); tab.Columns.Add(SR.Trace_Category, strtype); tab.Columns.Add(SR.Trace_Warning, strtype); tab.Columns.Add(SR.Trace_Message, strtype); tab.Columns.Add(SR.Trace_From_First, doubletype); tab.Columns.Add(SR.Trace_From_Last, doubletype); tab.Columns.Add("ErrorInfoMessage", strtype); tab.Columns.Add("ErrorInfoStack", strtype); // server variables tab = tempset.Tables.Add(SR.Trace_Server_Variables); tab.Columns.Add(SR.Trace_Name, strtype); tab.Columns.Add(SR.Trace_Value, strtype); _masterRequest = tempset; } private DataRow NewRow(DataSet ds, string table) { return ds.Tables[table].NewRow(); } private void AddRow(DataSet ds, string table, DataRow row) { ds.Tables[table].Rows.Add(row); } /* InitRequest * Initialize the given dataset with basic * request information */ private void InitRequest() { // Master request is assumed to be initialized first System.Web.Util.Debug.Assert(_masterRequest != null); DataSet requestData = _masterRequest.Clone(); // request info DataRow row = NewRow(requestData, SR.Trace_Request); row[SR.Trace_Time_of_Request] = _context.Timestamp.ToString("G"); string url = _context.Request.RawUrl; int loc = url.IndexOf("?", StringComparison.Ordinal); if (loc != -1) url = url.Substring(0, loc); row[SR.Trace_Url] = url; row[SR.Trace_Request_Type] = _context.Request.HttpMethod; try { row[SR.Trace_Request_Encoding] = _context.Request.ContentEncoding.EncodingName; } catch { // if we get an exception getting the ContentEncoding, most likely // there's an error in the config file. Just ignore it so we can finish InitRequest. } if (TraceMode == TraceMode.SortByCategory) requestData.Tables[SR.Trace_Trace_Information].DefaultView.Sort = SR.Trace_Category; AddRow(requestData, SR.Trace_Request, row); // header info try { // Bug 867196: Use Request.Unvalidated to ensure request validation will not // be triggered when the entries of the collection are accessed. AddCollectionToRequestData(requestData, SR.Trace_Headers_Collection, _context.Request.Unvalidated.Headers); } catch { // ---- exceptions when we fail to get the unvalidated collection } // response header info ArrayList headers = _context.Response.GenerateResponseHeaders(false); int n = (headers != null) ? headers.Count : 0; for (int i = 0; i < n; i++) { HttpResponseHeader h = (HttpResponseHeader)headers[i]; row = NewRow(requestData, SR.Trace_Response_Headers_Collection); row[SR.Trace_Name] = h.Name; row[SR.Trace_Value] = h.Value; AddRow(requestData, SR.Trace_Response_Headers_Collection, row); } //form info try { AddCollectionToRequestData(requestData, SR.Trace_Form_Collection, _context.Request.Unvalidated.Form); } catch { // ---- exceptions when we fail to get the unvalidated collection } //QueryString info try { AddCollectionToRequestData(requestData, SR.Trace_Querystring_Collection, _context.Request.Unvalidated.QueryString); } catch { // ---- exceptions when we fail to get the unvalidated collection } //Server Variable info if (HttpRuntime.HasAppPathDiscoveryPermission()) { AddCollectionToRequestData(requestData, SR.Trace_Server_Variables, _context.Request.ServerVariables); } _requestData = requestData; if (HttpRuntime.UseIntegratedPipeline) { // Dev10 914119: When trace is enabled, the request entity is read and no longer // available to IIS. In integrated mode, we have an API that allows us to reinsert // the entity. Although it is expensive, performance is not a concern when // trace is enalbed, so we will reinsert just in case a native handler needs // to access the entity. I decided not to check the current handler, since // that can be changed if someone sets the IIS script map. _context.Request.InsertEntityBody(); } } private void AddCollectionToRequestData(DataSet requestData, string traceCollectionTitle, NameValueCollection collection) { if (null != collection) { var keys = collection.AllKeys; for (int i = 0; i < keys.Length; i++) { var row = NewRow(requestData, traceCollectionTitle); row[SR.Trace_Name] = keys[i]; row[SR.Trace_Value] = collection[keys[i]]; AddRow(requestData, traceCollectionTitle, row); } } } } }
using UnityEngine; using UnityEditor; using System.IO; using System.Collections.Generic; using System.Xml; using System.Xml.Serialization; using PixelCrushers.DialogueSystem.Examples; namespace PixelCrushers.DialogueSystem.Editors { /// <summary> /// Player setup wizard. /// </summary> public class PlayerSetupWizard : EditorWindow { [MenuItem("Window/Dialogue System/Tools/Wizards/Player Setup Wizard", false, 1)] public static void Init() { (EditorWindow.GetWindow(typeof(PlayerSetupWizard), false, "Player Setup") as PlayerSetupWizard).minSize = new Vector2(700, 500); } // Private fields for the window: private enum Stage { SelectPC, Control, Camera, Targeting, Transition, Persistence, Review }; private Stage stage = Stage.SelectPC; private string[] stageLabels = new string[] { "Player", "Control", "Camera", "Targeting", "Transition", "Persistence", "Review" }; private const float ToggleWidth = 16; private GameObject pcObject = null; private bool setEnabledFlag = false; /// <summary> /// Draws the window. /// </summary> void OnGUI() { DrawProgressIndicator(); DrawCurrentStage(); } private void DrawProgressIndicator() { EditorGUI.BeginDisabledGroup(true); EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUILayout.Toolbar((int) stage, stageLabels, GUILayout.Width(700)); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); EditorGUI.EndDisabledGroup(); EditorWindowTools.DrawHorizontalLine(); } private void DrawNavigationButtons(bool backEnabled, bool nextEnabled, bool nextCloses) { GUILayout.FlexibleSpace(); EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Cancel", GUILayout.Width(100))) { this.Close(); } else if (backEnabled && GUILayout.Button("Back", GUILayout.Width(100))) { stage--; } else { EditorGUI.BeginDisabledGroup(!nextEnabled); if (GUILayout.Button(nextCloses ? "Finish" : "Next", GUILayout.Width(100))) { if (nextCloses) { Close(); } else { stage++; } } EditorGUI.EndDisabledGroup(); } EditorGUILayout.EndHorizontal(); EditorGUILayout.LabelField(string.Empty, GUILayout.Height(2)); } private void DrawCurrentStage() { if (pcObject == null) stage = Stage.SelectPC; switch (stage) { case Stage.SelectPC: DrawSelectPCStage(); break; case Stage.Control: DrawControlStage(); break; case Stage.Camera: DrawCameraStage(); break; case Stage.Targeting: DrawTargetingStage(); break; case Stage.Transition: DrawTransitionStage(); break; case Stage.Persistence: DrawPersistenceStage(); break; case Stage.Review: DrawReviewStage(); break; } } private void DrawSelectPCStage() { EditorGUILayout.LabelField("Select Player Object", EditorStyles.boldLabel); EditorWindowTools.StartIndentedSection(); EditorGUILayout.HelpBox("This wizard will help you configure a Player object to work with the Dialogue System. First, assign the Player's GameObject below.", MessageType.Info); pcObject = EditorGUILayout.ObjectField("Player Object", pcObject, typeof(GameObject), true) as GameObject; EditorWindowTools.EndIndentedSection(); DrawNavigationButtons(false, (pcObject != null), false); } private enum ControlStyle { ThirdPersonShooter, FollowMouseClicks, Custom }; private void DrawControlStage() { EditorGUILayout.LabelField("Control", EditorStyles.boldLabel); EditorWindowTools.StartIndentedSection(); SimpleController simpleController = pcObject.GetComponent<SimpleController>(); NavigateOnMouseClick navigateOnMouseClick = pcObject.GetComponent<NavigateOnMouseClick>(); ControlStyle controlStyle = (simpleController != null) ? ControlStyle.ThirdPersonShooter : (navigateOnMouseClick != null) ? ControlStyle.FollowMouseClicks : ControlStyle.Custom; EditorGUILayout.HelpBox("How will the player control movement? (Select Custom to provide your own control components instead of using the Dialogue System's.)", MessageType.Info); controlStyle = (ControlStyle) EditorGUILayout.EnumPopup("Control", controlStyle); switch (controlStyle) { case ControlStyle.ThirdPersonShooter: DestroyImmediate(navigateOnMouseClick); DrawSimpleControllerSection(simpleController ?? pcObject.AddComponent<SimpleController>()); break; case ControlStyle.FollowMouseClicks: DestroyImmediate(simpleController); DrawNavigateOnMouseClickSection(navigateOnMouseClick ?? pcObject.AddComponent<NavigateOnMouseClick>()); break; default: DestroyImmediate(simpleController); DestroyImmediate(navigateOnMouseClick); break; } if (GUILayout.Button("Select Player", GUILayout.Width(100))) Selection.activeGameObject = pcObject; EditorWindowTools.EndIndentedSection(); DrawNavigationButtons(true, true, false); } private void DrawSimpleControllerSection(SimpleController simpleController) { EditorWindowTools.StartIndentedSection(); if ((simpleController.idle == null) || (simpleController.runForward == null)) { EditorGUILayout.HelpBox("The player uses third-person shooter style controls. At a minimum, Idle and Run animations are required. Click Select Player to customize further.", MessageType.Info); } simpleController.idle = EditorGUILayout.ObjectField("Idle Animation", simpleController.idle, typeof(AnimationClip), false) as AnimationClip; simpleController.runForward = EditorGUILayout.ObjectField("Run Animation", simpleController.runForward, typeof(AnimationClip), false) as AnimationClip; EditorWindowTools.StartIndentedSection(); EditorGUILayout.LabelField("Optional", EditorStyles.boldLabel); simpleController.runSpeed = EditorGUILayout.FloatField("Run Speed", simpleController.runSpeed); simpleController.runBack = EditorGUILayout.ObjectField("Run Back", simpleController.runBack, typeof(AnimationClip), false) as AnimationClip; simpleController.aim = EditorGUILayout.ObjectField("Aim", simpleController.aim, typeof(AnimationClip), false) as AnimationClip; simpleController.fire = EditorGUILayout.ObjectField("Fire", simpleController.fire, typeof(AnimationClip), false) as AnimationClip; if (simpleController.fire != null) { if (simpleController.upperBodyMixingTransform == null) EditorGUILayout.HelpBox("Specify the upper body mixing transform for the fire animation.", MessageType.Info); simpleController.upperBodyMixingTransform = EditorGUILayout.ObjectField("Upper Body Transform", simpleController.upperBodyMixingTransform, typeof(Transform), true) as Transform; simpleController.fireLayerMask = EditorGUILayout.LayerField("Fire Layer", simpleController.fireLayerMask); simpleController.fireSound = EditorGUILayout.ObjectField("Fire Sound", simpleController.fireSound, typeof(AudioClip), false) as AudioClip; AudioSource audioSource = pcObject.GetComponent<AudioSource>(); if (audioSource == null) { audioSource = pcObject.AddComponent<AudioSource>(); audioSource.playOnAwake = false; audioSource.loop = false; } } EditorWindowTools.EndIndentedSection(); EditorWindowTools.EndIndentedSection(); } private void DrawNavigateOnMouseClickSection(NavigateOnMouseClick navigateOnMouseClick) { EditorWindowTools.StartIndentedSection(); if ((navigateOnMouseClick.idle == null) || (navigateOnMouseClick.run == null)) { EditorGUILayout.HelpBox("The player clicks on the map to move. At a minimum, Idle and Run animations are required. Click Select Player to customize further.", MessageType.Info); } navigateOnMouseClick.idle = EditorGUILayout.ObjectField("Idle Animation", navigateOnMouseClick.idle, typeof(AnimationClip), false) as AnimationClip; navigateOnMouseClick.run = EditorGUILayout.ObjectField("Run Animation", navigateOnMouseClick.run, typeof(AnimationClip), false) as AnimationClip; navigateOnMouseClick.mouseButton = (NavigateOnMouseClick.MouseButtonType) EditorGUILayout.EnumPopup("Mouse Button", navigateOnMouseClick.mouseButton); EditorWindowTools.EndIndentedSection(); } private void DrawCameraStage() { EditorGUILayout.LabelField("Camera", EditorStyles.boldLabel); EditorWindowTools.StartIndentedSection(); Camera playerCamera = pcObject.GetComponentInChildren<Camera>() ?? Camera.main; SmoothCameraWithBumper smoothCamera = (playerCamera != null) ? playerCamera.GetComponent<SmoothCameraWithBumper>() : null; EditorGUILayout.BeginHorizontal(); bool useSmoothCamera = EditorGUILayout.Toggle((smoothCamera != null) , GUILayout.Width(ToggleWidth)); EditorGUILayout.LabelField("Use Smooth Follow Camera", EditorStyles.boldLabel); EditorGUILayout.EndHorizontal(); if (useSmoothCamera) { if (playerCamera == null) { GameObject playerCameraObject = new GameObject("Player Camera"); playerCameraObject.transform.parent = pcObject.transform; playerCamera = playerCameraObject.AddComponent<Camera>(); playerCamera.tag = "MainCamera"; } smoothCamera = playerCamera.GetComponentInChildren<SmoothCameraWithBumper>() ?? playerCamera.gameObject.AddComponent<SmoothCameraWithBumper>(); EditorWindowTools.StartIndentedSection(); if (smoothCamera.target == null) { EditorGUILayout.HelpBox("Specify the transform (usually the head) that the camera should follow.", MessageType.Info); } smoothCamera.target = EditorGUILayout.ObjectField("Target", smoothCamera.target, typeof(Transform), true) as Transform; EditorWindowTools.EndIndentedSection(); } else { DestroyImmediate(smoothCamera); } if (GUILayout.Button("Select Camera", GUILayout.Width(100))) Selection.activeObject = playerCamera; EditorWindowTools.EndIndentedSection(); DrawNavigationButtons(true, true, false); } private void DrawTargetingStage() { EditorGUILayout.LabelField("Targeting", EditorStyles.boldLabel); EditorWindowTools.StartIndentedSection(); SelectorType selectorType = GetSelectorType(); if (selectorType == SelectorType.None) EditorGUILayout.HelpBox("Specify how the player will target NPCs to trigger conversations and barks.", MessageType.Info); selectorType = (SelectorType) EditorGUILayout.EnumPopup("Target NPCs By", selectorType); switch (selectorType) { case SelectorType.Proximity: DrawProximitySelector(); break; case SelectorType.CenterOfScreen: case SelectorType.MousePosition: case SelectorType.CustomPosition: DrawSelector(selectorType); break; default: DrawNoSelector(); break; } EditorWindowTools.EndIndentedSection(); EditorWindowTools.DrawHorizontalLine(); DrawOverrideNameSubsection(); if (GUILayout.Button("Select Player", GUILayout.Width(100))) Selection.activeGameObject = pcObject; DrawNavigationButtons(true, true, false); } private enum SelectorType { CenterOfScreen, MousePosition, Proximity, CustomPosition, None, }; private enum MouseButtonChoice { LeftMouseButton, RightMouseButton } private SelectorType GetSelectorType() { if (pcObject.GetComponent<ProximitySelector>() != null) { return SelectorType.Proximity; } else { Selector selector = pcObject.GetComponent<Selector>(); if (selector != null) { switch (selector.selectAt) { case Selector.SelectAt.CenterOfScreen: return SelectorType.CenterOfScreen; case Selector.SelectAt.MousePosition: return SelectorType.MousePosition; default: return SelectorType.CustomPosition; } } else { return SelectorType.None; } } } private void DrawNoSelector() { DestroyImmediate(pcObject.GetComponent<Selector>()); DestroyImmediate(pcObject.GetComponent<ProximitySelector>()); EditorWindowTools.StartIndentedSection(); EditorGUILayout.HelpBox("The player will not use a Dialogue System-provided targeting component.", MessageType.None); EditorWindowTools.EndIndentedSection(); } private void DrawProximitySelector() { DestroyImmediate(pcObject.GetComponent<Selector>()); ProximitySelector proximitySelector = pcObject.GetComponent<ProximitySelector>() ?? pcObject.AddComponent<ProximitySelector>(); EditorWindowTools.StartIndentedSection(); EditorGUILayout.HelpBox("The player can target usable objects (e.g., conversations on NPCs) when inside their trigger areas. Click Select Player Inspect to customize the Proximity Selector.", MessageType.None); proximitySelector.useKey = (KeyCode) EditorGUILayout.EnumPopup("'Use' Key", proximitySelector.useKey); proximitySelector.useButton = EditorGUILayout.TextField("'Use' Button", proximitySelector.useButton); EditorWindowTools.EndIndentedSection(); } private void DrawSelector(SelectorType selectorType) { DestroyImmediate(pcObject.GetComponent<ProximitySelector>()); Selector selector = pcObject.GetComponent<Selector>() ?? pcObject.AddComponent<Selector>(); EditorWindowTools.StartIndentedSection(); switch (selectorType) { case SelectorType.CenterOfScreen: EditorGUILayout.HelpBox("Usable objects in the center of the screen will be targeted.", MessageType.None); selector.selectAt = Selector.SelectAt.CenterOfScreen; break; case SelectorType.MousePosition: EditorGUILayout.HelpBox("Usable objects under the mouse cursor will be targeted. Specify which mouse button activates the targeted object.", MessageType.None); selector.selectAt = Selector.SelectAt.MousePosition; MouseButtonChoice mouseButtonChoice = string.Equals(selector.useButton, "Fire2") ? MouseButtonChoice.RightMouseButton : MouseButtonChoice.LeftMouseButton; mouseButtonChoice = (MouseButtonChoice) EditorGUILayout.EnumPopup("Select With", mouseButtonChoice); selector.useButton = (mouseButtonChoice == MouseButtonChoice.RightMouseButton) ? "Fire2" : "Fire1"; break; default: case SelectorType.CustomPosition: EditorGUILayout.HelpBox("Usable objects will be targeted at a custom screen position. You are responsible for setting the Selector component's CustomPosition property.", MessageType.None); selector.selectAt = Selector.SelectAt.CustomPosition; break; } if (selector.reticle != null) { selector.reticle.inRange = EditorGUILayout.ObjectField("In-Range Reticle", selector.reticle.inRange, typeof(Texture2D), false) as Texture2D; selector.reticle.outOfRange = EditorGUILayout.ObjectField("Out-of-Range Reticle", selector.reticle.outOfRange, typeof(Texture2D), false) as Texture2D; } selector.useKey = (KeyCode) EditorGUILayout.EnumPopup("'Use' Key", selector.useKey); selector.useButton = EditorGUILayout.TextField("'Use' Button", selector.useButton); EditorGUILayout.HelpBox("Click Select Player Inspect to customize the Selector.", MessageType.None); EditorWindowTools.EndIndentedSection(); } private void DrawOverrideNameSubsection() { NPCSetupWizard.DrawOverrideNameSubsection(pcObject); } private void DrawTransitionStage() { EditorGUILayout.LabelField("Gameplay/Conversation Transition", EditorStyles.boldLabel); EditorWindowTools.StartIndentedSection(); SetEnabledOnDialogueEvent setEnabled = pcObject.GetComponent<SetEnabledOnDialogueEvent>(); setEnabledFlag = setEnabledFlag || (setEnabled != null); if (!setEnabledFlag) EditorGUILayout.HelpBox("Gameplay components, such as movement and camera control, will interfere with conversations. If you want to disable gameplay components during conversations, tick the checkbox below.", MessageType.None); EditorGUILayout.BeginHorizontal(); setEnabledFlag = EditorGUILayout.Toggle(setEnabledFlag, GUILayout.Width(ToggleWidth)); EditorGUILayout.LabelField("Disable gameplay components during conversations", EditorStyles.boldLabel); EditorGUILayout.EndHorizontal(); DrawDisableControlsSection(); DrawShowCursorSection(); if (GUILayout.Button("Select Player", GUILayout.Width(100))) Selection.activeGameObject = pcObject; EditorWindowTools.EndIndentedSection(); DrawNavigationButtons(true, true, false); } private void DrawDisableControlsSection() { EditorWindowTools.StartIndentedSection(); SetEnabledOnDialogueEvent enabler = FindConversationEnabler(); if (setEnabledFlag) { if (enabler == null) enabler = pcObject.AddComponent<SetEnabledOnDialogueEvent>(); enabler.trigger = DialogueEvent.OnConversation; enabler.onStart = GetPlayerControls(enabler.onStart, Toggle.False); enabler.onEnd = GetPlayerControls(enabler.onEnd, Toggle.True); ShowDisabledComponents(enabler.onStart); } else { DestroyImmediate(enabler); } EditorWindowTools.EndIndentedSection(); } private SetEnabledOnDialogueEvent FindConversationEnabler() { foreach (var component in pcObject.GetComponents<SetEnabledOnDialogueEvent>()) { if (component.trigger == DialogueEvent.OnConversation) return component; } return null; } private void ShowDisabledComponents(SetEnabledOnDialogueEvent.SetEnabledAction[] actionList) { EditorGUILayout.LabelField("The following components will be disabled during conversations:"); EditorWindowTools.StartIndentedSection(); foreach (SetEnabledOnDialogueEvent.SetEnabledAction action in actionList) { if (action.target != null) { EditorGUILayout.LabelField(action.target.GetType().Name); } } EditorWindowTools.EndIndentedSection(); } private SetEnabledOnDialogueEvent.SetEnabledAction[] GetPlayerControls(SetEnabledOnDialogueEvent.SetEnabledAction[] oldList, Toggle state) { List<SetEnabledOnDialogueEvent.SetEnabledAction> actions = new List<SetEnabledOnDialogueEvent.SetEnabledAction>(); if (oldList != null) { actions.AddRange(oldList); } foreach (var component in pcObject.GetComponents<MonoBehaviour>()) { if (IsPlayerControlComponent(component) && !IsInActionList(actions, component)) { AddToActionList(actions, component, state); } } SmoothCameraWithBumper smoothCamera = pcObject.GetComponentInChildren<SmoothCameraWithBumper>(); if (smoothCamera == null) smoothCamera = Camera.main.GetComponent<SmoothCameraWithBumper>(); if ((smoothCamera != null) && !IsInActionList(actions, smoothCamera)) { AddToActionList(actions, smoothCamera, state); } actions.RemoveAll(a => ((a == null) || (a.target == null))); return actions.ToArray(); } private bool IsPlayerControlComponent(MonoBehaviour component) { return (component is Selector) || (component is ProximitySelector) || (component is SimpleController) || (component is NavigateOnMouseClick); } private bool IsInActionList(List<SetEnabledOnDialogueEvent.SetEnabledAction> actions, MonoBehaviour component) { return (actions.Find(a => (a.target == component)) != null); } private void AddToActionList(List<SetEnabledOnDialogueEvent.SetEnabledAction> actions, MonoBehaviour component, Toggle state) { SetEnabledOnDialogueEvent.SetEnabledAction newAction = new SetEnabledOnDialogueEvent.SetEnabledAction(); newAction.state = state; newAction.target = component; actions.Add(newAction); } private void DrawShowCursorSection() { EditorWindowTools.DrawHorizontalLine(); ShowCursorOnConversation showCursor = pcObject.GetComponent<ShowCursorOnConversation>(); bool showCursorFlag = (showCursor != null); if (!showCursorFlag) EditorGUILayout.HelpBox("If regular gameplay hides the mouse cursor, tick Show Mouse Cursor to enable it during conversations.", MessageType.Info); EditorGUILayout.BeginHorizontal(); showCursorFlag = EditorGUILayout.Toggle(showCursorFlag, GUILayout.Width(ToggleWidth)); EditorGUILayout.LabelField("Show mouse cursor during conversations", EditorStyles.boldLabel); EditorGUILayout.EndHorizontal(); if (showCursorFlag) { if (showCursor == null) showCursor = pcObject.AddComponent<ShowCursorOnConversation>(); } else { DestroyImmediate(showCursor); } } private void DrawPersistenceStage() { EditorGUILayout.LabelField("Persistence", EditorStyles.boldLabel); PersistentPositionData persistentPositionData = pcObject.GetComponent<PersistentPositionData>(); EditorWindowTools.StartIndentedSection(); if (persistentPositionData == null) EditorGUILayout.HelpBox("The player can be configured to record its position in the Dialogue System's Lua environment so it will be preserved when saving and loading games.", MessageType.Info); EditorGUILayout.BeginHorizontal(); bool hasPersistentPosition = EditorGUILayout.Toggle((persistentPositionData != null), GUILayout.Width(ToggleWidth)); EditorGUILayout.LabelField("Player records position for saved games", EditorStyles.boldLabel); EditorGUILayout.EndHorizontal(); if (hasPersistentPosition) { if (persistentPositionData == null) { persistentPositionData = pcObject.AddComponent<PersistentPositionData>(); persistentPositionData.overrideActorName = "Player"; } if (string.IsNullOrEmpty(persistentPositionData.overrideActorName)) { EditorGUILayout.HelpBox(string.Format("Position data will be saved to the Actor['{0}'] (the name of the GameObject) or the Override Actor Name if defined. You can override the name below.", pcObject.name), MessageType.None); } else { EditorGUILayout.HelpBox(string.Format("Position data will be saved to the Actor['{0}']. To use the name of the GameObject instead, clear the field below.", persistentPositionData.overrideActorName), MessageType.None); } persistentPositionData.overrideActorName = EditorGUILayout.TextField("Actor Name", persistentPositionData.overrideActorName); } else { DestroyImmediate(persistentPositionData); } EditorWindowTools.EndIndentedSection(); DrawNavigationButtons(true, true, false); } private void DrawReviewStage() { EditorGUILayout.LabelField("Review", EditorStyles.boldLabel); EditorWindowTools.StartIndentedSection(); EditorGUILayout.HelpBox("Your Player is ready! Below is a summary of the configuration.", MessageType.Info); SimpleController simpleController = pcObject.GetComponent<SimpleController>(); NavigateOnMouseClick navigateOnMouseClick = pcObject.GetComponent<NavigateOnMouseClick>(); if (simpleController != null) { EditorGUILayout.LabelField("Control: Third-Person Shooter Style"); } else if (navigateOnMouseClick != null) { EditorGUILayout.LabelField("Control: Follow Mouse Clicks"); } else { EditorGUILayout.LabelField("Control: Custom"); } switch (GetSelectorType()) { case SelectorType.CenterOfScreen: EditorGUILayout.LabelField("Targeting: Center of Screen"); break; case SelectorType.CustomPosition: EditorGUILayout.LabelField("Targeting: Custom Position (you must set Selector.CustomPosition)"); break; case SelectorType.MousePosition: EditorGUILayout.LabelField("Targeting: Mouse Position"); break; case SelectorType.Proximity: EditorGUILayout.LabelField("Targeting: Proximity"); break; default: EditorGUILayout.LabelField("Targeting: None"); break; } SetEnabledOnDialogueEvent enabler = FindConversationEnabler(); if (enabler != null) ShowDisabledComponents(enabler.onStart); ShowCursorOnConversation showCursor = pcObject.GetComponentInChildren<ShowCursorOnConversation>(); if (showCursor != null) EditorGUILayout.LabelField("Show Cursor During Conversations: Yes"); PersistentPositionData persistentPositionData = pcObject.GetComponentInChildren<PersistentPositionData>(); EditorGUILayout.LabelField(string.Format("Save Position: {0}", (persistentPositionData != null) ? "Yes" : "No")); EditorWindowTools.EndIndentedSection(); DrawNavigationButtons(true, true, true); } } }
// SPDX-License-Identifier: MIT // Copyright [email protected] // Copyright iced contributors using System; using System.Collections.Generic; using System.Linq; using Generator.Constants; using Generator.Enums; using Generator.Enums.InstructionInfo; using Generator.IO; using Generator.Tables; namespace Generator.InstructionInfo { abstract class InstrInfoGenerator { protected abstract void Generate(EnumType enumType); protected abstract void Generate(ConstantsType constantsType); protected abstract void Generate((InstructionDef def, uint dword1, uint dword2)[] infos); protected abstract void Generate(EnumValue[] enumValues, RflagsBits[] read, RflagsBits[] undefined, RflagsBits[] written, RflagsBits[] cleared, RflagsBits[] set, RflagsBits[] modified); protected abstract void Generate((EnumValue cpuidInternal, EnumValue[] cpuidFeatures)[] cpuidFeatures); protected abstract void GenerateImpliedAccesses(ImpliedAccessesDef[] defs); protected abstract void GenerateIgnoresSegmentTable((EncodingKind encoding, InstructionDef[] defs)[] defs); protected abstract void GenerateIgnoresIndexTable((EncodingKind encoding, InstructionDef[] defs)[] defs); protected abstract void GenerateTileStrideIndexTable((EncodingKind encoding, InstructionDef[] defs)[] defs); protected abstract void GenerateFpuStackIncrementInfoTable((FpuStackInfo info, InstructionDef[] defs)[] defs); protected abstract void GenerateStackPointerIncrementTable((EncodingKind encoding, StackInfo info, InstructionDef[] defs)[] defs); protected abstract void GenerateCore(); protected readonly GenTypes genTypes; protected readonly InstrInfoTypes instrInfoTypes; protected readonly struct FpuStackInfo : IEquatable<FpuStackInfo>, IComparable<FpuStackInfo> { public readonly int Increment; public readonly bool Conditional; public readonly bool WritesTop; public FpuStackInfo(InstructionDef def) { Increment = def.FpuStackIncrement; Conditional = (def.Flags3 & InstructionDefFlags3.IsFpuCondWriteTop) != 0; WritesTop = (def.Flags3 & InstructionDefFlags3.WritesFpuTop) != 0; } public override bool Equals(object? obj) => obj is FpuStackInfo info && Equals(info); public bool Equals(FpuStackInfo other) => Increment == other.Increment && Conditional == other.Conditional && WritesTop == other.WritesTop; public override int GetHashCode() => HashCode.Combine(Increment, Conditional, WritesTop); public int CompareTo(FpuStackInfo other) { int c = Increment.CompareTo(other.Increment); if (c != 0) return c; c = Conditional.CompareTo(other.Conditional); if (c != 0) return c; return WritesTop.CompareTo(other.WritesTop); } } protected InstrInfoGenerator(GenTypes genTypes) { this.genTypes = genTypes; instrInfoTypes = genTypes.GetObject<InstrInfoTypes>(TypeIds.InstrInfoTypes); } public void Generate() { var enumTypes = new List<EnumType> { genTypes[TypeIds.ImpliedAccess], genTypes[TypeIds.RflagsInfo], genTypes[TypeIds.InfoFlags1], genTypes[TypeIds.InfoFlags2], genTypes[TypeIds.CpuidFeatureInternal], }; enumTypes.AddRange(instrInfoTypes.EnumOpInfos); foreach (var enumType in enumTypes) Generate(enumType); var constantsTypes = new ConstantsType[] { genTypes.GetConstantsType(TypeIds.InstrInfoConstants), }; foreach (var constantsType in constantsTypes) Generate(constantsType); var defs = genTypes.GetObject<InstructionDefs>(TypeIds.InstructionDefs).Defs; GenerateImpliedAccesses(genTypes.GetObject<InstructionDefs>(TypeIds.InstructionDefs).ImpliedAccessesDefs); static (EncodingKind encoding, InstructionDef[] defs)[] GetDefs(IEnumerable<InstructionDef> defs) => defs.GroupBy(a => a.Encoding, (a, b) => (encoding: a, b.OrderBy(a => a.Code.Value).ToArray())).OrderBy(a => a.encoding).ToArray(); GenerateIgnoresSegmentTable(GetDefs(defs.Where(a => (a.Flags1 & InstructionDefFlags1.IgnoresSegment) != 0))); GenerateIgnoresIndexTable(GetDefs(defs.Where(a => (a.Flags3 & InstructionDefFlags3.IgnoresIndex) != 0))); GenerateTileStrideIndexTable(GetDefs(defs.Where(a => (a.Flags3 & InstructionDefFlags3.TileStrideIndex) != 0))); var fpuDefs = defs. Where(a => a.FpuStackIncrement != 0 || (a.Flags3 & (InstructionDefFlags3.IsFpuCondWriteTop | InstructionDefFlags3.WritesFpuTop)) != 0). GroupBy(a => new FpuStackInfo(a), (a, b) => (info: a, b.OrderBy(a => a.Code.Value).ToArray())). OrderBy(a => a.info).ToArray(); GenerateFpuStackIncrementInfoTable(fpuDefs); var stackDefs = defs. Where(a => a.StackInfo.Kind != StackInfoKind.None). GroupBy(a => (encoding: a.Encoding, info: a.StackInfo), (a, b) => (a.encoding, a.info, b.OrderBy(a => a.Code.Value).ToArray())). OrderBy(a => (a.encoding, a.info)).ToArray(); GenerateStackPointerIncrementTable(stackDefs); { var shifts = new int[IcedConstants.MaxOpCount] { (int)genTypes[TypeIds.InfoFlags1]["OpInfo0Shift"].Value, (int)genTypes[TypeIds.InfoFlags1]["OpInfo1Shift"].Value, (int)genTypes[TypeIds.InfoFlags1]["OpInfo2Shift"].Value, (int)genTypes[TypeIds.InfoFlags1]["OpInfo3Shift"].Value, (int)genTypes[TypeIds.InfoFlags1]["OpInfo4Shift"].Value, }; var infos = new (InstructionDef def, uint dword1, uint dword2)[defs.Length]; for (int i = 0; i < defs.Length; i++) { var def = defs[i]; uint dword1 = 0; uint dword2 = 0; for (int j = 0; j < def.OpInfoEnum.Length; j++) dword1 |= def.OpInfoEnum[j].Value << shifts[j]; var rflagsInfo = def.RflagsInfo ?? throw new InvalidOperationException(); if (rflagsInfo.Value > (uint)InfoFlags1.RflagsInfoMask) throw new InvalidOperationException(); dword1 |= rflagsInfo.Value << (int)InfoFlags1.RflagsInfoShift; if (def.ImpliedAccessDef.EnumValue.Value > (uint)InfoFlags1.ImpliedAccessMask) throw new InvalidOperationException(); dword1 |= def.ImpliedAccessDef.EnumValue.Value << (int)InfoFlags1.ImpliedAccessShift; // TILELOADD{,T1}, TILESTORED: the index reg is the stride indicator. The real index is tilecfg.start_row if ((def.Flags3 & InstructionDefFlags3.TileStrideIndex) != 0) dword1 |= (uint)InfoFlags1.IgnoresIndexVA; if ((def.Flags1 & InstructionDefFlags1.OpMaskReadWrite) != 0) dword1 |= (uint)InfoFlags1.OpMaskReadWrite; if ((def.Flags1 & InstructionDefFlags1.IgnoresSegment) != 0) dword1 |= (uint)InfoFlags1.IgnoresSegment; if (def.EncodingValue.Value > (uint)InfoFlags2.EncodingMask) throw new InvalidOperationException(); dword2 |= def.EncodingValue.Value << (int)InfoFlags2.EncodingShift; if ((def.Flags1 & InstructionDefFlags1.SaveRestore) != 0) dword2 |= (uint)InfoFlags2.SaveRestore; if ((def.Flags1 & InstructionDefFlags1.StackInstruction) != 0) dword2 |= (uint)InfoFlags2.StackInstruction; if ((def.Flags3 & InstructionDefFlags3.Privileged) != 0) dword2 |= (uint)InfoFlags2.Privileged; if (def.ControlFlow.Value > (uint)InfoFlags2.FlowControlMask) throw new InvalidOperationException(); dword2 |= def.ControlFlow.Value << (int)InfoFlags2.FlowControlShift; var cpuidInternal = def.CpuidInternal ?? throw new InvalidOperationException(); if (cpuidInternal.Value > (uint)InfoFlags2.CpuidFeatureInternalMask) throw new InvalidOperationException(); dword2 |= cpuidInternal.Value << (int)InfoFlags2.CpuidFeatureInternalShift; infos[i] = (def, dword1, dword2); } Generate(infos); } { var rflagsInfos = instrInfoTypes.RflagsInfos; var enumValues = new EnumValue[rflagsInfos.Length]; var read = new RflagsBits[rflagsInfos.Length]; var undefined = new RflagsBits[rflagsInfos.Length]; var written = new RflagsBits[rflagsInfos.Length]; var cleared = new RflagsBits[rflagsInfos.Length]; var set = new RflagsBits[rflagsInfos.Length]; var modified = new RflagsBits[rflagsInfos.Length]; for (int i = 0; i < rflagsInfos.Length; i++) { var rflags = rflagsInfos[i].rflags; enumValues[i] = rflagsInfos[i].value; read[i] = rflags.read; undefined[i] = rflags.undefined; written[i] = rflags.written; cleared[i] = rflags.cleared; set[i] = rflags.set; modified[i] = rflags.undefined | rflags.written | rflags.cleared | rflags.set; } Generate(enumValues, read, undefined, written, cleared, set, modified); } Generate(instrInfoTypes.CpuidFeatures); GenerateCore(); } protected EnumValue ToOpAccess(EnumValue opInfo) { if (opInfo.RawName == nameof(OpInfo.ReadP3)) return genTypes[TypeIds.OpAccess][nameof(OpAccess.Read)]; if (opInfo.RawName == nameof(OpInfo.WriteForceP1)) return genTypes[TypeIds.OpAccess][nameof(OpAccess.Write)]; return genTypes[TypeIds.OpAccess][opInfo.RawName]; } protected struct StmtState { readonly string regBegin; readonly string regEnd; readonly string memBegin; readonly string memEnd; StmtKind stmtKind; FileWriter.Indenter? indenter; public StmtState(string regBegin, string regEnd, string memBegin, string memEnd) { this.regBegin = regBegin; this.regEnd = regEnd; this.memBegin = memBegin; this.memEnd = memEnd; stmtKind = StmtKind.Other; indenter = null; } enum StmtKind { Other, Register, Memory, } public void Done(FileWriter writer) => SetKind(writer, StmtKind.Other); public void SetKind(FileWriter writer, ImplAccStatementKind kind) => SetKind(writer, GetStmtKind(kind)); void SetKind(FileWriter writer, StmtKind kind) { if (kind == stmtKind) return; indenter?.Dispose(); indenter = null; switch (stmtKind) { case StmtKind.Other: break; case StmtKind.Register: writer.WriteLine(regEnd); break; case StmtKind.Memory: writer.WriteLine(memEnd); break; default: throw new InvalidOperationException(); } switch (kind) { case StmtKind.Other: break; case StmtKind.Register: writer.WriteLine(regBegin); indenter = writer.Indent(); break; case StmtKind.Memory: writer.WriteLine(memBegin); indenter = writer.Indent(); break; default: throw new InvalidOperationException(); } stmtKind = kind; } static StmtKind GetStmtKind(ImplAccStatementKind kind) => kind switch { ImplAccStatementKind.MemoryAccess => StmtKind.Memory, ImplAccStatementKind.RegisterAccess or ImplAccStatementKind.RegisterRangeAccess => StmtKind.Register, _ => StmtKind.Other, }; } protected static bool CouldBeNullSegIn64BitMode(ImplAccRegister register, out bool definitelyNullSeg) { definitelyNullSeg = false; switch (register.Kind) { case ImplAccRegisterKind.Register: switch ((Register)register.Register!.Value) { case Register.ES: case Register.CS: case Register.SS: case Register.DS: definitelyNullSeg = true; return true; } return false; case ImplAccRegisterKind.SegmentDefaultDS: return true; case ImplAccRegisterKind.a_rDI: case ImplAccRegisterKind.Op0: case ImplAccRegisterKind.Op1: case ImplAccRegisterKind.Op2: case ImplAccRegisterKind.Op3: case ImplAccRegisterKind.Op4: return false; default: throw new InvalidOperationException(); } } protected static uint Verify_9_or_17(uint value) => value switch { 9 or 17 => value, _ => throw new InvalidOperationException(), }; protected static uint Verify_2_4_or_8(uint value) => value switch { 2 or 4 or 8 => value, _ => throw new InvalidOperationException(), }; protected static uint Verify_2_or_4(uint value) => value switch { 2 or 4 => value, _ => throw new InvalidOperationException(), }; protected static EnumValue GetOpAccess(EnumType opAccessType, EmmiAccess access) => access switch { EmmiAccess.Read => opAccessType[nameof(OpAccess.Read)], EmmiAccess.Write => opAccessType[nameof(OpAccess.Write)], EmmiAccess.ReadWrite => opAccessType[nameof(OpAccess.ReadWrite)], _ => throw new InvalidOperationException(), }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; namespace System.Drawing.Internal { [SuppressUnmanagedCodeSecurity] internal static partial class IntUnsafeNativeMethods { [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetDC", CharSet = CharSet.Auto)] public static extern IntPtr IntGetDC(HandleRef hWnd); public static IntPtr GetDC(HandleRef hWnd) { IntPtr hdc = System.Internal.HandleCollector.Add(IntGetDC(hWnd), IntSafeNativeMethods.CommonHandles.HDC); DbgUtil.AssertWin32(hdc != IntPtr.Zero, "GetHdc([hWnd=0x{0:X8}]) failed.", hWnd); return hdc; } /// <summary> /// NOTE: DeleteDC is to be used to delete the hdc created from CreateCompatibleDC ONLY. All other hdcs should /// be deleted with DeleteHDC. /// </summary> [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "DeleteDC", CharSet = CharSet.Auto)] public static extern bool IntDeleteDC(HandleRef hDC); public static bool DeleteDC(HandleRef hDC) { System.Internal.HandleCollector.Remove((IntPtr)hDC, IntSafeNativeMethods.CommonHandles.GDI); bool retVal = IntDeleteDC(hDC); DbgUtil.AssertWin32(retVal, "DeleteDC([hdc=0x{0:X8}]) failed.", hDC.Handle); return retVal; } public static bool DeleteHDC(HandleRef hDC) { System.Internal.HandleCollector.Remove((IntPtr)hDC, IntSafeNativeMethods.CommonHandles.HDC); bool retVal = IntDeleteDC(hDC); DbgUtil.AssertWin32(retVal, "DeleteHDC([hdc=0x{0:X8}]) failed.", hDC.Handle); return retVal; } [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, EntryPoint = "ReleaseDC", CharSet = CharSet.Auto)] public static extern int IntReleaseDC(HandleRef hWnd, HandleRef hDC); public static int ReleaseDC(HandleRef hWnd, HandleRef hDC) { System.Internal.HandleCollector.Remove((IntPtr)hDC, IntSafeNativeMethods.CommonHandles.HDC); // Note: retVal == 0 means it was not released but doesn't necessarily means an error; class or private DCs are never released. return IntReleaseDC(hWnd, hDC); } [DllImport(ExternDll.Gdi32, SetLastError = true, EntryPoint = "CreateDC", CharSet = CharSet.Auto)] public static extern IntPtr IntCreateDC(string lpszDriverName, string lpszDeviceName, string lpszOutput, HandleRef /*DEVMODE*/ lpInitData); public static IntPtr CreateDC(string lpszDriverName, string lpszDeviceName, string lpszOutput, HandleRef /*DEVMODE*/ lpInitData) { IntPtr hdc = System.Internal.HandleCollector.Add(IntCreateDC(lpszDriverName, lpszDeviceName, lpszOutput, lpInitData), IntSafeNativeMethods.CommonHandles.HDC); DbgUtil.AssertWin32(hdc != IntPtr.Zero, "CreateDC([driverName={0}], [deviceName={1}], [fileName={2}], [devMode={3}]) failed.", lpszDriverName, lpszDeviceName, lpszOutput, lpInitData.Handle); return hdc; } [DllImport(ExternDll.Gdi32, SetLastError = true, EntryPoint = "CreateIC", CharSet = CharSet.Auto)] public static extern IntPtr IntCreateIC(string lpszDriverName, string lpszDeviceName, string lpszOutput, HandleRef /*DEVMODE*/ lpInitData); public static IntPtr CreateIC(string lpszDriverName, string lpszDeviceName, string lpszOutput, HandleRef /*DEVMODE*/ lpInitData) { IntPtr hdc = System.Internal.HandleCollector.Add(IntCreateIC(lpszDriverName, lpszDeviceName, lpszOutput, lpInitData), IntSafeNativeMethods.CommonHandles.HDC); DbgUtil.AssertWin32(hdc != IntPtr.Zero, "CreateIC([driverName={0}], [deviceName={1}], [fileName={2}], [devMode={3}]) failed.", lpszDriverName, lpszDeviceName, lpszOutput, lpInitData.Handle); return hdc; } /// <summary> /// CreateCompatibleDC requires to add a GDI handle instead of an HDC handle to avoid perf penalty in HandleCollector. /// The hdc obtained from this method needs to be deleted with DeleteDC instead of DeleteHDC. /// </summary> [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreateCompatibleDC", CharSet = CharSet.Auto)] public static extern IntPtr IntCreateCompatibleDC(HandleRef hDC); public static IntPtr CreateCompatibleDC(HandleRef hDC) { IntPtr compatibleDc = System.Internal.HandleCollector.Add(IntCreateCompatibleDC(hDC), IntSafeNativeMethods.CommonHandles.GDI); DbgUtil.AssertWin32(compatibleDc != IntPtr.Zero, "CreateCompatibleDC([hdc=0x{0:X8}]) failed", hDC.Handle); return compatibleDc; } [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "SaveDC", CharSet = CharSet.Auto)] public static extern int IntSaveDC(HandleRef hDC); public static int SaveDC(HandleRef hDC) { int state = IntSaveDC(hDC); DbgUtil.AssertWin32(state != 0, "SaveDC([hdc=0x{0:X8}]) failed", hDC.Handle); return state; } [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "RestoreDC", CharSet = CharSet.Auto)] public static extern bool IntRestoreDC(HandleRef hDC, int nSavedDC); public static bool RestoreDC(HandleRef hDC, int nSavedDC) { bool retVal = IntRestoreDC(hDC, nSavedDC); // When a winforms app is closing, the cached MeasurementGraphics is finalized but it is possible that // its DeviceContext is finalized first so when this method is called the DC has already been relesaed poping up the // assert window. Need to find a way to work around this and enable the assert IF NEEDED. // DbgUtil.AssertWin32(retVal, "RestoreDC([hdc=0x{0:X8}], [restoreState={1}]) failed.", (int)hDC.Handle, nSavedDC); return retVal; } [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true)] public static extern IntPtr WindowFromDC(HandleRef hDC); [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "OffsetViewportOrgEx", CharSet = CharSet.Auto)] public static extern bool IntOffsetViewportOrgEx(HandleRef hDC, int nXOffset, int nYOffset, [In, Out] IntNativeMethods.POINT point); public static bool OffsetViewportOrgEx(HandleRef hDC, int nXOffset, int nYOffset, [In, Out] IntNativeMethods.POINT point) { bool retVal = IntOffsetViewportOrgEx(hDC, nXOffset, nYOffset, point); DbgUtil.AssertWin32(retVal, "OffsetViewportOrgEx([hdc=0x{0:X8}], dx=[{1}], dy=[{2}], [out pPoint]) failed.", hDC.Handle, nXOffset, nYOffset); return retVal; } // Region. [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CombineRgn", CharSet = CharSet.Auto)] public static extern IntNativeMethods.RegionFlags IntCombineRgn(HandleRef hRgnDest, HandleRef hRgnSrc1, HandleRef hRgnSrc2, RegionCombineMode combineMode); public static IntNativeMethods.RegionFlags CombineRgn(HandleRef hRgnDest, HandleRef hRgnSrc1, HandleRef hRgnSrc2, RegionCombineMode combineMode) { Debug.Assert(hRgnDest.Wrapper != null && hRgnDest.Handle != IntPtr.Zero, "Destination region is invalid"); Debug.Assert(hRgnSrc1.Wrapper != null && hRgnSrc1.Handle != IntPtr.Zero, "Source region 1 is invalid"); Debug.Assert(hRgnSrc2.Wrapper != null && hRgnSrc2.Handle != IntPtr.Zero, "Source region 2 is invalid"); if (hRgnDest.Wrapper == null || hRgnSrc1.Wrapper == null || hRgnSrc2.Wrapper == null) { return IntNativeMethods.RegionFlags.ERROR; } // Note: CombineRgn can return Error when no regions are combined, this is not an error condition. return IntCombineRgn(hRgnDest, hRgnSrc1, hRgnSrc2, combineMode); } [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetClipRgn", CharSet = CharSet.Auto)] public static extern int IntGetClipRgn(HandleRef hDC, HandleRef hRgn); public static int GetClipRgn(HandleRef hDC, HandleRef hRgn) { int retVal = IntGetClipRgn(hDC, hRgn); DbgUtil.AssertWin32(retVal != -1, "IntGetClipRgn([hdc=0x{0:X8}], [hRgn]) failed.", hDC.Handle); return retVal; } [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "SelectClipRgn", CharSet = CharSet.Auto)] public static extern IntNativeMethods.RegionFlags IntSelectClipRgn(HandleRef hDC, HandleRef hRgn); public static IntNativeMethods.RegionFlags SelectClipRgn(HandleRef hDC, HandleRef hRgn) { IntNativeMethods.RegionFlags result = IntSelectClipRgn(hDC, hRgn); DbgUtil.AssertWin32(result != IntNativeMethods.RegionFlags.ERROR, "SelectClipRgn([hdc=0x{0:X8}], [hRegion=0x{1:X8}]) failed.", hDC.Handle, hRgn.Handle); return result; } [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetRgnBox", CharSet = CharSet.Auto)] public static extern IntNativeMethods.RegionFlags IntGetRgnBox(HandleRef hRgn, [In, Out] ref IntNativeMethods.RECT clipRect); public static IntNativeMethods.RegionFlags GetRgnBox(HandleRef hRgn, [In, Out] ref IntNativeMethods.RECT clipRect) { IntNativeMethods.RegionFlags result = IntGetRgnBox(hRgn, ref clipRect); DbgUtil.AssertWin32(result != IntNativeMethods.RegionFlags.ERROR, "GetRgnBox([hRegion=0x{0:X8}], [out rect]) failed.", hRgn.Handle); return result; } // Font. [DllImport(ExternDll.Gdi32, SetLastError = true, EntryPoint = "CreateFontIndirect", CharSet = CharSet.Auto)] #pragma warning disable CS0618 // Legacy code: We don't care about using obsolete API's. public static extern IntPtr IntCreateFontIndirect([In, Out, MarshalAs(UnmanagedType.AsAny)] object lf); // need object here since LOGFONT is not public. #pragma warning restore CS0618 // Common. [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "DeleteObject", CharSet = CharSet.Auto)] public static extern bool IntDeleteObject(HandleRef hObject); public static bool DeleteObject(HandleRef hObject) { System.Internal.HandleCollector.Remove((IntPtr)hObject, IntSafeNativeMethods.CommonHandles.GDI); bool retVal = IntDeleteObject(hObject); DbgUtil.AssertWin32(retVal, "DeleteObject(hObj=[0x{0:X8}]) failed.", hObject.Handle); return retVal; } [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetCurrentObject", CharSet = CharSet.Auto)] public static extern IntPtr IntGetCurrentObject(HandleRef hDC, int uObjectType); public static IntPtr GetCurrentObject(HandleRef hDC, int uObjectType) { IntPtr hGdiObj = IntGetCurrentObject(hDC, uObjectType); // If the selected object is a region the return value is HGI_ERROR on failure. DbgUtil.AssertWin32(hGdiObj != IntPtr.Zero, "GetObject(hdc=[0x{0:X8}], type=[{1}]) failed.", hDC, uObjectType); return hGdiObj; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Xunit; using Xunit.Sdk; namespace Tests.Collections { public abstract class ICollectionTest<T> : IEnumerableTest<T> { private readonly bool _expectedIsSynchronized; protected ICollectionTest(bool isSynchronized) { _expectedIsSynchronized = isSynchronized; ValidArrayTypes = new[] {typeof (object)}; InvalidArrayTypes = new[] { typeof (MyInvalidReferenceType), typeof (MyInvalidValueType) }; } protected Type[] ValidArrayTypes { get; set; } protected Type[] InvalidArrayTypes { get; set; } protected abstract bool ItemsMustBeUnique { get; } protected abstract bool ItemsMustBeNonNull { get; } protected bool ExpectedIsSynchronized { get { return _expectedIsSynchronized; } } protected virtual bool CopyToOnlySupportsZeroLowerBounds { get { return true; } } protected ICollection GetCollection(object[] items) { IEnumerable obj = GetEnumerable(items); Assert.IsAssignableFrom<ICollection>(obj); return (ICollection) obj; } [Fact] public void Count() { object[] items = GenerateItems(16); ICollection collection = GetCollection(items); Assert.Equal(items.Length, collection.Count); } [Fact] public void IsSynchronized() { ICollection collection = GetCollection(GenerateItems(16)); Assert.Equal( ExpectedIsSynchronized, collection.IsSynchronized); } [Fact] public void SyncRootNonNull() { ICollection collection = GetCollection(GenerateItems(16)); Assert.NotNull(collection.SyncRoot); } [Fact] public void SyncRootConsistent() { ICollection collection = GetCollection(GenerateItems(16)); object syncRoot1 = collection.SyncRoot; object syncRoot2 = collection.SyncRoot; Assert.Equal(syncRoot1, syncRoot2); } [Fact] public void SyncRootCanBeLocked() { ICollection collection = GetCollection(GenerateItems(16)); lock (collection.SyncRoot) { } } [Fact] public void SyncRootUnique() { ICollection collection1 = GetCollection(GenerateItems(16)); ICollection collection2 = GetCollection(GenerateItems(16)); Assert.NotEqual(collection1.SyncRoot, collection2.SyncRoot); } [Fact] public void CopyToNull() { ICollection collection = GetCollection(GenerateItems(16)); Assert.Throws<ArgumentNullException>( () => collection.CopyTo(null, 0)); } [Theory] [InlineData(int.MinValue)] [InlineData(-1)] [InlineData(int.MaxValue)] public void CopyToBadIndex(int index) { object[] items = GenerateItems(16); ICollection collection = GetCollection(items); var items2 = (object[]) items.Clone(); Assert.ThrowsAny<ArgumentException>( () => collection.CopyTo(items2, index)); CollectionAssert.Equal(items, items2); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNonZeroLowerBoundArraySupported))] public void CopyToArrayWithNonZeroBounds() { object[] items = GenerateItems(16); ICollection collection = GetCollection(items); if (CopyToOnlySupportsZeroLowerBounds) { Array itemArray = Array.CreateInstance( typeof (object), new[] {collection.Count + 8}, new[] {-4}); var tempItemArray = (Array) itemArray.Clone(); Assert.Throws<ArgumentException>( () => collection.CopyTo(itemArray, 0)); CollectionAssert.Equal(tempItemArray, itemArray); } else { Array itemArray = Array.CreateInstance( typeof (object), new[] {collection.Count + 4}, new[] {-4}); var tempItemArray = (Array) itemArray.Clone(); Assert.Throws<ArgumentException>( () => collection.CopyTo(itemArray, 1)); CollectionAssert.Equal(tempItemArray, itemArray); itemArray = Array.CreateInstance( typeof (object), new[] {collection.Count + 4}, new[] {-6}); tempItemArray = (Array) itemArray.Clone(); Assert.Throws<ArgumentException>( () => collection.CopyTo(itemArray, -1)); CollectionAssert.Equal(tempItemArray, itemArray); } } [Fact] public void CopyToIndexArrayLength() { object[] items = GenerateItems(16); ICollection collection = GetCollection(items); var tempArray = (object[]) items.Clone(); Assert.Throws<ArgumentException>( () => collection.CopyTo(items, collection.Count)); CollectionAssert.Equal(tempArray, items); } [Fact] public void CopyToCollectionLargerThanArray() { object[] items = GenerateItems(16); ICollection collection = GetCollection(items); object[] itemArray = GenerateItems(collection.Count + 1); var tempItemArray = (object[]) itemArray.Clone(); Assert.Throws<ArgumentException>( () => collection.CopyTo(itemArray, 2)); CollectionAssert.Equal(tempItemArray, itemArray); } [Fact] public void CopyToMDArray() { object[] items = GenerateItems(16); ICollection collection = GetCollection(items); Assert.Throws<ArgumentException>( () => collection.CopyTo(new object[1, collection.Count], 0)); } protected void AssertThrows( Type[] exceptionTypes, Action testCode) { Exception exception = Record.Exception(testCode); if (exception == null) { throw new AssertActualExpectedException( exceptionTypes, null, "Expected an exception but got null."); } Type exceptionType = exception.GetType(); if (!exceptionTypes.Contains(exceptionType)) { throw new AssertActualExpectedException( exceptionTypes, exceptionType, "Caught wrong exception."); } } [Fact] public void CopyToInvalidTypes() { object[] items = GenerateItems(16); ICollection collection = GetCollection(items); Type[] expectedExceptionTypes = IsGenericCompatibility ? new[] { typeof ( ArgumentException), typeof ( InvalidCastException ) } : new[] { typeof ( ArgumentException) }; foreach (Type type in InvalidArrayTypes) { Array itemArray = Array.CreateInstance( type, collection.Count); var tempItemArray = (Array) itemArray.Clone(); AssertThrows( expectedExceptionTypes, () => collection.CopyTo(itemArray, 0)); CollectionAssert.Equal(tempItemArray, itemArray); } } [Theory] [InlineData(16, 20, -5, -1)] [InlineData(16, 21, -4, 1)] [InlineData(16, 20, 0, 0)] [InlineData(16, 20, 0, 4)] [InlineData(16, 24, 0, 4)] public void CopyTo( int size, int arraySize, int arrayLowerBound, int copyToIndex) { if (arrayLowerBound != 0 && !PlatformDetection.IsNonZeroLowerBoundArraySupported) return; object[] items = GenerateItems(16); ICollection collection = GetCollection(items); Array itemArray = Array.CreateInstance( typeof (object), new[] {arraySize}, new[] {arrayLowerBound}); var tempItemArray = (Array) itemArray.Clone(); if (CopyToOnlySupportsZeroLowerBounds && arrayLowerBound != 0) { Assert.Throws<ArgumentException>( () => collection.CopyTo(itemArray, copyToIndex)); } else { collection.CopyTo(itemArray, copyToIndex); Array.Copy( items, 0, tempItemArray, copyToIndex, items.Length); CollectionAssert.Equal(tempItemArray, itemArray); } } [Fact] public void CopyToValidTypes() { foreach (Type type in ValidArrayTypes) { object[] items = GenerateItems(16); ICollection collection = GetCollection(items); Array itemArray = Array.CreateInstance( type, collection.Count); collection.CopyTo(itemArray, 0); CollectionAssert.Equal(items, itemArray); } } [Fact] public void CollectionShouldContainAllItems() { object[] items = GenerateItems(16); ICollection<T> collection = GetCollection(items) as ICollection<T>; if (collection == null) return; Assert.All(items, item => Assert.True(collection.Contains((T) item))); } internal class MyInvalidReferenceType { } internal struct MyInvalidValueType { } } }
namespace FakeItEasy.Specs { using System; using FakeItEasy.Configuration; using FakeItEasy.Tests.TestHelpers; using FluentAssertions; using Xbehave; using Xunit; public static class ArgumentMatchingSpecs { public interface IFoo { int Bar(int a); int Bar(int a, string b); int Bar(int a, string b, bool c); int Bar(int a, string b, bool c, object d); } [Scenario] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(10)] public static void WithAnyArguments(int argument, IFoo fake, int result) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And a fake method with 1 parameter is configured to return a value when called with any arguments" .x(() => A.CallTo(() => fake.Bar(0)) .WithAnyArguments() .Returns(42)); $"When the method is called with argument {argument}" .x(() => result = fake.Bar(argument)); "Then it returns the configured value" .x(() => result.Should().Be(42)); } [Scenario] public static void WhenArgumentsMatchWith1ArgSuccess(IFoo fake, int result) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And a fake method with 1 parameter is configured to return a value when the arguments match a predicate" .x(() => A.CallTo(() => fake.Bar(0)) .WhenArgumentsMatch(args => args.Get<int>(0) % 2 == 0) .Returns(42)); "When the method is called with an argument that satisfies the predicate" .x(() => result = fake.Bar(4)); "Then it returns the configured value" .x(() => result.Should().Be(42)); } [Scenario] public static void WhenArgumentsMatchWith1ArgFailure(IFoo fake, int result) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And a fake method with 1 parameter is configured to return a value when the arguments match a predicate" .x(() => A.CallTo(() => fake.Bar(0)) .WhenArgumentsMatch(args => args.Get<int>(0) % 2 == 0) .Returns(42)); "When the method is called with an argument that doesn't satisfy the predicate" .x(() => result = fake.Bar(3)); "Then it returns the default value" .x(() => result.Should().Be(0)); } [Scenario] public static void WhenArgumentsMatchWith2ArgsSuccess(IFoo fake, int result) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And a fake method with 2 parameters is configured to return a value when the arguments match a predicate" .x(() => A.CallTo(() => fake.Bar(0, string.Empty)) .WhenArgumentsMatch(args => args.Get<int>(0) % 2 == 0 && args.Get<string>(1)?.Length < 3) .Returns(42)); "When the method is called with arguments that satisfy the predicate" .x(() => result = fake.Bar(4, "x")); "Then it returns the configured value" .x(() => result.Should().Be(42)); } [Scenario] public static void WhenArgumentsMatchWith2ArgsFailure(IFoo fake, int result) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And a fake method with 2 parameters is configured to return a value when the arguments match a predicate" .x(() => A.CallTo(() => fake.Bar(0, string.Empty)) .WhenArgumentsMatch(args => args.Get<int>(0) % 2 == 0 && args.Get<string>(1)?.Length < 3) .Returns(42)); "When the method is called with arguments that don't satisfy the predicate" .x(() => result = fake.Bar(3, "hello")); "Then it returns the default value" .x(() => result.Should().Be(0)); } [Scenario] public static void StronglyTypedWhenArgumentsMatchWith1ArgSuccess(IFoo fake, int result) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And a fake method with 1 parameter is configured to return a value when the arguments match a predicate" .x(() => A.CallTo(() => fake.Bar(0)) .WhenArgumentsMatch((int a) => a % 2 == 0) .Returns(42)); "When the method is called with an argument that satisfies the predicate" .x(() => result = fake.Bar(4)); "Then it returns the configured value" .x(() => result.Should().Be(42)); } [Scenario] public static void StronglyTypedWhenArgumentsMatchWith1ArgFailure(IFoo fake, int result) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And a fake method with 1 parameter is configured to return a value when the arguments match a predicate" .x(() => A.CallTo(() => fake.Bar(0)) .WhenArgumentsMatch((int a) => a % 2 == 0) .Returns(42)); "When the method is called with an argument that doesn't satisfy the predicate" .x(() => result = fake.Bar(3)); "Then it returns the default value" .x(() => result.Should().Be(0)); } [Scenario] public static void StronglyTypedWhenArgumentsMatchWith1ArgWrongSignature(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And a fake method with 1 parameter is configured with an arguments predicate with an incompatible signature" .x(() => exception = Record.Exception( () => A.CallTo(() => fake.Bar(0)) .WhenArgumentsMatch((long a) => true) .Returns(42))); "When the method is called" .x(() => exception = Record.Exception(() => fake.Bar(3))); "Then it throws a FakeConfigurationException that describes the problem" .x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>() .WithMessage("The faked method has the signature (System.Int32), but when arguments match was used with (System.Int64).")); } [Scenario] public static void StronglyTypedWhenArgumentsMatchWith2ArgsSuccess(IFoo fake, int result) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And a fake method with 2 parameters is configured to return a value when the arguments match a predicate" .x(() => A.CallTo(() => fake.Bar(0, string.Empty)) .WhenArgumentsMatch((int a, string b) => a % 2 == 0 && b.Length < 3) .Returns(42)); "When the method is called with arguments that satisfy the predicate" .x(() => result = fake.Bar(4, "x")); "Then it returns the configured value" .x(() => result.Should().Be(42)); } [Scenario] public static void StronglyTypedWhenArgumentsMatchWith2ArgsFailure(IFoo fake, int result) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And a fake method with 2 parameters is configured to return a value when the arguments match a predicate" .x(() => A.CallTo(() => fake.Bar(0, string.Empty)) .WhenArgumentsMatch((int a, string b) => a % 2 == 0 && b.Length < 3) .Returns(42)); "When the method is called with arguments that don't satisfy the predicate" .x(() => result = fake.Bar(3, "hello")); "Then it returns the default value" .x(() => result.Should().Be(0)); } [Scenario] public static void StronglyTypedWhenArgumentsMatchWith2ArgsWrongSignature(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And a fake method with 2 parameters is configured with an arguments predicate with an incompatible signature" .x(() => exception = Record.Exception( () => A.CallTo(() => fake.Bar(0, string.Empty)) .WhenArgumentsMatch((long a, DateTime b) => true) .Returns(42))); "When the method is called" .x(() => exception = Record.Exception(() => fake.Bar(3, "hello"))); "Then it throws a FakeConfigurationException that describes the problem" .x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>() .WithMessage("The faked method has the signature (System.Int32, System.String), but when arguments match was used with (System.Int64, System.DateTime).")); } [Scenario] public static void StronglyTypedWhenArgumentsMatchWith3ArgsSuccess(IFoo fake, int result) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And a fake method with 3 parameters is configured to return a value when the arguments match a predicate" .x(() => A.CallTo(() => fake.Bar(0, string.Empty, false)) .WhenArgumentsMatch((int a, string b, bool c) => a % 2 == 0 && b.Length < 3 && c) .Returns(42)); "When the method is called with arguments that satisfy the predicate" .x(() => result = fake.Bar(4, "x", true)); "Then it returns the configured value" .x(() => result.Should().Be(42)); } [Scenario] public static void StronglyTypedWhenArgumentsMatchWith3ArgsFailure(IFoo fake, int result) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And a fake method with 3 parameters is configured to return a value when the arguments match a predicate" .x(() => A.CallTo(() => fake.Bar(0, string.Empty, false)) .WhenArgumentsMatch((int a, string b, bool c) => a % 2 == 0 && b.Length < 3 && c) .Returns(42)); "When the method is called with arguments that don't satisfy the predicate" .x(() => result = fake.Bar(3, "hello", false)); "Then it returns the default value" .x(() => result.Should().Be(0)); } [Scenario] public static void StronglyTypedWhenArgumentsMatchWith3ArgsWrongSignature(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And a fake method with 3 parameters is configured with an arguments predicate with an incompatible signature" .x(() => exception = Record.Exception( () => A.CallTo(() => fake.Bar(0, string.Empty, false)) .WhenArgumentsMatch((long a, DateTime b, Type c) => true) .Returns(42))); "When the method is called" .x(() => exception = Record.Exception(() => fake.Bar(3, "hello", true))); "Then it throws a FakeConfigurationException that describes the problem" .x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>() .WithMessage("The faked method has the signature (System.Int32, System.String, System.Boolean), but when arguments match was used with (System.Int64, System.DateTime, System.Type).")); } [Scenario] public static void StronglyTypedWhenArgumentsMatchWith4ArgsSuccess(IFoo fake, int result) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And a fake method with 4 parameters is configured to return a value when the arguments match a predicate" .x(() => A.CallTo(() => fake.Bar(0, string.Empty, false, new object())) .WhenArgumentsMatch((int a, string b, bool c, object d) => a % 2 == 0 && b.Length < 3 && c && d is object) .Returns(42)); "When the method is called with arguments that satisfy the predicate" .x(() => result = fake.Bar(4, "x", true, new object())); "Then it returns the configured value" .x(() => result.Should().Be(42)); } [Scenario] public static void StronglyTypedWhenArgumentsMatchWith4ArgsFailure(IFoo fake, int result) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And a fake method with 4 parameters is configured to return a value when the arguments match a predicate" .x(() => A.CallTo(() => fake.Bar(0, string.Empty, false, new object())) .WhenArgumentsMatch((int a, string b, bool c, object d) => a % 2 == 0 && b.Length < 3 && c && d is object) .Returns(42)); "When the method is called with arguments that don't satisfy the predicate" .x(() => result = fake.Bar(3, "hello", false, new object())); "Then it returns the default value" .x(() => result.Should().Be(0)); } [Scenario] public static void StronglyTypedWhenArgumentsMatchWith4ArgsWrongSignature(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And a fake method with 4 parameters is configured with an arguments predicate with an incompatible signature" .x(() => exception = Record.Exception( () => A.CallTo(() => fake.Bar(0, string.Empty, false, new object())) .WhenArgumentsMatch((long a, DateTime b, Type c, char d) => true) .Returns(42))); "When the method is called" .x(() => exception = Record.Exception(() => fake.Bar(3, "hello", true, new object()))); "Then it throws a FakeConfigurationException that describes the problem" .x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>() .WithMessage("The faked method has the signature (System.Int32, System.String, System.Boolean, System.Object), but when arguments match was used with (System.Int64, System.DateTime, System.Type, System.Char).")); } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.HSLF.Record { using System; using System.IO; using NPOI.Util; using NPOI.HSLF.Exceptions; using System.Reflection; using System.Collections.Generic; /** * This abstract class represents a record in the PowerPoint document. * Record classes should extend with RecordContainer or RecordAtom, which * extend this in turn. * * @author Nick Burch */ public abstract class Record { // For logging protected POILogger logger = POILogFactory.GetLogger(typeof(Record)); /** * Is this record type an Atom record (only has data), * or is it a non-Atom record (has other records)? */ public abstract bool IsAnAtom { get; } /** * Returns the type (held as a little endian in bytes 3 and 4) * that this class handles */ public abstract long RecordType { get; } /** * Fetch all the child records of this record * If this record is an atom, will return null * If this record is a non-atom, but has no children, will return * an empty array */ public abstract Record[] GetChildRecords(); /** * Have the contents printer out into an OutputStream, used when * writing a file back out to disk * (Normally, atom classes will keep their bytes around, but * non atom classes will just request the bytes from their * children, then chuck on their header and return) */ public abstract void WriteOut(Stream o); /** * When writing out, write out a signed int (32bit) in Little Endian format */ public static void WriteLittleEndian(int i, Stream o) { byte[] bi = new byte[4]; LittleEndian.PutInt(bi, i); o.Write(bi, (int)o.Position, bi.Length); } /** * When writing out, write out a signed short (16bit) in Little Endian format */ public static void WriteLittleEndian(short s, Stream o) { byte[] bs = new byte[2]; LittleEndian.PutShort(bs, s); o.Write(bs,(int)o.Position,bs.Length); } /** * Build and return the Record at the given OffSet. * Note - does less error Checking and handling than FindChildRecords * @param b The byte array to build from * @param offset The offset to build at */ public static Record BuildRecordAtOffset(byte[] b, int offset) { long type = LittleEndian.GetUShort(b, offset + 2); long rlen = LittleEndian.GetUInt(b, offset + 4); // Sanity check the length int rleni = (int)rlen; if (rleni < 0) { rleni = 0; } return CreateRecordForType(type, b, offset, 8 + rleni); } /** * Default method for Finding child records of a Container record */ public static Record[] FindChildRecords(byte[] b, int start, int len) { List<Record> children = new List<Record>(5); // Jump our little way along, creating records as we go int pos = start; while (pos <= (start + len - 8)) { long type = LittleEndian.GetUShort(b, pos + 2); long rlen = LittleEndian.GetUInt(b, pos + 4); // Sanity check the length int rleni = (int)rlen; if (rleni < 0) { rleni = 0; } // Abort if first record is of type 0000 and length FFFF, // as that's a sign of a screwed up record if (pos == 0 && type == 0L && rleni == 0xffff) { throw new CorruptPowerPointFileException("Corrupt document - starts with record of type 0000 and length 0xFFFF"); } Record r = CreateRecordForType(type, b, pos, 8 + rleni); if (r != null) { children.Add(r); } else { // Record was horribly corrupt } pos += 8; pos += rleni; } // Turn the vector into an array, and return Record[] cRecords = new Record[children.Count]; for (int i = 0; i < children.Count; i++) { cRecords[i] = (Record)children[i]; } return cRecords; } /** * For a given type (little endian bytes 3 and 4 in record header), * byte array, start position and Length: * will return a Record object that will handle that record * * Remember that while PPT stores the record Lengths as 8 bytes short * (not including the size of the header), this code assumes you're * passing in corrected Lengths */ public static Record CreateRecordForType(long type, byte[] b, int start, int len) { Record toReturn = null; // Handle case of a corrupt last record, whose claimed length // would take us passed the end of the file if (start + len > b.Length) { Console.Error.WriteLine("Warning: Skipping record of type " + type + " at position " + start + " which claims to be longer than the file! (" + len + " vs " + (b.Length - start) + ")"); return null; } // We use the RecordTypes class to provide us with the right // class to use for a given type // A spot of reflection Gets us the (byte[],int,int) constructor // From there, we instanciate the class // Any special record handling occurs once we have the class Type c = null; try { c = RecordTypes.RecordHandlingClass((int)type); if (c == null) { // How odd. RecordTypes normally subsitutes in // a default handler class if it has heard of the record // type but there's no support for it. Explicitly request // that now c = RecordTypes.RecordHandlingClass(RecordTypes.Unknown.typeID); } // Grab the right constructor ConstructorInfo con = c.GetConstructor(new Type[] { typeof(byte[]), typeof(Int32), typeof(Int32) }); // Instantiate toReturn = (Record)(con.Invoke(new Object[] { b, start, len })); } catch (TargetInvocationException ite) { throw new Exception("Couldn't instantiate the class for type with id " + type + " on class " + c + " : " + ite + "\nCause was : " + ite.Message, ite); } catch (MethodAccessException iae) { throw new Exception("Couldn't access the constructor for type with id " + type + " on class " + c + " : " + iae, iae); } catch (NotSupportedException nsme) { throw new Exception("Couldn't access the constructor for type with id " + type + " on class " + c + " : " + nsme, nsme); } // Handling for special kinds of records follow // If it's a position aware record, tell it where it is if (toReturn is PositionDependentRecord) { PositionDependentRecord pdr = (PositionDependentRecord)toReturn; pdr.LastOnDiskOffset = (start); } // Return the Created record return toReturn; } } }
using UnityEngine; using Stratus; using System.Text; using System; using System.Collections.Generic; namespace Stratus.AI { public abstract class StratusBehaviorSystem : StratusScriptable { //------------------------------------------------------------------------/ // Fields //------------------------------------------------------------------------/ [Header("Debug")] /// <summary> /// Whether this system will print debug output /// </summary> public bool debug = false; /// <summary> /// A short description of what this system does /// </summary> public string description; /// <summary> /// The blackboard the blackboard is using. /// </summary> public StratusBlackboard blackboard; //------------------------------------------------------------------------/ // Properties //------------------------------------------------------------------------/ /// <summary> /// Whether this behavior system is currently running /// </summary> public bool active { protected set; get; } /// <summary> /// The agent this system is using /// </summary> public StratusAgent agent { private set; get; } /// <summary> /// The current behavior being run by this system /// </summary> protected abstract StratusAIBehavior currentBehavior { get; } /// <summary> /// Whether this system has behaviors present /// </summary> protected abstract bool hasBehaviors { get; } /// <summary> /// All currently running behavior systems for given agents /// </summary> protected static Dictionary<StratusAgent, StratusBehaviorSystem> agentBehaviors { get; set; } = new Dictionary<StratusAgent, StratusBehaviorSystem>(); /// <summary> /// Arguments used for updating behaviors /// </summary> protected StratusAIBehavior.Arguments behaviorArguments { private set; get; } /// <summary> /// A description of the state of the system /// </summary> public string stateDescription { get; } //------------------------------------------------------------------------/ // Interface //------------------------------------------------------------------------/ protected abstract void OnInitialize(); protected abstract void OnUpdate(); protected abstract void OnReset(); protected abstract void OnAssert(); protected abstract void OnBehaviorAdded(StratusAIBehavior behavior); public abstract void OnBehaviorStarted(StratusAIBehavior behavior); public abstract void OnBehaviorEnded(StratusAIBehavior behavior, StratusAIBehavior.Status status); protected abstract void OnBehaviorsCleared(); //------------------------------------------------------------------------/ // Methods //------------------------------------------------------------------------/ /// <summary> /// Initializes the system for the given agent /// </summary> public void InitializeSystem() { this.behaviorArguments = new StratusAIBehavior.Arguments() { agent = this.agent, system = this }; this.OnInitialize(); } /// <summary> /// Updates this behavior system. /// </summary> /// <param name="dt"></param> public void UpdateSystem() { this.OnUpdate(); } /// <summary> /// Resets the behaviour system so that it must evaluate from the beginning /// </summary> public void ResetSystem() { this.OnReset(); } /// <summary> /// Validates the correctness of this system /// </summary> /// <returns></returns> public void Assert() { this.OnAssert(); } /// <summary> /// Initializes an instance of this system, unique for the given agent /// </summary> /// <param name="agent"></param> /// <param name="system"></param> public static StratusBehaviorSystem InitializeSystemInstance(StratusAgent agent, StratusBehaviorSystem system) { if (!agentBehaviors.ContainsKey(agent)) agentBehaviors.Add(agent, system.Instantiate(agent)); StratusBehaviorSystem instance = agentBehaviors[agent]; instance.InitializeSystem(); return instance; } /// <summary> /// Updates an instance of the system that is unique for the given agent /// </summary> /// <param name="agent"></param> /// <param name="system"></param> public static void UpdateSystemInstance(StratusAgent agent) { agentBehaviors[agent].UpdateSystem(); } /// <summary> /// Resets the behaviour system so that it must evaluate from the beginning /// </summary> public void ResetSystemInstance(StratusAgent agent) { agentBehaviors[agent].ResetSystem(); } //------------------------------------------------------------------------/ // Behavior //------------------------------------------------------------------------/ /// <summary> /// Adds a behaviour to the system /// </summary> /// <param name="behaviorType"></param> public StratusAIBehavior AddBehavior(Type behaviorType) { StratusAIBehavior behavior = StratusAIBehavior.Instantiate(behaviorType); this.AddBehavior(behavior); return behavior; } /// <summary> /// Adds a behaviour to the system /// </summary> /// <param name="behaviorType"></param> public T AddBehavior<T>() where T : StratusAIBehavior { T behavior = StratusAIBehavior.Instantiate<T>(); this.AddBehavior(behavior); return behavior; } /// <summary> /// Adds a behaviour to the system /// </summary> /// <param name="type"></param> public void AddBehavior(StratusAIBehavior behavior) { this.OnBehaviorAdded(behavior); } /// <summary> /// Adds a behaviour to the system /// </summary> /// <param name="type"></param> public void AddBehavior<T>(T behavior) where T : StratusAIBehavior { this.OnBehaviorAdded(behavior); } /// <summary> /// Clears all behaviors from this system /// </summary> public void ClearBehaviors() { this.OnBehaviorsCleared(); } //------------------------------------------------------------------------/ // Methods: Static //------------------------------------------------------------------------/ /// <summary> /// Returns an instance of this behavior system to be used by a single agent. /// </summary> /// <param name="agent"></param> /// <returns></returns> public StratusBehaviorSystem Instantiate(StratusAgent agent) { var behaviorSystem = Instantiate(this); behaviorSystem.agent = agent; return behaviorSystem; } /// <summary> /// Returns an instance of this behavior system to be used by a single agent. /// </summary> /// <param name="agent"></param> /// <returns></returns> public StratusBehaviorSystem Instantiate(StratusBlackboard blackboard) { var behaviorSystem = Instantiate(this); behaviorSystem.blackboard = blackboard; return behaviorSystem; } } }
// CRC32.cs - Computes CRC32 data checksum of a data stream // Copyright (C) 2001 Mike Krueger // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 1999, 2000, 2001 Free Software Foundation, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; namespace GameAnalyticsSDK.Net.Utilities.Zip.Checksums { /// <summary> /// Generate a table for a byte-wise 32-bit CRC calculation on the polynomial: /// x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. /// /// Polynomials over GF(2) are represented in binary, one bit per coefficient, /// with the lowest powers in the most significant bit. Then adding polynomials /// is just exclusive-or, and multiplying a polynomial by x is a right shift by /// one. If we call the above polynomial p, and represent a byte as the /// polynomial q, also with the lowest power in the most significant bit (so the /// byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, /// where a mod b means the remainder after dividing a by b. /// /// This calculation is done using the shift-register method of multiplying and /// taking the remainder. The register is initialized to zero, and for each /// incoming bit, x^32 is added mod p to the register if the bit is a one (where /// x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by /// x (which is shifting right by one and adding x^32 mod p if the bit shifted /// out is a one). We start with the highest power (least significant bit) of /// q and repeat for all eight bits of q. /// /// The table is simply the CRC of all possible eight bit values. This is all /// the information needed to generate CRC's on data a byte at a time for all /// combinations of CRC register values and incoming bytes. /// </summary> public sealed class Crc32 : IChecksum { readonly static uint CrcSeed = 0xFFFFFFFF; readonly static uint[] CrcTable = new uint[] { 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D }; internal static uint ComputeCrc32(uint oldCrc, byte bval) { return (uint)(Crc32.CrcTable[(oldCrc ^ bval) & 0xFF] ^ (oldCrc >> 8)); } /// <summary> /// The crc data checksum so far. /// </summary> uint crc = 0; /// <summary> /// Returns the CRC32 data checksum computed so far. /// </summary> public long Value { get { return (long)crc; } set { crc = (uint)value; } } /// <summary> /// Resets the CRC32 data checksum as if no update was ever called. /// </summary> public void Reset() { crc = 0; } /// <summary> /// Updates the checksum with the int bval. /// </summary> /// <param name = "bval"> /// the byte is taken as the lower 8 bits of bval /// </param> public void Update(int bval) { crc ^= CrcSeed; crc = CrcTable[(crc ^ bval) & 0xFF] ^ (crc >> 8); crc ^= CrcSeed; } /// <summary> /// Updates the checksum with the bytes taken from the array. /// </summary> /// <param name="buffer"> /// buffer an array of bytes /// </param> public void Update(byte[] buffer) { Update(buffer, 0, buffer.Length); } /// <summary> /// Adds the byte array to the data checksum. /// </summary> /// <param name = "buf"> /// the buffer which contains the data /// </param> /// <param name = "off"> /// the offset in the buffer where the data starts /// </param> /// <param name = "len"> /// the length of the data /// </param> public void Update(byte[] buf, int off, int len) { if (buf == null) { throw new ArgumentNullException("buf"); } if (off < 0 || len < 0 || off + len > buf.Length) { throw new ArgumentOutOfRangeException(); } crc ^= CrcSeed; while (--len >= 0) { crc = CrcTable[(crc ^ buf[off++]) & 0xFF] ^ (crc >> 8); } crc ^= CrcSeed; } } }
/* * 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. */ // ReSharper disable SpecifyACultureInStringConversionExplicitly // ReSharper disable UnusedAutoPropertyAccessor.Global #pragma warning disable 618 // SpringConfigUrl namespace Apache.Ignite.Core.Tests.Compute { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Resource; using NUnit.Framework; /// <summary> /// Tests for compute. /// </summary> public class ComputeApiTest { /** Echo task name. */ public const string EchoTask = "org.apache.ignite.platform.PlatformComputeEchoTask"; /** Binary argument task name. */ public const string BinaryArgTask = "org.apache.ignite.platform.PlatformComputeBinarizableArgTask"; /** Broadcast task name. */ public const string BroadcastTask = "org.apache.ignite.platform.PlatformComputeBroadcastTask"; /** Broadcast task name. */ private const string DecimalTask = "org.apache.ignite.platform.PlatformComputeDecimalTask"; /** Java binary class name. */ private const string JavaBinaryCls = "PlatformComputeJavaBinarizable"; /** Echo type: null. */ private const int EchoTypeNull = 0; /** Echo type: byte. */ private const int EchoTypeByte = 1; /** Echo type: bool. */ private const int EchoTypeBool = 2; /** Echo type: short. */ private const int EchoTypeShort = 3; /** Echo type: char. */ private const int EchoTypeChar = 4; /** Echo type: int. */ private const int EchoTypeInt = 5; /** Echo type: long. */ private const int EchoTypeLong = 6; /** Echo type: float. */ private const int EchoTypeFloat = 7; /** Echo type: double. */ private const int EchoTypeDouble = 8; /** Echo type: array. */ private const int EchoTypeArray = 9; /** Echo type: collection. */ private const int EchoTypeCollection = 10; /** Echo type: map. */ private const int EchoTypeMap = 11; /** Echo type: binarizable. */ public const int EchoTypeBinarizable = 12; /** Echo type: binary (Java only). */ private const int EchoTypeBinarizableJava = 13; /** Type: object array. */ private const int EchoTypeObjArray = 14; /** Type: binary object array. */ private const int EchoTypeBinarizableArray = 15; /** Type: enum. */ private const int EchoTypeEnum = 16; /** Type: enum array. */ private const int EchoTypeEnumArray = 17; /** Type: enum field. */ private const int EchoTypeEnumField = 18; /** Type: affinity key. */ public const int EchoTypeAffinityKey = 19; /** First node. */ private IIgnite _grid1; /** Second node. */ private IIgnite _grid2; /** Third node. */ private IIgnite _grid3; /// <summary> /// Initialization routine. /// </summary> [TestFixtureSetUp] public void InitClient() { TestUtils.KillProcesses(); var configs = GetConfigs(); _grid1 = Ignition.Start(Configuration(configs.Item1)); _grid2 = Ignition.Start(Configuration(configs.Item2)); _grid3 = Ignition.Start(Configuration(configs.Item3)); } /// <summary> /// Gets the configs. /// </summary> protected virtual Tuple<string, string, string> GetConfigs() { return Tuple.Create( "config\\compute\\compute-grid1.xml", "config\\compute\\compute-grid2.xml", "config\\compute\\compute-grid3.xml"); } /// <summary> /// Gets the expected compact footers setting. /// </summary> protected virtual bool CompactFooter { get { return true; } } [TestFixtureTearDown] public void StopClient() { if (_grid1 != null) Ignition.Stop(_grid1.Name, true); if (_grid2 != null) Ignition.Stop(_grid2.Name, true); if (_grid3 != null) Ignition.Stop(_grid3.Name, true); } [TearDown] public void AfterTest() { TestUtils.AssertHandleRegistryIsEmpty(1000, _grid1, _grid2, _grid3); } /// <summary> /// Test that it is possible to get projection from grid. /// </summary> [Test] public void TestProjection() { IClusterGroup prj = _grid1.GetCluster(); Assert.NotNull(prj); Assert.IsTrue(prj == prj.Ignite); } /// <summary> /// Test getting cache with default (null) name. /// </summary> [Test] public void TestCacheDefaultName() { var cache = _grid1.GetCache<int, int>(null); Assert.IsNotNull(cache); cache.GetAndPut(1, 1); Assert.AreEqual(1, cache.Get(1)); } /// <summary> /// Test non-existent cache. /// </summary> [Test] public void TestNonExistentCache() { Assert.Catch(typeof(ArgumentException), () => { _grid1.GetCache<int, int>("bad_name"); }); } /// <summary> /// Test node content. /// </summary> [Test] public void TestNodeContent() { ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes(); foreach (IClusterNode node in nodes) { Assert.NotNull(node.Addresses); Assert.IsTrue(node.Addresses.Count > 0); Assert.Throws<NotSupportedException>(() => node.Addresses.Add("addr")); Assert.NotNull(node.GetAttributes()); Assert.IsTrue(node.GetAttributes().Count > 0); Assert.Throws<NotSupportedException>(() => node.GetAttributes().Add("key", "val")); Assert.NotNull(node.HostNames); Assert.Throws<NotSupportedException>(() => node.HostNames.Add("h")); Assert.IsTrue(node.Id != Guid.Empty); Assert.IsTrue(node.Order > 0); Assert.NotNull(node.GetMetrics()); } } /// <summary> /// Test cluster metrics. /// </summary> [Test] public void TestClusterMetrics() { var cluster = _grid1.GetCluster(); IClusterMetrics metrics = cluster.GetMetrics(); Assert.IsNotNull(metrics); Assert.AreEqual(cluster.GetNodes().Count, metrics.TotalNodes); Thread.Sleep(2000); IClusterMetrics newMetrics = cluster.GetMetrics(); Assert.IsFalse(metrics == newMetrics); Assert.IsTrue(metrics.LastUpdateTime < newMetrics.LastUpdateTime); } /// <summary> /// Test cluster metrics. /// </summary> [Test] public void TestNodeMetrics() { var node = _grid1.GetCluster().GetNode(); IClusterMetrics metrics = node.GetMetrics(); Assert.IsNotNull(metrics); Assert.IsTrue(metrics == node.GetMetrics()); Thread.Sleep(2000); IClusterMetrics newMetrics = node.GetMetrics(); Assert.IsFalse(metrics == newMetrics); Assert.IsTrue(metrics.LastUpdateTime < newMetrics.LastUpdateTime); } /// <summary> /// Test cluster metrics. /// </summary> [Test] public void TestResetMetrics() { var cluster = _grid1.GetCluster(); Thread.Sleep(2000); var metrics1 = cluster.GetMetrics(); cluster.ResetMetrics(); var metrics2 = cluster.GetMetrics(); Assert.IsNotNull(metrics1); Assert.IsNotNull(metrics2); } /// <summary> /// Test node ping. /// </summary> [Test] public void TestPingNode() { var cluster = _grid1.GetCluster(); Assert.IsTrue(cluster.GetNodes().Select(node => node.Id).All(cluster.PingNode)); Assert.IsFalse(cluster.PingNode(Guid.NewGuid())); } /// <summary> /// Tests the topology version. /// </summary> [Test] public void TestTopologyVersion() { var cluster = _grid1.GetCluster(); var topVer = cluster.TopologyVersion; Ignition.Stop(_grid3.Name, true); Assert.AreEqual(topVer + 1, _grid1.GetCluster().TopologyVersion); _grid3 = Ignition.Start(Configuration(GetConfigs().Item3)); Assert.AreEqual(topVer + 2, _grid1.GetCluster().TopologyVersion); } /// <summary> /// Tests the topology by version. /// </summary> [Test] public void TestTopology() { var cluster = _grid1.GetCluster(); Assert.AreEqual(1, cluster.GetTopology(1).Count); Assert.AreEqual(null, cluster.GetTopology(int.MaxValue)); // Check that Nodes and Topology return the same for current version var topVer = cluster.TopologyVersion; var top = cluster.GetTopology(topVer); var nodes = cluster.GetNodes(); Assert.AreEqual(top.Count, nodes.Count); Assert.IsTrue(top.All(nodes.Contains)); // Stop/start node to advance version and check that history is still correct Assert.IsTrue(Ignition.Stop(_grid2.Name, true)); try { top = cluster.GetTopology(topVer); Assert.AreEqual(top.Count, nodes.Count); Assert.IsTrue(top.All(nodes.Contains)); } finally { _grid2 = Ignition.Start(Configuration(GetConfigs().Item2)); } } /// <summary> /// Test nodes in full topology. /// </summary> [Test] public void TestNodes() { Assert.IsNotNull(_grid1.GetCluster().GetNode()); ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes(); Assert.IsTrue(nodes.Count == 3); // Check subsequent call on the same topology. nodes = _grid1.GetCluster().GetNodes(); Assert.IsTrue(nodes.Count == 3); Assert.IsTrue(Ignition.Stop(_grid2.Name, true)); // Check subsequent calls on updating topologies. nodes = _grid1.GetCluster().GetNodes(); Assert.IsTrue(nodes.Count == 2); nodes = _grid1.GetCluster().GetNodes(); Assert.IsTrue(nodes.Count == 2); _grid2 = Ignition.Start(Configuration(GetConfigs().Item2)); nodes = _grid1.GetCluster().GetNodes(); Assert.IsTrue(nodes.Count == 3); } /// <summary> /// Test "ForNodes" and "ForNodeIds". /// </summary> [Test] public void TestForNodes() { ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes(); IClusterNode first = nodes.ElementAt(0); IClusterNode second = nodes.ElementAt(1); IClusterGroup singleNodePrj = _grid1.GetCluster().ForNodeIds(first.Id); Assert.AreEqual(1, singleNodePrj.GetNodes().Count); Assert.AreEqual(first.Id, singleNodePrj.GetNodes().First().Id); singleNodePrj = _grid1.GetCluster().ForNodeIds(new List<Guid> { first.Id }); Assert.AreEqual(1, singleNodePrj.GetNodes().Count); Assert.AreEqual(first.Id, singleNodePrj.GetNodes().First().Id); singleNodePrj = _grid1.GetCluster().ForNodes(first); Assert.AreEqual(1, singleNodePrj.GetNodes().Count); Assert.AreEqual(first.Id, singleNodePrj.GetNodes().First().Id); singleNodePrj = _grid1.GetCluster().ForNodes(new List<IClusterNode> { first }); Assert.AreEqual(1, singleNodePrj.GetNodes().Count); Assert.AreEqual(first.Id, singleNodePrj.GetNodes().First().Id); IClusterGroup multiNodePrj = _grid1.GetCluster().ForNodeIds(first.Id, second.Id); Assert.AreEqual(2, multiNodePrj.GetNodes().Count); Assert.IsTrue(multiNodePrj.GetNodes().Contains(first)); Assert.IsTrue(multiNodePrj.GetNodes().Contains(second)); multiNodePrj = _grid1.GetCluster().ForNodeIds(new[] {first, second}.Select(x => x.Id)); Assert.AreEqual(2, multiNodePrj.GetNodes().Count); Assert.IsTrue(multiNodePrj.GetNodes().Contains(first)); Assert.IsTrue(multiNodePrj.GetNodes().Contains(second)); multiNodePrj = _grid1.GetCluster().ForNodes(first, second); Assert.AreEqual(2, multiNodePrj.GetNodes().Count); Assert.IsTrue(multiNodePrj.GetNodes().Contains(first)); Assert.IsTrue(multiNodePrj.GetNodes().Contains(second)); multiNodePrj = _grid1.GetCluster().ForNodes(new List<IClusterNode> { first, second }); Assert.AreEqual(2, multiNodePrj.GetNodes().Count); Assert.IsTrue(multiNodePrj.GetNodes().Contains(first)); Assert.IsTrue(multiNodePrj.GetNodes().Contains(second)); } /// <summary> /// Test "ForNodes" and "ForNodeIds". Make sure lazy enumerables are enumerated only once. /// </summary> [Test] public void TestForNodesLaziness() { var nodes = _grid1.GetCluster().GetNodes().Take(2).ToArray(); var callCount = 0; Func<IClusterNode, IClusterNode> nodeSelector = node => { callCount++; return node; }; Func<IClusterNode, Guid> idSelector = node => { callCount++; return node.Id; }; var projection = _grid1.GetCluster().ForNodes(nodes.Select(nodeSelector)); Assert.AreEqual(2, projection.GetNodes().Count); Assert.AreEqual(2, callCount); projection = _grid1.GetCluster().ForNodeIds(nodes.Select(idSelector)); Assert.AreEqual(2, projection.GetNodes().Count); Assert.AreEqual(4, callCount); } /// <summary> /// Test for local node projection. /// </summary> [Test] public void TestForLocal() { IClusterGroup prj = _grid1.GetCluster().ForLocal(); Assert.AreEqual(1, prj.GetNodes().Count); Assert.AreEqual(_grid1.GetCluster().GetLocalNode(), prj.GetNodes().First()); } /// <summary> /// Test for remote nodes projection. /// </summary> [Test] public void TestForRemotes() { ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes(); IClusterGroup prj = _grid1.GetCluster().ForRemotes(); Assert.AreEqual(2, prj.GetNodes().Count); Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(0))); Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(1))); } /// <summary> /// Test for host nodes projection. /// </summary> [Test] public void TestForHost() { ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes(); IClusterGroup prj = _grid1.GetCluster().ForHost(nodes.First()); Assert.AreEqual(3, prj.GetNodes().Count); Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(0))); Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(1))); Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(2))); } /// <summary> /// Test for oldest, youngest and random projections. /// </summary> [Test] public void TestForOldestYoungestRandom() { ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes(); IClusterGroup prj = _grid1.GetCluster().ForYoungest(); Assert.AreEqual(1, prj.GetNodes().Count); Assert.IsTrue(nodes.Contains(prj.GetNode())); prj = _grid1.GetCluster().ForOldest(); Assert.AreEqual(1, prj.GetNodes().Count); Assert.IsTrue(nodes.Contains(prj.GetNode())); prj = _grid1.GetCluster().ForRandom(); Assert.AreEqual(1, prj.GetNodes().Count); Assert.IsTrue(nodes.Contains(prj.GetNode())); } /// <summary> /// Test for attribute projection. /// </summary> [Test] public void TestForAttribute() { ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes(); IClusterGroup prj = _grid1.GetCluster().ForAttribute("my_attr", "value1"); Assert.AreEqual(1, prj.GetNodes().Count); Assert.IsTrue(nodes.Contains(prj.GetNode())); Assert.AreEqual("value1", prj.GetNodes().First().GetAttribute<string>("my_attr")); } /// <summary> /// Test for cache/data/client projections. /// </summary> [Test] public void TestForCacheNodes() { ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes(); // Cache nodes. IClusterGroup prjCache = _grid1.GetCluster().ForCacheNodes("cache1"); Assert.AreEqual(2, prjCache.GetNodes().Count); Assert.IsTrue(nodes.Contains(prjCache.GetNodes().ElementAt(0))); Assert.IsTrue(nodes.Contains(prjCache.GetNodes().ElementAt(1))); // Data nodes. IClusterGroup prjData = _grid1.GetCluster().ForDataNodes("cache1"); Assert.AreEqual(2, prjData.GetNodes().Count); Assert.IsTrue(prjCache.GetNodes().Contains(prjData.GetNodes().ElementAt(0))); Assert.IsTrue(prjCache.GetNodes().Contains(prjData.GetNodes().ElementAt(1))); // Client nodes. IClusterGroup prjClient = _grid1.GetCluster().ForClientNodes("cache1"); Assert.AreEqual(0, prjClient.GetNodes().Count); } /// <summary> /// Test for cache predicate. /// </summary> [Test] public void TestForPredicate() { IClusterGroup prj1 = _grid1.GetCluster().ForPredicate(new NotAttributePredicate("value1").Apply); Assert.AreEqual(2, prj1.GetNodes().Count); IClusterGroup prj2 = prj1.ForPredicate(new NotAttributePredicate("value2").Apply); Assert.AreEqual(1, prj2.GetNodes().Count); string val; prj2.GetNodes().First().TryGetAttribute("my_attr", out val); Assert.IsTrue(val == null || (!val.Equals("value1") && !val.Equals("value2"))); } /// <summary> /// Attribute predicate. /// </summary> private class NotAttributePredicate { /** Required attribute value. */ private readonly string _attrVal; /// <summary> /// Constructor. /// </summary> /// <param name="attrVal">Required attribute value.</param> public NotAttributePredicate(string attrVal) { _attrVal = attrVal; } /** <inhreitDoc /> */ public bool Apply(IClusterNode node) { string val; node.TryGetAttribute("my_attr", out val); return val == null || !val.Equals(_attrVal); } } /// <summary> /// Test echo with decimals. /// </summary> [Test] public void TestEchoDecimal() { decimal val; Assert.AreEqual(val = decimal.Zero, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, 0, 1, false, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, 0, 1, true, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, 0, 1, false, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, 0, 1, true, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, 0, 1, false, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, 0, 1, true, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, 0, int.MinValue, false, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, 0, int.MinValue, true, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, 0, int.MinValue, false, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, 0, int.MinValue, true, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, 0, int.MinValue, false, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, 0, int.MinValue, true, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, 0, int.MaxValue, false, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, 0, int.MaxValue, true, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, 0, int.MaxValue, false, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, 0, int.MaxValue, true, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, 0, int.MaxValue, false, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, 0, int.MaxValue, true, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, 1, 0, false, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, 1, 0, true, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, 1, 0, false, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, 1, 0, true, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, 1, 0, false, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, 1, 0, true, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, int.MinValue, 0, false, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, int.MinValue, 0, true, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, int.MinValue, 0, false, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, int.MinValue, 0, true, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, int.MinValue, 0, false, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, int.MinValue, 0, true, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, int.MaxValue, 0, false, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, int.MaxValue, 0, true, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, int.MaxValue, 0, false, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, int.MaxValue, 0, true, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, int.MaxValue, 0, false, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(0, int.MaxValue, 0, true, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(1, 0, 0, false, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(1, 0, 0, true, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(1, 0, 0, false, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(1, 0, 0, true, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(1, 0, 0, false, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(1, 0, 0, true, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(int.MinValue, 0, 0, false, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(int.MinValue, 0, 0, true, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(int.MinValue, 0, 0, false, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(int.MinValue, 0, 0, true, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(int.MinValue, 0, 0, false, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(int.MinValue, 0, 0, true, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(int.MaxValue, 0, 0, false, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(int.MaxValue, 0, 0, true, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(int.MaxValue, 0, 0, false, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(int.MaxValue, 0, 0, true, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(int.MaxValue, 0, 0, false, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(int.MaxValue, 0, 0, true, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(1, 1, 1, false, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(1, 1, 1, true, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(1, 1, 1, false, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(1, 1, 1, true, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(1, 1, 1, false, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = new decimal(1, 1, 1, true, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("65536"), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("-65536"), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("65536") - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("-65536") - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("65536") + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("-65536") + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("4294967296"), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("-4294967296"), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("4294967296") - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("-4294967296") - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("4294967296") + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("-4294967296") + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("281474976710656"), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("-281474976710656"), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("281474976710656") - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("-281474976710656") - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("281474976710656") + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("-281474976710656") + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("18446744073709551616"), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("-18446744073709551616"), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("18446744073709551616") - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("-18446744073709551616") - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("18446744073709551616") + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("-18446744073709551616") + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("1208925819614629174706176"), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("-1208925819614629174706176"), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("1208925819614629174706176") - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("-1208925819614629174706176") - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("1208925819614629174706176") + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("-1208925819614629174706176") + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.MaxValue, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.MinValue, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.MaxValue - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.MinValue + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("11,12"), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); Assert.AreEqual(val = decimal.Parse("-11,12"), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() })); // Test echo with overflow. try { _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { null, decimal.MaxValue.ToString() + 1 }); Assert.Fail(); } catch (IgniteException) { // No-op. } } /// <summary> /// Test echo task returning null. /// </summary> [Test] public void TestEchoTaskNull() { Assert.IsNull(_grid1.GetCompute().ExecuteJavaTask<object>(EchoTask, EchoTypeNull)); } /// <summary> /// Test echo task returning various primitives. /// </summary> [Test] public void TestEchoTaskPrimitives() { Assert.AreEqual(1, _grid1.GetCompute().ExecuteJavaTask<byte>(EchoTask, EchoTypeByte)); Assert.AreEqual(true, _grid1.GetCompute().ExecuteJavaTask<bool>(EchoTask, EchoTypeBool)); Assert.AreEqual(1, _grid1.GetCompute().ExecuteJavaTask<short>(EchoTask, EchoTypeShort)); Assert.AreEqual((char)1, _grid1.GetCompute().ExecuteJavaTask<char>(EchoTask, EchoTypeChar)); Assert.AreEqual(1, _grid1.GetCompute().ExecuteJavaTask<int>(EchoTask, EchoTypeInt)); Assert.AreEqual(1, _grid1.GetCompute().ExecuteJavaTask<long>(EchoTask, EchoTypeLong)); Assert.AreEqual((float)1, _grid1.GetCompute().ExecuteJavaTask<float>(EchoTask, EchoTypeFloat)); Assert.AreEqual((double)1, _grid1.GetCompute().ExecuteJavaTask<double>(EchoTask, EchoTypeDouble)); } /// <summary> /// Test echo task returning compound types. /// </summary> [Test] public void TestEchoTaskCompound() { int[] res1 = _grid1.GetCompute().ExecuteJavaTask<int[]>(EchoTask, EchoTypeArray); Assert.AreEqual(1, res1.Length); Assert.AreEqual(1, res1[0]); var res2 = _grid1.GetCompute().ExecuteJavaTask<IList>(EchoTask, EchoTypeCollection); Assert.AreEqual(1, res2.Count); Assert.AreEqual(1, res2[0]); var res3 = _grid1.GetCompute().ExecuteJavaTask<IDictionary>(EchoTask, EchoTypeMap); Assert.AreEqual(1, res3.Count); Assert.AreEqual(1, res3[1]); } /// <summary> /// Test echo task returning binary object. /// </summary> [Test] public void TestEchoTaskBinarizable() { var res = _grid1.GetCompute().ExecuteJavaTask<PlatformComputeBinarizable>(EchoTask, EchoTypeBinarizable); Assert.AreEqual(1, res.Field); } /// <summary> /// Test echo task returning binary object with no corresponding class definition. /// </summary> [Test] public void TestEchoTaskBinarizableNoClass() { ICompute compute = _grid1.GetCompute(); compute.WithKeepBinary(); IBinaryObject res = compute.ExecuteJavaTask<IBinaryObject>(EchoTask, EchoTypeBinarizableJava); Assert.AreEqual(1, res.GetField<int>("field")); // This call must fail because "keepBinary" flag is reset. Assert.Catch(typeof(BinaryObjectException), () => { compute.ExecuteJavaTask<IBinaryObject>(EchoTask, EchoTypeBinarizableJava); }); } /// <summary> /// Tests the echo task returning object array. /// </summary> [Test] public void TestEchoTaskObjectArray() { var res = _grid1.GetCompute().ExecuteJavaTask<string[]>(EchoTask, EchoTypeObjArray); Assert.AreEqual(new[] {"foo", "bar", "baz"}, res); } /// <summary> /// Tests the echo task returning binary array. /// </summary> [Test] public void TestEchoTaskBinarizableArray() { var res = _grid1.GetCompute().ExecuteJavaTask<object[]>(EchoTask, EchoTypeBinarizableArray); Assert.AreEqual(3, res.Length); for (var i = 0; i < res.Length; i++) Assert.AreEqual(i + 1, ((PlatformComputeBinarizable) res[i]).Field); } /// <summary> /// Tests the echo task returning enum. /// </summary> [Test] public void TestEchoTaskEnum() { var res = _grid1.GetCompute().ExecuteJavaTask<PlatformComputeEnum>(EchoTask, EchoTypeEnum); Assert.AreEqual(PlatformComputeEnum.Bar, res); } /// <summary> /// Tests the echo task returning enum. /// </summary> [Test] public void TestEchoTaskEnumArray() { var res = _grid1.GetCompute().ExecuteJavaTask<PlatformComputeEnum[]>(EchoTask, EchoTypeEnumArray); Assert.AreEqual(new[] { PlatformComputeEnum.Bar, PlatformComputeEnum.Baz, PlatformComputeEnum.Foo }, res); } /// <summary> /// Tests the echo task reading enum from a binary object field. /// Ensures that Java can understand enums written by .NET. /// </summary> [Test] public void TestEchoTaskEnumField() { var enumVal = PlatformComputeEnum.Baz; _grid1.GetCache<int, InteropComputeEnumFieldTest>(null) .Put(EchoTypeEnumField, new InteropComputeEnumFieldTest {InteropEnum = enumVal}); var res = _grid1.GetCompute().ExecuteJavaTask<PlatformComputeEnum>(EchoTask, EchoTypeEnumField); var enumMeta = _grid1.GetBinary().GetBinaryType(typeof (PlatformComputeEnum)); Assert.IsTrue(enumMeta.IsEnum); Assert.AreEqual(enumMeta.TypeName, typeof(PlatformComputeEnum).Name); Assert.AreEqual(0, enumMeta.Fields.Count); Assert.AreEqual(enumVal, res); } /// <summary> /// Test for binary argument in Java. /// </summary> [Test] public void TestBinarizableArgTask() { ICompute compute = _grid1.GetCompute(); compute.WithKeepBinary(); PlatformComputeNetBinarizable arg = new PlatformComputeNetBinarizable(); arg.Field = 100; int res = compute.ExecuteJavaTask<int>(BinaryArgTask, arg); Assert.AreEqual(arg.Field, res); } /// <summary> /// Test running broadcast task. /// </summary> [Test] public void TestBroadcastTask() { var res = _grid1.GetCompute().ExecuteJavaTask<ICollection>(BroadcastTask, null).OfType<Guid>().ToList(); Assert.AreEqual(3, res.Count); Assert.AreEqual(1, _grid1.GetCluster().ForNodeIds(res.ElementAt(0)).GetNodes().Count); Assert.AreEqual(1, _grid1.GetCluster().ForNodeIds(res.ElementAt(1)).GetNodes().Count); Assert.AreEqual(1, _grid1.GetCluster().ForNodeIds(res.ElementAt(2)).GetNodes().Count); var prj = _grid1.GetCluster().ForPredicate(node => res.Take(2).Contains(node.Id)); Assert.AreEqual(2, prj.GetNodes().Count); var filteredRes = prj.GetCompute().ExecuteJavaTask<ICollection>(BroadcastTask, null).OfType<Guid>().ToList(); Assert.AreEqual(2, filteredRes.Count); Assert.IsTrue(filteredRes.Contains(res.ElementAt(0))); Assert.IsTrue(filteredRes.Contains(res.ElementAt(1))); } /// <summary> /// Test running broadcast task in async mode. /// </summary> [Test] public void TestBroadcastTaskAsync() { var gridCompute = _grid1.GetCompute(); var res = gridCompute.ExecuteJavaTaskAsync<ICollection>(BroadcastTask, null).Result.OfType<Guid>().ToList(); Assert.AreEqual(3, res.Count); Assert.AreEqual(1, _grid1.GetCluster().ForNodeIds(res.ElementAt(0)).GetNodes().Count); Assert.AreEqual(1, _grid1.GetCluster().ForNodeIds(res.ElementAt(1)).GetNodes().Count); Assert.AreEqual(1, _grid1.GetCluster().ForNodeIds(res.ElementAt(2)).GetNodes().Count); var prj = _grid1.GetCluster().ForPredicate(node => res.Take(2).Contains(node.Id)); Assert.AreEqual(2, prj.GetNodes().Count); var compute = prj.GetCompute(); var filteredRes = compute.ExecuteJavaTaskAsync<IList>(BroadcastTask, null).Result; Assert.AreEqual(2, filteredRes.Count); Assert.IsTrue(filteredRes.Contains(res.ElementAt(0))); Assert.IsTrue(filteredRes.Contains(res.ElementAt(1))); } /// <summary> /// Tests the action broadcast. /// </summary> [Test] public void TestBroadcastAction() { ComputeAction.InvokeCount = 0; _grid1.GetCompute().Broadcast(new ComputeAction()); Assert.AreEqual(_grid1.GetCluster().GetNodes().Count, ComputeAction.InvokeCount); } /// <summary> /// Tests single action run. /// </summary> [Test] public void TestRunAction() { ComputeAction.InvokeCount = 0; _grid1.GetCompute().Run(new ComputeAction()); Assert.AreEqual(1, ComputeAction.InvokeCount); } /// <summary> /// Tests single action run. /// </summary> [Test] public void TestRunActionAsyncCancel() { using (var cts = new CancellationTokenSource()) { // Cancel while executing var task = _grid1.GetCompute().RunAsync(new ComputeAction(), cts.Token); cts.Cancel(); Assert.IsTrue(task.IsCanceled); // Use cancelled token task = _grid1.GetCompute().RunAsync(new ComputeAction(), cts.Token); Assert.IsTrue(task.IsCanceled); } } /// <summary> /// Tests multiple actions run. /// </summary> [Test] public void TestRunActions() { ComputeAction.InvokeCount = 0; var actions = Enumerable.Range(0, 10).Select(x => new ComputeAction()); _grid1.GetCompute().Run(actions); Assert.AreEqual(10, ComputeAction.InvokeCount); } /// <summary> /// Tests affinity run. /// </summary> [Test] public void TestAffinityRun() { const string cacheName = null; // Test keys for non-client nodes var nodes = new[] {_grid1, _grid2}.Select(x => x.GetCluster().GetLocalNode()); var aff = _grid1.GetAffinity(cacheName); foreach (var node in nodes) { var primaryKey = Enumerable.Range(1, int.MaxValue).First(x => aff.IsPrimary(node, x)); var affinityKey = _grid1.GetAffinity(cacheName).GetAffinityKey<int, int>(primaryKey); _grid1.GetCompute().AffinityRun(cacheName, affinityKey, new ComputeAction()); Assert.AreEqual(node.Id, ComputeAction.LastNodeId); } } /// <summary> /// Tests affinity call. /// </summary> [Test] public void TestAffinityCall() { const string cacheName = null; // Test keys for non-client nodes var nodes = new[] { _grid1, _grid2 }.Select(x => x.GetCluster().GetLocalNode()); var aff = _grid1.GetAffinity(cacheName); foreach (var node in nodes) { var primaryKey = Enumerable.Range(1, int.MaxValue).First(x => aff.IsPrimary(node, x)); var affinityKey = _grid1.GetAffinity(cacheName).GetAffinityKey<int, int>(primaryKey); var result = _grid1.GetCompute().AffinityCall(cacheName, affinityKey, new ComputeFunc()); Assert.AreEqual(result, ComputeFunc.InvokeCount); Assert.AreEqual(node.Id, ComputeFunc.LastNodeId); } } /// <summary> /// Test "withNoFailover" feature. /// </summary> [Test] public void TestWithNoFailover() { var res = _grid1.GetCompute().WithNoFailover().ExecuteJavaTask<ICollection>(BroadcastTask, null) .OfType<Guid>().ToList(); Assert.AreEqual(3, res.Count); Assert.AreEqual(1, _grid1.GetCluster().ForNodeIds(res.ElementAt(0)).GetNodes().Count); Assert.AreEqual(1, _grid1.GetCluster().ForNodeIds(res.ElementAt(1)).GetNodes().Count); Assert.AreEqual(1, _grid1.GetCluster().ForNodeIds(res.ElementAt(2)).GetNodes().Count); } /// <summary> /// Test "withTimeout" feature. /// </summary> [Test] public void TestWithTimeout() { var res = _grid1.GetCompute().WithTimeout(1000).ExecuteJavaTask<ICollection>(BroadcastTask, null) .OfType<Guid>().ToList(); Assert.AreEqual(3, res.Count); Assert.AreEqual(1, _grid1.GetCluster().ForNodeIds(res.ElementAt(0)).GetNodes().Count); Assert.AreEqual(1, _grid1.GetCluster().ForNodeIds(res.ElementAt(1)).GetNodes().Count); Assert.AreEqual(1, _grid1.GetCluster().ForNodeIds(res.ElementAt(2)).GetNodes().Count); } /// <summary> /// Test simple dotNet task execution. /// </summary> [Test] public void TestNetTaskSimple() { int res = _grid1.GetCompute().Execute<NetSimpleJobArgument, NetSimpleJobResult, NetSimpleTaskResult>( typeof(NetSimpleTask), new NetSimpleJobArgument(1)).Res; Assert.AreEqual(_grid1.GetCompute().ClusterGroup.GetNodes().Count, res); } /// <summary> /// Tests the exceptions. /// </summary> [Test] public void TestExceptions() { Assert.Throws<BinaryObjectException>(() => _grid1.GetCompute().Broadcast(new InvalidComputeAction())); Assert.Throws<BinaryObjectException>( () => _grid1.GetCompute().Execute<NetSimpleJobArgument, NetSimpleJobResult, NetSimpleTaskResult>( typeof (NetSimpleTask), new NetSimpleJobArgument(-1))); } /// <summary> /// Tests the footer setting. /// </summary> [Test] public void TestFooterSetting() { Assert.AreEqual(CompactFooter, ((Ignite)_grid1).Marshaller.CompactFooter); foreach (var g in new[] {_grid1, _grid2, _grid3}) Assert.AreEqual(CompactFooter, g.GetConfiguration().BinaryConfiguration.CompactFooter); } /// <summary> /// Create configuration. /// </summary> /// <param name="path">XML config path.</param> private IgniteConfiguration Configuration(string path) { IgniteConfiguration cfg = new IgniteConfiguration(); BinaryConfiguration portCfg = new BinaryConfiguration(); var portTypeCfgs = new List<BinaryTypeConfiguration> { new BinaryTypeConfiguration(typeof (PlatformComputeBinarizable)), new BinaryTypeConfiguration(typeof (PlatformComputeNetBinarizable)), new BinaryTypeConfiguration(JavaBinaryCls), new BinaryTypeConfiguration(typeof(PlatformComputeEnum)), new BinaryTypeConfiguration(typeof(InteropComputeEnumFieldTest)) }; portCfg.TypeConfigurations = portTypeCfgs; cfg.BinaryConfiguration = portCfg; cfg.JvmClasspath = Classpath.CreateClasspath(cfg, true); cfg.JvmOptions = TestUtils.TestJavaOptions(); cfg.SpringConfigUrl = path; return cfg; } } class PlatformComputeBinarizable { public int Field { get; set; } } class PlatformComputeNetBinarizable : PlatformComputeBinarizable { } [Serializable] class NetSimpleTask : IComputeTask<NetSimpleJobArgument, NetSimpleJobResult, NetSimpleTaskResult> { /** <inheritDoc /> */ public IDictionary<IComputeJob<NetSimpleJobResult>, IClusterNode> Map(IList<IClusterNode> subgrid, NetSimpleJobArgument arg) { var jobs = new Dictionary<IComputeJob<NetSimpleJobResult>, IClusterNode>(); for (int i = 0; i < subgrid.Count; i++) { var job = arg.Arg > 0 ? new NetSimpleJob {Arg = arg} : new InvalidNetSimpleJob(); jobs[job] = subgrid[i]; } return jobs; } /** <inheritDoc /> */ public ComputeJobResultPolicy OnResult(IComputeJobResult<NetSimpleJobResult> res, IList<IComputeJobResult<NetSimpleJobResult>> rcvd) { return ComputeJobResultPolicy.Wait; } /** <inheritDoc /> */ public NetSimpleTaskResult Reduce(IList<IComputeJobResult<NetSimpleJobResult>> results) { return new NetSimpleTaskResult(results.Sum(res => res.Data.Res)); } } [Serializable] class NetSimpleJob : IComputeJob<NetSimpleJobResult> { public NetSimpleJobArgument Arg; /** <inheritDoc /> */ public NetSimpleJobResult Execute() { return new NetSimpleJobResult(Arg.Arg); } /** <inheritDoc /> */ public void Cancel() { // No-op. } } class InvalidNetSimpleJob : NetSimpleJob { // No-op. } [Serializable] class NetSimpleJobArgument { public int Arg; public NetSimpleJobArgument(int arg) { Arg = arg; } } [Serializable] class NetSimpleTaskResult { public int Res; public NetSimpleTaskResult(int res) { Res = res; } } [Serializable] class NetSimpleJobResult { public int Res; public NetSimpleJobResult(int res) { Res = res; } } [Serializable] class ComputeAction : IComputeAction { [InstanceResource] #pragma warning disable 649 private IIgnite _grid; public static int InvokeCount; public static Guid LastNodeId; public void Invoke() { Thread.Sleep(10); Interlocked.Increment(ref InvokeCount); LastNodeId = _grid.GetCluster().GetLocalNode().Id; } } class InvalidComputeAction : ComputeAction { // No-op. } interface IUserInterface<out T> { T Invoke(); } interface INestedComputeFunc : IComputeFunc<int> { } [Serializable] class ComputeFunc : INestedComputeFunc, IUserInterface<int> { [InstanceResource] private IIgnite _grid; public static int InvokeCount; public static Guid LastNodeId; int IComputeFunc<int>.Invoke() { InvokeCount++; LastNodeId = _grid.GetCluster().GetLocalNode().Id; return InvokeCount; } int IUserInterface<int>.Invoke() { // Same signature as IComputeFunc<int>, but from different interface throw new Exception("Invalid method"); } public int Invoke() { // Same signature as IComputeFunc<int>, but due to explicit interface implementation this is a wrong method throw new Exception("Invalid method"); } } public enum PlatformComputeEnum { Foo, Bar, Baz } public class InteropComputeEnumFieldTest { public PlatformComputeEnum InteropEnum { get; set; } } }
// // AudioType.cs: // // Authors: // Miguel de Icaza ([email protected]) // AKIHIRO Uehara ([email protected]) // Marek Safar ([email protected]) // // Copyright 2009, 2010 Novell, Inc // Copyright 2010, Reinforce Lab. // Copyright 2011, 2012 Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Text; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Diagnostics; using MonoMac.CoreFoundation; using MonoMac.ObjCRuntime; using MonoMac.Foundation; namespace MonoMac.AudioToolbox { public enum AudioFormatType { LinearPCM = 0x6c70636d, AC3 = 0x61632d33, CAC3 = 0x63616333, AppleIMA4 = 0x696d6134, MPEG4AAC = 0x61616320, MPEG4CELP = 0x63656c70, MPEG4HVXC = 0x68767863, MPEG4TwinVQ = 0x74777671, MACE3 = 0x4d414333, MACE6 = 0x4d414336, ULaw = 0x756c6177, ALaw = 0x616c6177, QDesign = 0x51444d43, QDesign2 = 0x51444d32, QUALCOMM = 0x51636c70, MPEGLayer1 = 0x2e6d7031, MPEGLayer2 = 0x2e6d7032, MPEGLayer3 = 0x2e6d7033, TimeCode = 0x74696d65, MIDIStream = 0x6d696469, ParameterValueStream = 0x61707673, AppleLossless = 0x616c6163, MPEG4AAC_HE = 0x61616368, MPEG4AAC_LD = 0x6161636c, MPEG4AAC_ELD = 0x61616365, // 'aace' MPEG4AAC_ELD_SBR = 0x61616366, // 'aacf', MPEG4AAC_ELD_V2 = 0x61616367, // 'aacg', MPEG4AAC_HE_V2 = 0x61616370, MPEG4AAC_Spatial = 0x61616373, AMR = 0x73616d72, Audible = 0x41554442, iLBC = 0x696c6263, DVIIntelIMA = 0x6d730011, MicrosoftGSM = 0x6d730031, AES3 = 0x61657333, } [Flags] public enum AudioFormatFlags : uint { IsFloat = (1 << 0), // 0x1 IsBigEndian = (1 << 1), // 0x2 IsSignedInteger = (1 << 2), // 0x4 IsPacked = (1 << 3), // 0x8 IsAlignedHigh = (1 << 4), // 0x10 IsNonInterleaved = (1 << 5), // 0x20 IsNonMixable = (1 << 6), // 0x40 FlagsAreAllClear = unchecked((uint)(1 << 31)), LinearPCMIsFloat = (1 << 0), // 0x1 LinearPCMIsBigEndian = (1 << 1), // 0x2 LinearPCMIsSignedInteger = (1 << 2), // 0x4 LinearPCMIsPacked = (1 << 3), // 0x8 LinearPCMIsAlignedHigh = (1 << 4), // 0x10 LinearPCMIsNonInterleaved = (1 << 5), // 0x20 LinearPCMIsNonMixable = (1 << 6), // 0x40 LinearPCMSampleFractionShift = 7, LinearPCMSampleFractionMask = 0x3F << (int)LinearPCMSampleFractionShift, LinearPCMFlagsAreAllClear = FlagsAreAllClear, AppleLossless16BitSourceData = 1, AppleLossless20BitSourceData = 2, AppleLossless24BitSourceData = 3, AppleLossless32BitSourceData = 4 } [StructLayout (LayoutKind.Sequential)] unsafe struct AudioFormatInfo { public AudioStreamBasicDescription AudioStreamBasicDescription; public byte* MagicCookieWeak; public int MagicCookieSize; } [DebuggerDisplay ("{FormatName}")] [StructLayout(LayoutKind.Sequential)] public struct AudioStreamBasicDescription { public double SampleRate; public AudioFormatType Format; public AudioFormatFlags FormatFlags; public int BytesPerPacket; // uint public int FramesPerPacket; // uint public int BytesPerFrame; // uint public int ChannelsPerFrame; // uint public int BitsPerChannel; // uint public int Reserved; // uint public const double AudioStreamAnyRate = 0; const int AudioUnitSampleFractionBits = 24; const AudioFormatFlags AudioFormatFlagIsBigEndian = 0; public static readonly AudioFormatFlags AudioFormatFlagsAudioUnitCanonical = AudioFormatFlags.IsSignedInteger | AudioFormatFlagIsBigEndian | AudioFormatFlags.IsPacked | AudioFormatFlags.IsNonInterleaved | (AudioFormatFlags) (AudioUnitSampleFractionBits << (int)AudioFormatFlags.LinearPCMSampleFractionShift); public AudioStreamBasicDescription (AudioFormatType formatType) : this () { Format = formatType; } public static AudioStreamBasicDescription CreateLinearPCM (double sampleRate = 44100, uint channelsPerFrame = 2, uint bitsPerChannel = 16, bool bigEndian = false) { var desc = new AudioStreamBasicDescription (AudioFormatType.LinearPCM); desc.SampleRate = sampleRate; desc.ChannelsPerFrame = (int) channelsPerFrame; desc.BitsPerChannel = (int) bitsPerChannel; desc.BytesPerPacket = desc.BytesPerFrame = (int) channelsPerFrame * sizeof (Int16); desc.FramesPerPacket = 1; desc.FormatFlags = AudioFormatFlags.IsSignedInteger | AudioFormatFlags.IsPacked; if (bigEndian) desc.FormatFlags |= AudioFormatFlags.IsBigEndian; return desc; } public unsafe static AudioChannelLayoutTag[] GetAvailableEncodeChannelLayoutTags (AudioStreamBasicDescription format) { var type_size = sizeof (AudioStreamBasicDescription); uint size; if (AudioFormatPropertyNative.AudioFormatGetPropertyInfo (AudioFormatProperty.AvailableEncodeChannelLayoutTags, type_size, ref format, out size) != 0) return null; var data = new AudioChannelLayoutTag[size / sizeof (AudioChannelLayoutTag)]; fixed (AudioChannelLayoutTag* ptr = data) { var res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.AvailableEncodeChannelLayoutTags, type_size, ref format, ref size, (int*)ptr); if (res != 0) return null; return data; } } public unsafe static int[] GetAvailableEncodeNumberChannels (AudioStreamBasicDescription format) { uint size; if (AudioFormatPropertyNative.AudioFormatGetPropertyInfo (AudioFormatProperty.AvailableEncodeNumberChannels, sizeof (AudioStreamBasicDescription), ref format, out size) != 0) return null; var data = new int[size / sizeof (int)]; fixed (int* ptr = data) { var res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.AvailableEncodeNumberChannels, sizeof (AudioStreamBasicDescription), ref format, ref size, ptr); if (res != 0) return null; return data; } } public unsafe AudioFormat[] GetOutputFormatList (byte[] magicCookie = null) { var afi = new AudioFormatInfo (); afi.AudioStreamBasicDescription = this; var type_size = sizeof (AudioFormat); uint size; if (AudioFormatPropertyNative.AudioFormatGetPropertyInfo (AudioFormatProperty.OutputFormatList, type_size, ref afi, out size) != 0) return null; Debug.Assert (sizeof (AudioFormat) == type_size); var data = new AudioFormat[size / type_size]; fixed (AudioFormat* ptr = &data[0]) { var res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.OutputFormatList, type_size, ref afi, ref size, ptr); if (res != 0) return null; Array.Resize (ref data, (int) size / type_size); return data; } } public unsafe AudioFormat[] GetFormatList (byte[] magicCookie) { if (magicCookie == null) throw new ArgumentNullException ("magicCookie"); var afi = new AudioFormatInfo (); afi.AudioStreamBasicDescription = this; fixed (byte* b = magicCookie) { afi.MagicCookieWeak = b; afi.MagicCookieSize = magicCookie.Length; var type_size = sizeof (AudioFormat); uint size; if (AudioFormatPropertyNative.AudioFormatGetPropertyInfo (AudioFormatProperty.FormatList, type_size, ref afi, out size) != 0) return null; Debug.Assert (sizeof (AudioFormat) == type_size); var data = new AudioFormat[size / type_size]; fixed (AudioFormat* ptr = &data[0]) { var res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.FormatList, type_size, ref afi, ref size, ptr); if (res != 0) return null; Array.Resize (ref data, (int)size / type_size); return data; } } } public static AudioFormatError GetFormatInfo (ref AudioStreamBasicDescription format) { unsafe { var size = sizeof (AudioStreamBasicDescription); return AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.FormatInfo, 0, IntPtr.Zero, ref size, ref format); } } public unsafe string FormatName { get { IntPtr ptr; var size = sizeof (IntPtr); if (AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.FormatName, sizeof (AudioStreamBasicDescription), ref this, ref size, out ptr) != 0) return null; return new CFString (ptr, true); } } public unsafe bool IsEncrypted { get { uint data; var size = sizeof (uint); if (AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.FormatIsEncrypted, sizeof (AudioStreamBasicDescription), ref this, ref size, out data) != 0) return false; return data != 0; } } public unsafe bool IsExternallyFramed { get { uint data; var size = sizeof (uint); if (AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.FormatIsExternallyFramed, sizeof (AudioStreamBasicDescription), ref this, ref size, out data) != 0) return false; return data != 0; } } public unsafe bool IsVariableBitrate { get { uint data; var size = sizeof (uint); if (AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.FormatName, sizeof (AudioStreamBasicDescription), ref this, ref size, out data) != 0) return false; return data != 0; } } public override string ToString () { return String.Format ("[SampleRate={0} FormatID={1} FormatFlags={2} BytesPerPacket={3} FramesPerPacket={4} BytesPerFrame={5} ChannelsPerFrame={6} BitsPerChannel={7}]", SampleRate, Format, FormatFlags, BytesPerPacket, FramesPerPacket, BytesPerFrame, ChannelsPerFrame, BitsPerChannel); } } [StructLayout(LayoutKind.Sequential)] public struct AudioStreamPacketDescription { public long StartOffset; public int VariableFramesInPacket; public int DataByteSize; public override string ToString () { return String.Format ("StartOffset={0} VariableFramesInPacket={1} DataByteSize={2}", StartOffset, VariableFramesInPacket, DataByteSize); } } [Flags] public enum AudioChannelFlags { AllOff = 0, RectangularCoordinates = 1 << 0, SphericalCoordinates = 1 << 1, Meters = 1 << 2 } public enum AudioChannelLabel { Unknown = -1, Unused = 0, UseCoordinates = 100, Left = 1, Right = 2, Center = 3, LFEScreen = 4, LeftSurround = 5, RightSurround = 6, LeftCenter = 7, RightCenter = 8, CenterSurround = 9, LeftSurroundDirect = 10, RightSurroundDirect = 11, TopCenterSurround = 12, VerticalHeightLeft = 13, VerticalHeightCenter = 14, VerticalHeightRight = 15, TopBackLeft = 16, TopBackCenter = 17, TopBackRight = 18, RearSurroundLeft = 33, RearSurroundRight = 34, LeftWide = 35, RightWide = 36, LFE2 = 37, LeftTotal = 38, RightTotal = 39, HearingImpaired = 40, Narration = 41, Mono = 42, DialogCentricMix = 43, CenterSurroundDirect = 44, Haptic = 45, // first order ambisonic channels Ambisonic_W = 200, Ambisonic_X = 201, Ambisonic_Y = 202, Ambisonic_Z = 203, // Mid/Side Recording MS_Mid = 204, MS_Side = 205, // X-Y Recording XY_X = 206, XY_Y = 207, // other HeadphonesLeft = 301, HeadphonesRight = 302, ClickTrack = 304, ForeignLanguage = 305, // generic discrete channel Discrete = 400, // numbered discrete channel Discrete_0 = (1<<16) | 0, Discrete_1 = (1<<16) | 1, Discrete_2 = (1<<16) | 2, Discrete_3 = (1<<16) | 3, Discrete_4 = (1<<16) | 4, Discrete_5 = (1<<16) | 5, Discrete_6 = (1<<16) | 6, Discrete_7 = (1<<16) | 7, Discrete_8 = (1<<16) | 8, Discrete_9 = (1<<16) | 9, Discrete_10 = (1<<16) | 10, Discrete_11 = (1<<16) | 11, Discrete_12 = (1<<16) | 12, Discrete_13 = (1<<16) | 13, Discrete_14 = (1<<16) | 14, Discrete_15 = (1<<16) | 15, Discrete_65535 = (1<<16) | 65535 } [Flags] public enum AudioChannelBit { Left = 1<<0, Right = 1<<1, Center = 1<<2, LFEScreen = 1<<3, LeftSurround = 1<<4, RightSurround = 1<<5, LeftCenter = 1<<6, RightCenter = 1<<7, CenterSurround = 1<<8, LeftSurroundDirect = 1<<9, RightSurroundDirect = 1<<10, TopCenterSurround = 1<<11, VerticalHeightLeft = 1<<12, VerticalHeightCenter = 1<<13, VerticalHeightRight = 1<<14, TopBackLeft = 1<<15, TopBackCenter = 1<<16, TopBackRight = 1<<17 } [StructLayout (LayoutKind.Sequential)] public struct AudioChannelDescription { public AudioChannelLabel Label; public AudioChannelFlags Flags; float Coord0, Coord1, Coord2; public float [] Coords { get { return new float [3] { Coord0, Coord1, Coord2 }; } set { if (value.Length != 3) throw new ArgumentException ("Must contain three floats"); Coord0 = value [0]; Coord1 = value [1]; Coord2 = value [2]; } } public unsafe string Name { get { IntPtr sptr; int size = sizeof (IntPtr); int ptr_size = sizeof (AudioChannelDescription); var ptr = ToPointer (); var res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.ChannelName, ptr_size, ptr, ref size, out sptr); Marshal.FreeHGlobal (ptr); if (res != 0) return null; return new CFString (sptr, true); } } public unsafe string ShortName { get { IntPtr sptr; int size = sizeof (IntPtr); int ptr_size = sizeof (AudioChannelDescription); var ptr = ToPointer (); var res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.ChannelShortName, ptr_size, ptr, ref size, out sptr); Marshal.FreeHGlobal (ptr); if (res != 0) return null; return new CFString (sptr, true); } } internal unsafe IntPtr ToPointer () { var ptr = (AudioChannelDescription *) Marshal.AllocHGlobal (sizeof (AudioChannelLabel) + sizeof (AudioChannelFlags) + 3 * sizeof (float)); *ptr = this; return (IntPtr) ptr; } public override string ToString () { return String.Format ("[id={0} {1} - {2},{3},{4}", Label, Flags, Coords [0], Coords[1], Coords[2]); } } public enum AudioChannelLayoutTag : uint { UseChannelDescriptions = (0<<16) | 0, UseChannelBitmap = (1<<16) | 0, Mono = (100<<16) | 1, Stereo = (101<<16) | 2, StereoHeadphones = (102<<16) | 2, MatrixStereo = (103<<16) | 2, MidSide = (104<<16) | 2, XY = (105<<16) | 2, Binaural = (106<<16) | 2, Ambisonic_B_Format = (107<<16) | 4, Quadraphonic = (108<<16) | 4, Pentagonal = (109<<16) | 5, Hexagonal = (110<<16) | 6, Octagonal = (111<<16) | 8, Cube = (112<<16) | 8, MPEG_1_0 = Mono, MPEG_2_0 = Stereo, MPEG_3_0_A = (113<<16) | 3, MPEG_3_0_B = (114<<16) | 3, MPEG_4_0_A = (115<<16) | 4, MPEG_4_0_B = (116<<16) | 4, MPEG_5_0_A = (117<<16) | 5, MPEG_5_0_B = (118<<16) | 5, MPEG_5_0_C = (119<<16) | 5, MPEG_5_0_D = (120<<16) | 5, MPEG_5_1_A = (121<<16) | 6, MPEG_5_1_B = (122<<16) | 6, MPEG_5_1_C = (123<<16) | 6, MPEG_5_1_D = (124<<16) | 6, MPEG_6_1_A = (125<<16) | 7, MPEG_7_1_A = (126<<16) | 8, MPEG_7_1_B = (127<<16) | 8, MPEG_7_1_C = (128<<16) | 8, Emagic_Default_7_1 = (129<<16) | 8, SMPTE_DTV = (130<<16) | 8, ITU_1_0 = Mono, ITU_2_0 = Stereo, ITU_2_1 = (131<<16) | 3, ITU_2_2 = (132<<16) | 4, ITU_3_0 = MPEG_3_0_A, ITU_3_1 = MPEG_4_0_A, ITU_3_2 = MPEG_5_0_A, ITU_3_2_1 = MPEG_5_1_A, ITU_3_4_1 = MPEG_7_1_C, DVD_0 = Mono, DVD_1 = Stereo, DVD_2 = ITU_2_1, DVD_3 = ITU_2_2, DVD_4 = (133<<16) | 3, DVD_5 = (134<<16) | 4, DVD_6 = (135<<16) | 5, DVD_7 = MPEG_3_0_A, DVD_8 = MPEG_4_0_A, DVD_9 = MPEG_5_0_A, DVD_10 = (136<<16) | 4, DVD_11 = (137<<16) | 5, DVD_12 = MPEG_5_1_A, DVD_13 = DVD_8, DVD_14 = DVD_9, DVD_15 = DVD_10, DVD_16 = DVD_11, DVD_17 = DVD_12, DVD_18 = (138<<16) | 5, DVD_19 = MPEG_5_0_B, DVD_20 = MPEG_5_1_B, AudioUnit_4 = Quadraphonic, AudioUnit_5 = Pentagonal, AudioUnit_6 = Hexagonal, AudioUnit_8 = Octagonal, AudioUnit_5_0 = MPEG_5_0_B, AudioUnit_6_0 = (139<<16) | 6, AudioUnit_7_0 = (140<<16) | 7, AudioUnit_7_0_Front = (148<<16) | 7, AudioUnit_5_1 = MPEG_5_1_A, AudioUnit_6_1 = MPEG_6_1_A, AudioUnit_7_1 = MPEG_7_1_C, AudioUnit_7_1_Front = MPEG_7_1_A, AAC_3_0 = MPEG_3_0_B, AAC_Quadraphonic = Quadraphonic, AAC_4_0 = MPEG_4_0_B, AAC_5_0 = MPEG_5_0_D, AAC_5_1 = MPEG_5_1_D, AAC_6_0 = (141<<16) | 6, AAC_6_1 = (142<<16) | 7, AAC_7_0 = (143<<16) | 7, AAC_7_1 = MPEG_7_1_B, AAC_Octagonal = (144<<16) | 8, TMH_10_2_std = (145<<16) | 16, TMH_10_2_full = (146<<16) | 21, AC3_1_0_1 = (149<<16) | 2, AC3_3_0 = (150<<16) | 3, AC3_3_1 = (151<<16) | 4, AC3_3_0_1 = (152<<16) | 4, AC3_2_1_1 = (153<<16) | 4, AC3_3_1_1 = (154<<16) | 5, EAC_6_0_A = (155<<16) | 6, EAC_7_0_A = (156<<16) | 7, EAC3_6_1_A = (157<<16) | 7, EAC3_6_1_B = (158<<16) | 7, EAC3_6_1_C = (159<<16) | 7, EAC3_7_1_A = (160<<16) | 8, EAC3_7_1_B = (161<<16) | 8, EAC3_7_1_C = (162<<16) | 8, EAC3_7_1_D = (163<<16) | 8, EAC3_7_1_E = (164<<16) | 8, EAC3_7_1_F = (165<<16) | 8, EAC3_7_1_G = (166<<16) | 8, EAC3_7_1_H = (167<<16) | 8, DTS_3_1 = (168<<16) | 4, DTS_4_1 = (169<<16) | 5, DTS_6_0_A = (170<<16) | 6, DTS_6_0_B = (171<<16) | 6, DTS_6_0_C = (172<<16) | 6, DTS_6_1_A = (173<<16) | 7, DTS_6_1_B = (174<<16) | 7, DTS_6_1_C = (175<<16) | 7, DTS_7_0 = (176<<16) | 7, DTS_7_1 = (177<<16) | 8, DTS_8_0_A = (178<<16) | 8, DTS_8_0_B = (179<<16) | 8, DTS_8_1_A = (180<<16) | 9, DTS_8_1_B = (181<<16) | 9, DTS_6_1_D = (182<<16) | 7, DiscreteInOrder = (147<<16) | 0, // needs to be ORed with the actual number of channels Unknown = 0xFFFF0000 // needs to be ORed with the actual number of channels } public static class AudioChannelLayoutTagExtensions { public static AudioChannelBit? ToAudioChannel (this AudioChannelLayoutTag layoutTag) { int value; int size = sizeof (uint); int layout = (int) layoutTag; if (AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.BitmapForLayoutTag, sizeof (AudioChannelLayoutTag), ref layout, ref size, out value) != 0) return null; return (AudioChannelBit) value; } } [DebuggerDisplay ("{Name}")] public class AudioChannelLayout { public AudioChannelLayout () { } internal unsafe AudioChannelLayout (IntPtr h) { AudioTag = (AudioChannelLayoutTag) Marshal.ReadInt32 (h, 0); ChannelUsage = (AudioChannelBit) Marshal.ReadInt32 (h, 4); Channels = new AudioChannelDescription [Marshal.ReadInt32 (h, 8)]; int p = 12; int size = sizeof (AudioChannelDescription); for (int i = 0; i < Channels.Length; i++){ Channels [i] = *(AudioChannelDescription *) (unchecked (((byte *) h) + p)); p += size; } } [Advice ("Use the strongly typed AudioTag instead")] public int Tag { get { return (int) AudioTag; } set { AudioTag = (AudioChannelLayoutTag) value; } } [Advice ("Use ChannelUsage instead")] public int Bitmap { get { return (int) ChannelUsage; } set { ChannelUsage = (AudioChannelBit) value; } } public AudioChannelLayoutTag AudioTag; public AudioChannelBit ChannelUsage; public AudioChannelDescription[] Channels; public unsafe string Name { get { IntPtr sptr; int size = sizeof (IntPtr); int ptr_size; var ptr = ToBlock (out ptr_size); var res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.ChannelLayoutName, ptr_size, ptr, ref size, out sptr); Marshal.FreeHGlobal (ptr); if (res != 0) return null; return new CFString (sptr, true); } } public unsafe string SimpleName { get { IntPtr sptr; int size = sizeof (IntPtr); int ptr_size; var ptr = ToBlock (out ptr_size); var res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.ChannelLayoutSimpleName, ptr_size, ptr, ref size, out sptr); Marshal.FreeHGlobal (ptr); if (res != 0) return null; return new CFString (sptr, true); } } public static AudioChannelLayout FromAudioChannelBitmap (AudioChannelBit channelBitmap) { return GetChannelLayout (AudioFormatProperty.ChannelLayoutForBitmap, (int) channelBitmap); } public static AudioChannelLayout FromAudioChannelLayoutTag (AudioChannelLayoutTag channelLayoutTag) { return GetChannelLayout (AudioFormatProperty.ChannelLayoutForTag, (int) channelLayoutTag); } static AudioChannelLayout GetChannelLayout (AudioFormatProperty property, int value) { int size; AudioFormatPropertyNative.AudioFormatGetPropertyInfo (property, sizeof (AudioFormatProperty), ref value, out size); AudioChannelLayout layout; IntPtr ptr = Marshal.AllocHGlobal (size); if (AudioFormatPropertyNative.AudioFormatGetProperty (property, sizeof (AudioFormatProperty), ref value, ref size, ptr) == 0) layout = new AudioChannelLayout (ptr); else layout = null; Marshal.FreeHGlobal (ptr); return layout; } internal static AudioChannelLayout FromHandle (IntPtr handle) { if (handle == IntPtr.Zero) return null; return new AudioChannelLayout (handle); } public override string ToString () { return String.Format ("AudioChannelLayout: Tag={0} Bitmap={1} Channels={2}", AudioTag, ChannelUsage, Channels.Length); } // The returned block must be released with FreeHGlobal internal unsafe IntPtr ToBlock (out int size) { if (Channels == null) throw new ArgumentNullException ("Channels"); var desc_size = sizeof (AudioChannelDescription); size = 12 + Channels.Length * desc_size; IntPtr buffer = Marshal.AllocHGlobal (size); Marshal.WriteInt32 (buffer, (int) AudioTag); Marshal.WriteInt32 (buffer, 4, (int) ChannelUsage); Marshal.WriteInt32 (buffer, 8, Channels.Length); AudioChannelDescription *dest = (AudioChannelDescription *) ((byte *) buffer + 12); foreach (var desc in Channels){ *dest = desc; dest++; } return buffer; } public static AudioFormatError Validate (AudioChannelLayout layout) { if (layout == null) throw new ArgumentNullException ("layout"); int ptr_size; var ptr = layout.ToBlock (out ptr_size); var res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.ValidateChannelLayout, ptr_size, ptr, IntPtr.Zero, IntPtr.Zero); Marshal.FreeHGlobal (ptr); return res; } public unsafe static int[] GetChannelMap (AudioChannelLayout inputLayout, AudioChannelLayout outputLayout) { if (inputLayout == null) throw new ArgumentNullException ("inputLayout"); if (outputLayout == null) throw new ArgumentNullException ("outputLayout"); var channels_count = GetNumberOfChannels (outputLayout); if (channels_count == null) throw new ArgumentException ("outputLayout"); int ptr_size; var input_ptr = inputLayout.ToBlock (out ptr_size); var output_ptr = outputLayout.ToBlock (out ptr_size); var array = new IntPtr[] { input_ptr, output_ptr }; ptr_size = sizeof (IntPtr) * array.Length; int[] value; AudioFormatError res; fixed (IntPtr* ptr = &array[0]) { value = new int[channels_count.Value]; var size = sizeof (int) * value.Length; fixed (int* value_ptr = &value[0]) { res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.ChannelMap, ptr_size, ptr, ref size, value_ptr); } } Marshal.FreeHGlobal (input_ptr); Marshal.FreeHGlobal (output_ptr); return res == 0 ? value : null; } public unsafe static float[,] GetMatrixMixMap (AudioChannelLayout inputLayout, AudioChannelLayout outputLayout) { if (inputLayout == null) throw new ArgumentNullException ("inputLayout"); if (outputLayout == null) throw new ArgumentNullException ("outputLayout"); var channels_count_output = GetNumberOfChannels (outputLayout); if (channels_count_output == null) throw new ArgumentException ("outputLayout"); var channels_count_input = GetNumberOfChannels (inputLayout); if (channels_count_input == null) throw new ArgumentException ("inputLayout"); int ptr_size; var input_ptr = inputLayout.ToBlock (out ptr_size); var output_ptr = outputLayout.ToBlock (out ptr_size); var array = new IntPtr[] { input_ptr, output_ptr }; ptr_size = sizeof (IntPtr) * array.Length; float[,] value; AudioFormatError res; fixed (IntPtr* ptr = &array[0]) { value = new float[channels_count_input.Value, channels_count_output.Value]; var size = sizeof (float) * channels_count_input.Value * channels_count_output.Value; fixed (float* value_ptr = &value[0, 0]) { res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.MatrixMixMap, ptr_size, ptr, ref size, value_ptr); } } Marshal.FreeHGlobal (input_ptr); Marshal.FreeHGlobal (output_ptr); return res == 0 ? value : null; } public static int? GetNumberOfChannels (AudioChannelLayout layout) { if (layout == null) throw new ArgumentNullException ("layout"); int ptr_size; var ptr = layout.ToBlock (out ptr_size); int size = sizeof (int); int value; var res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.NumberOfChannelsForLayout, ptr_size, ptr, ref size, out value); Marshal.FreeHGlobal (ptr); return res != 0 ? null : (int?) value; } public static AudioChannelLayoutTag? GetTagForChannelLayout (AudioChannelLayout layout) { if (layout == null) throw new ArgumentNullException ("layout"); int ptr_size; var ptr = layout.ToBlock (out ptr_size); int size = sizeof (AudioChannelLayoutTag); int value; var res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.TagForChannelLayout, ptr_size, ptr, ref size, out value); Marshal.FreeHGlobal (ptr); return res != 0 ? null : (AudioChannelLayoutTag?) value; } public unsafe static AudioChannelLayoutTag[] GetTagsForNumberOfChannels (int count) { const int type_size = sizeof (uint); int size; if (AudioFormatPropertyNative.AudioFormatGetPropertyInfo (AudioFormatProperty.TagsForNumberOfChannels, type_size, ref count, out size) != 0) return null; var data = new AudioChannelLayoutTag[size / type_size]; fixed (AudioChannelLayoutTag* ptr = data) { var res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.TagsForNumberOfChannels, type_size, ref count, ref size, (int*)ptr); if (res != 0) return null; return data; } } #if !COREBUILD public NSData AsData () { int size; var p = ToBlock (out size); var result = NSData.FromBytes (p, (uint) size); Marshal.FreeHGlobal (p); return result; } #endif } [StructLayout(LayoutKind.Sequential)] public struct SmpteTime { public short Subframes; public short SubframeDivisor; public uint Counter; public uint Type; public uint Flags; public short Hours; public short Minutes; public short Seconds; public short Frames; public override string ToString () { return String.Format ("[Subframes={0},Divisor={1},Counter={2},Type={3},Flags={4},Hours={5},Minutes={6},Seconds={7},Frames={8}]", Subframes, SubframeDivisor, Counter, Type, Flags, Hours, Minutes, Seconds, Frames); } } public enum SmpteTimeType { None = 0, Type24 = 1, Type25 = 2, Type30Drop = 3, Type30 = 4, Type2997 = 5, Type2997Drop = 6, Type60 = 7, Type5994 = 8, Type60Drop = 9, Type5994Drop = 10, Type50 = 11, Type2398 = 12 } [StructLayout(LayoutKind.Sequential)] public struct AudioTimeStamp { [Flags] public enum AtsFlags { SampleTimeValid = (1 << 0), HostTimeValid = (1 << 1), RateScalarValid = (1 << 2), WordClockTimeValid = (1 << 3), SmpteTimeValid = (1 << 4), SampleHostTimeValid = SampleTimeValid | HostTimeValid } public double SampleTime; public ulong HostTime; public double RateScalar; public ulong WordClockTime; public SmpteTime SMPTETime; public AtsFlags Flags; public uint Reserved; public override string ToString () { var sb = new StringBuilder ("{"); if ((Flags & AtsFlags.SampleTimeValid) != 0) sb.Append ("SampleTime=" + SampleTime.ToString ()); if ((Flags & AtsFlags.HostTimeValid) != 0){ if (sb.Length > 0) sb.Append (','); sb.Append ("HostTime=" + HostTime.ToString ()); } if ((Flags & AtsFlags.RateScalarValid) != 0){ if (sb.Length > 0) sb.Append (','); sb.Append ("RateScalar=" + RateScalar.ToString ()); } if ((Flags & AtsFlags.WordClockTimeValid) != 0){ if (sb.Length > 0) sb.Append (','); sb.Append ("WordClock=" + HostTime.ToString () + ","); } if ((Flags & AtsFlags.SmpteTimeValid) != 0){ if (sb.Length > 0) sb.Append (','); sb.Append ("SmpteTime=" + SMPTETime.ToString ()); } sb.Append ("}"); return sb.ToString (); } } [StructLayout(LayoutKind.Sequential)] public struct AudioBuffer { public int NumberChannels; public int DataByteSize; public IntPtr Data; public override string ToString () { return string.Format ("[channels={0},dataByteSize={1},ptrData=0x{2:x}]", NumberChannels, DataByteSize, Data); } } }
using RestBus.Client.Http; using RestBus.Client.Http.Formatting; using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; namespace RestBus.Client { public static class RestBusClientExtensions { //TODO: Now that a lot of the Formatting source has been moved into the codebase //Take a look at the code again and reimplement unimeplemented exceptions, also see if things like Formatting.TryParseDate should be re-coded where it was skipped #region Regular Client Method Extensions /// <summary>Send a GET request to the specified Uri as an asynchronous operation.</summary> /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The Uri the request is sent to.</param> /// <param name="options">The options for the request.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception> public static Task<HttpResponseMessage> GetAsync(this HttpMessageInvoker client, string requestUri, RequestOptions options) { return GetAsync(client, GetUri(requestUri), options); } /// <summary>Send a GET request to the specified Uri as an asynchronous operation.</summary> /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The Uri the request is sent to.</param> /// <param name="options">The options for the request.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception> public static Task<HttpResponseMessage> GetAsync(this HttpMessageInvoker client, Uri requestUri, RequestOptions options) { return GetAsync(client, requestUri, CancellationToken.None, options); } /// <summary>Send a GET request to the specified Uri with a cancellation token as an asynchronous operation.</summary> /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The Uri the request is sent to.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <param name="options">The options for the request.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception> public static Task<HttpResponseMessage> GetAsync(this HttpMessageInvoker client, string requestUri, CancellationToken cancellationToken, RequestOptions options) { return GetAsync(client, GetUri(requestUri), cancellationToken, options); } /// <summary>Send a GET request to the specified Uri with a cancellation token as an asynchronous operation.</summary> /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The Uri the request is sent to.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <param name="options">The options for the request.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception> public static Task<HttpResponseMessage> GetAsync(this HttpMessageInvoker client, Uri requestUri, CancellationToken cancellationToken, RequestOptions options) { if (client == null) throw new ArgumentNullException("client"); return client.SendAsync(CreateRequest(HttpMethod.Get, requestUri, null, options), cancellationToken); } /// <summary>Send a POST request to the specified Uri as an asynchronous operation.</summary> /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The Uri the request is sent to.</param> /// <param name="content">The HTTP request content sent to the server.</param> /// <param name="options">The options for the request.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception> public static Task<HttpResponseMessage> PostAsync(this HttpMessageInvoker client, string requestUri, HttpContent content, RequestOptions options) { return PostAsync(client, GetUri(requestUri), content, options); } /// <summary>Send a POST request to the specified Uri as an asynchronous operation.</summary> /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The Uri the request is sent to.</param> /// <param name="content">The HTTP request content sent to the server.</param> /// <param name="options">The options for the request.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception> public static Task<HttpResponseMessage> PostAsync(this HttpMessageInvoker client, Uri requestUri, HttpContent content, RequestOptions options) { return PostAsync(client, requestUri, content, CancellationToken.None, options); } /// <summary>Send a POST request with a cancellation token as an asynchronous operation.</summary> /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The Uri the request is sent to.</param> /// <param name="content">The HTTP request content sent to the server.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <param name="options">The options for the request.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception> public static Task<HttpResponseMessage> PostAsync(this HttpMessageInvoker client, string requestUri, HttpContent content, CancellationToken cancellationToken, RequestOptions options) { return PostAsync(client, GetUri(requestUri), content, cancellationToken, options); } /// <summary>Send a POST request with a cancellation token as an asynchronous operation.</summary> /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The Uri the request is sent to.</param> /// <param name="content">The HTTP request content sent to the server.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <param name="options">The options for the request.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception> public static Task<HttpResponseMessage> PostAsync(this HttpMessageInvoker client, Uri requestUri, HttpContent content, CancellationToken cancellationToken, RequestOptions options) { if (client == null) throw new ArgumentNullException("client"); return client.SendAsync(CreateRequest(HttpMethod.Post, requestUri, content, options), cancellationToken); } /// <summary>Send a PUT request to the specified Uri as an asynchronous operation.</summary> /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The Uri the request is sent to.</param> /// <param name="content">The HTTP request content sent to the server.</param> /// <param name="options">The options for the request.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception> public static Task<HttpResponseMessage> PutAsync(this HttpMessageInvoker client, string requestUri, HttpContent content, RequestOptions options) { return PutAsync(client, GetUri(requestUri), content, options); } /// <summary>Send a PUT request to the specified Uri as an asynchronous operation.</summary> /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The Uri the request is sent to.</param> /// <param name="content">The HTTP request content sent to the server.</param> /// <param name="options">The options for the request.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception> public static Task<HttpResponseMessage> PutAsync(this HttpMessageInvoker client, Uri requestUri, HttpContent content, RequestOptions options) { return PutAsync(client, requestUri, content, CancellationToken.None, options); } /// <summary>Send a PUT request with a cancellation token as an asynchronous operation.</summary> /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The Uri the request is sent to.</param> /// <param name="content">The HTTP request content sent to the server.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <param name="options">The options for the request.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception> public static Task<HttpResponseMessage> PutAsync(this HttpMessageInvoker client, string requestUri, HttpContent content, CancellationToken cancellationToken, RequestOptions options) { return PutAsync(client, GetUri(requestUri), content, cancellationToken, options); } /// <summary>Send a PUT request with a cancellation token as an asynchronous operation.</summary> /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The Uri the request is sent to.</param> /// <param name="content">The HTTP request content sent to the server.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <param name="options">The options for the request.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception> public static Task<HttpResponseMessage> PutAsync(this HttpMessageInvoker client, Uri requestUri, HttpContent content, CancellationToken cancellationToken, RequestOptions options) { if (client == null) throw new ArgumentNullException("client"); return client.SendAsync(CreateRequest(HttpMethod.Put, requestUri, content, options), cancellationToken); } /// <summary>Send a DELETE request to the specified Uri as an asynchronous operation.</summary> /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The Uri the request is sent to.</param> /// <param name="options">The options for the request.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception> public static Task<HttpResponseMessage> DeleteAsync(this HttpMessageInvoker client, string requestUri, RequestOptions options) { return DeleteAsync(client, GetUri(requestUri), options); } /// <summary>Send a DELETE request to the specified Uri as an asynchronous operation.</summary> /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The Uri the request is sent to.</param> /// <param name="options">The options for the request.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception> public static Task<HttpResponseMessage> DeleteAsync(this HttpMessageInvoker client, Uri requestUri, RequestOptions options) { return DeleteAsync(client, requestUri, CancellationToken.None, options); } /// <summary>Send a DELETE request to the specified Uri with a cancellation token as an asynchronous operation.</summary> /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The Uri the request is sent to.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <param name="options">The options for the request.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception> public static Task<HttpResponseMessage> DeleteAsync(this HttpMessageInvoker client, string requestUri, CancellationToken cancellationToken, RequestOptions options) { return DeleteAsync(client, GetUri(requestUri), cancellationToken, options); } /// <summary>Send a DELETE request to the specified Uri with a cancellation token as an asynchronous operation.</summary> /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The Uri the request is sent to.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <param name="options">The options for the request.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception> public static Task<HttpResponseMessage> DeleteAsync(this HttpMessageInvoker client, Uri requestUri, CancellationToken cancellationToken, RequestOptions options) { if (client == null) throw new ArgumentNullException("client"); return client.SendAsync(CreateRequest(HttpMethod.Delete, requestUri, null, options), cancellationToken); } /// <summary>Send a GET request to the specified Uri and return the response body as a string in an asynchronous operation.</summary> /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The Uri the request is sent to.</param> /// <param name="options">The options for the request.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception> public static Task<string> GetStringAsync(this HttpMessageInvoker client, string requestUri, RequestOptions options) { return GetStringAsync(client, GetUri(requestUri), options); } /// <summary>Send a GET request to the specified Uri and return the response body as a string in an asynchronous operation.</summary> /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The Uri the request is sent to.</param> /// <param name="options">The options for the request.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception> public static Task<string> GetStringAsync(this HttpMessageInvoker client, Uri requestUri, RequestOptions options) { //TODO: Look into adding Task.ConfigureAwait (false) here return SendAsync(client, new HttpRequestMessage(HttpMethod.Get, requestUri), options) .ContinueWith<string>(task => task.Result.Content.ReadAsStringAsync().Result, TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously ); } /// <summary>Send a GET request to the specified Uri and return the response body as a byte array in an asynchronous operation.</summary> /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The Uri the request is sent to.</param> /// <param name="options">The options for the request.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception> public static Task<byte[]> GetByteArrayAsync(this HttpMessageInvoker client, string requestUri, RequestOptions options) { return GetByteArrayAsync(client, GetUri(requestUri), options); } /// <summary>Send a GET request to the specified Uri and return the response body as a byte array in an asynchronous operation.</summary> /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The Uri the request is sent to.</param> /// <param name="options">The options for the request.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception> public static Task<byte[]> GetByteArrayAsync(this HttpMessageInvoker client, Uri requestUri, RequestOptions options) { //TODO: Look into adding Task.ConfigureAwait (false) here return SendAsync(client, new HttpRequestMessage(HttpMethod.Get, requestUri), options) .ContinueWith<byte[]>(task => task.Result.Content.ReadAsByteArrayAsync().Result, TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously); } /// <summary>Send a GET request to the specified Uri and return the response body as a stream in an asynchronous operation.</summary> /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The Uri the request is sent to.</param> /// <param name="options">The options for the request.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception> public static Task<Stream> GetStreamAsync(this HttpMessageInvoker client, string requestUri, RequestOptions options) { return GetStreamAsync(client, GetUri(requestUri), options); } /// <summary>Send a GET request to the specified Uri and return the response body as a stream in an asynchronous operation.</summary> /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The Uri the request is sent to.</param> /// <param name="options">The options for the request.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception> public static Task<Stream> GetStreamAsync(this HttpMessageInvoker client, Uri requestUri, RequestOptions options) { //TODO: Look into adding Task.ConfigureAwait (false) here return SendAsync(client, new HttpRequestMessage(HttpMethod.Get, requestUri), options) .ContinueWith<Stream>(task => task.Result.Content.ReadAsStreamAsync().Result, TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously); } /// <summary>Send an HTTP request as an asynchronous operation.</summary> /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="request">The HTTP request message to send.</param> /// <param name="options">The options for the request.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="request" /> was null.</exception> public static Task<HttpResponseMessage> SendAsync(this HttpMessageInvoker client, HttpRequestMessage request, RequestOptions options) { return SendAsync(client, request, CancellationToken.None, options); } /// <summary>Send an HTTP request as an asynchronous operation. </summary> /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="request">The HTTP request message to send.</param> /// <param name="cancellationToken">The cancellation token to cancel operation.</param> /// <param name="options">The options for the request.</param> public static Task<HttpResponseMessage> SendAsync(this HttpMessageInvoker client, HttpRequestMessage request, CancellationToken cancellationToken, RequestOptions options) { if (client == null) throw new ArgumentNullException("client"); AttachOptions(request, options); return client.SendAsync(request, cancellationToken); } #endregion #region Formatted Client Method Extensions /// <summary>Sends a POST request as an asynchronous operation, with a specified value serialized as JSON.</summary> /// <returns>A task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The URI the request is sent to.</param> /// <param name="value">The value to write into the entity body of the request.</param> /// <param name="options">The options for the request.</param> /// <typeparam name="T">The type of object to serialize.</typeparam> public static Task<HttpResponseMessage> PostAsJsonAsync<T>(this HttpMessageInvoker client, string requestUri, T value, RequestOptions options) { return client.PostAsJsonAsync(requestUri, value, CancellationToken.None, options); } /// <summary>Sends a POST request as an asynchronous operation, with a specified value serialized as JSON. Includes a cancellation token to cancel the request.</summary> /// <returns>A task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The URI the request is sent to.</param> /// <param name="value">The value to write into the entity body of the request.</param> /// <param name="options">The options for the request.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <typeparam name="T">The type of object to serialize.</typeparam> public static Task<HttpResponseMessage> PostAsJsonAsync<T>(this HttpMessageInvoker client, string requestUri, T value, CancellationToken cancellationToken, RequestOptions options) { return client.PostAsync(requestUri, value, new JsonMediaTypeFormatter(), cancellationToken, options); } /// <summary>Sends a POST request as an asynchronous operation, with a specified value serialized as XML.</summary> /// <returns>A task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The URI the request is sent to.</param> /// <param name="value">The value to write into the entity body of the request.</param> /// <param name="options">The options for the request.</param> /// <typeparam name="T">The type of object to serialize.</typeparam> public static Task<HttpResponseMessage> PostAsXmlAsync<T>(this HttpMessageInvoker client, string requestUri, T value, RequestOptions options) { return client.PostAsXmlAsync(requestUri, value, CancellationToken.None, options); } /// <summary>Sends a POST request as an asynchronous operation, with a specified value serialized as XML. Includes a cancellation token to cancel the request.</summary> /// <returns>A task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The URI the request is sent to.</param> /// <param name="value">The value to write into the entity body of the request.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <param name="options">The options for the request.</param> /// <typeparam name="T">The type of object to serialize.</typeparam> public static Task<HttpResponseMessage> PostAsXmlAsync<T>(this HttpMessageInvoker client, string requestUri, T value, CancellationToken cancellationToken, RequestOptions options) { return client.PostAsync(requestUri, value, new XmlMediaTypeFormatter(), cancellationToken, options); } /// <summary>Sends a POST request as an asynchronous operation, with a specified value serialized using the given formatter.</summary> /// <returns>A task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The URI the request is sent to.</param> /// <param name="value">The value to write into the entity body of the request.</param> /// <param name="formatter">The formatter used to serialize the value.</param> /// <param name="options">The options for the request.</param> /// <typeparam name="T">The type of object to serialize.</typeparam> private static Task<HttpResponseMessage> PostAsync<T>(this HttpMessageInvoker client, string requestUri, T value, MediaTypeFormatter formatter, RequestOptions options) { return client.PostAsync(requestUri, value, formatter, CancellationToken.None, options); } /// <summary>Sends a POST request as an asynchronous operation, with a specified value serialized using the given formatter. Includes a cancellation token to cancel the request.</summary> /// <returns>A task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The URI the request is sent to.</param> /// <param name="value">The value to write into the entity body of the request.</param> /// <param name="formatter">The formatter used to serialize the value.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <param name="options">The options for the request.</param> /// <typeparam name="T">The type of object to serialize.</typeparam> private static Task<HttpResponseMessage> PostAsync<T>(this HttpMessageInvoker client, string requestUri, T value, MediaTypeFormatter formatter, CancellationToken cancellationToken, RequestOptions options) { MediaTypeHeaderValue mediaType = null; return client.PostAsync(requestUri, value, formatter, mediaType, cancellationToken, options); } /// <summary>Sends a POST request as an asynchronous operation, with a specified value serialized using the given formatter and media type string.</summary> /// <returns>A task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The URI the request is sent to.</param> /// <param name="value">The value to write into the entity body of the request.</param> /// <param name="formatter">The formatter used to serialize the value.</param> /// <param name="mediaType">The authoritative value of the Content-Type header. Can be null, in which case the default content type of the formatter will be used.</param> /// <param name="options">The options for the request.</param> /// <typeparam name="T">The type of object to serialize.</typeparam> private static Task<HttpResponseMessage> PostAsync<T>(this HttpMessageInvoker client, string requestUri, T value, MediaTypeFormatter formatter, string mediaType, RequestOptions options) { return client.PostAsync(requestUri, value, formatter, mediaType, CancellationToken.None, options); } /// <summary>Sends a POST request as an asynchronous operation, with a specified value serialized using the given formatter and media type string. Includes a cancellation token to cancel the request.</summary> /// <returns>A task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The URI the request is sent to.</param> /// <param name="value">The value to write into the entity body of the request.</param> /// <param name="formatter">The formatter used to serialize the value.</param> /// <param name="mediaType">The authoritative value of the Content-Type header. Can be null, in which case the default content type of the formatter will be used.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <param name="options">The options for the request.</param> /// <typeparam name="T">The type of object to serialize.</typeparam> private static Task<HttpResponseMessage> PostAsync<T>(this HttpMessageInvoker client, string requestUri, T value, MediaTypeFormatter formatter, string mediaType, CancellationToken cancellationToken, RequestOptions options) { return client.PostAsync(requestUri, value, formatter, ObjectContent.BuildHeaderValue(mediaType), cancellationToken, options); } /// <summary>Sends a POST request as an asynchronous operation, with a specified value serialized using the given formatter and media type.</summary> /// <returns>A task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The URI the request is sent to.</param> /// <param name="value">The value to write into the entity body of the request.</param> /// <param name="formatter">The formatter used to serialize the value.</param> /// <param name="mediaType">The authoritative value of the Content-Type header. Can be null, in which case the default content type of the formatter will be used.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <param name="options">The options for the request.</param> /// <typeparam name="T">The type of object to serialize.</typeparam> private static Task<HttpResponseMessage> PostAsync<T>(this HttpMessageInvoker client, string requestUri, T value, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, CancellationToken cancellationToken, RequestOptions options) { if (client == null) throw new ArgumentNullException("client"); ObjectContent<T> objectContent = new ObjectContent<T>(value, formatter, mediaType); return client.PostAsync(requestUri, objectContent, cancellationToken, options); } /// <summary>Sends a PUT request as an asynchronous operation, with a specified value serialized as JSON.</summary> /// <returns>A task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The URI the request is sent to.</param> /// <param name="value">The value to write into the entity body of the request.</param> /// <param name="options">The options for the request.</param> /// <typeparam name="T">The type of object to serialize.</typeparam> public static Task<HttpResponseMessage> PutAsJsonAsync<T>(this HttpMessageInvoker client, string requestUri, T value, RequestOptions options) { return client.PutAsJsonAsync(requestUri, value, CancellationToken.None, options); } /// <summary>Sends a PUT request as an asynchronous operation, with a specified value serialized as JSON. Includes a cancellation token to cancel the request.</summary> /// <returns>A task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The URI the request is sent to.</param> /// <param name="value">The value to write into the entity body of the request.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation. </param> /// <param name="options">The options for the request.</param> /// <typeparam name="T">The type of object to serialize.</typeparam> public static Task<HttpResponseMessage> PutAsJsonAsync<T>(this HttpMessageInvoker client, string requestUri, T value, CancellationToken cancellationToken, RequestOptions options) { return client.PutAsync(requestUri, value, new JsonMediaTypeFormatter(), cancellationToken, options); } /// <summary>Sends a PUT request as an asynchronous operation, with a specified value serialized as XML.</summary> /// <returns>A task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The URI the request is sent to.</param> /// <param name="value">The value to write into the entity body of the request.</param> /// <param name="options">The options for the request.</param> /// <typeparam name="T">The type of object to serialize.</typeparam> public static Task<HttpResponseMessage> PutAsXmlAsync<T>(this HttpMessageInvoker client, string requestUri, T value, RequestOptions options) { return client.PutAsXmlAsync(requestUri, value, CancellationToken.None, options); } /// <summary>Sends a PUT request as an asynchronous operation, with a specified value serialized as XML. Includes a cancellation token to cancel the request.</summary> /// <returns>A task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The URI the request is sent to.</param> /// <param name="value">The value to write into the entity body of the request.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <param name="options">The options for the request.</param> /// <typeparam name="T">The type of object to serialize.</typeparam> public static Task<HttpResponseMessage> PutAsXmlAsync<T>(this HttpMessageInvoker client, string requestUri, T value, CancellationToken cancellationToken, RequestOptions options) { return client.PutAsync(requestUri, value, new XmlMediaTypeFormatter(), cancellationToken, options); } /// <summary>Sends a PUT request as an asynchronous operation, with a specified value serialized using the given formatter.</summary> /// <returns>A task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The URI the request is sent to.</param> /// <param name="value">The value to write into the entity body of the request.</param> /// <param name="formatter">The formatter used to serialize the value.</param> /// <param name="options">The options for the request.</param> /// <typeparam name="T">The type of object to serialize.</typeparam> private static Task<HttpResponseMessage> PutAsync<T>(this HttpMessageInvoker client, string requestUri, T value, MediaTypeFormatter formatter, RequestOptions options) { return client.PutAsync(requestUri, value, formatter, CancellationToken.None, options); } /// <summary>Sends a PUT request as an asynchronous operation, with a specified value serialized using the given formatter and medai type string. Includes a cancellation token to cancel the request.</summary> /// <returns>A task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The URI the request is sent to.</param> /// <param name="value">The value to write into the entity body of the request.</param> /// <param name="formatter">The formatter used to serialize the value.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <param name="options">The options for the request.</param> /// <typeparam name="T">The type of object to serialize.</typeparam> private static Task<HttpResponseMessage> PutAsync<T>(this HttpMessageInvoker client, string requestUri, T value, MediaTypeFormatter formatter, CancellationToken cancellationToken, RequestOptions options) { MediaTypeHeaderValue mediaType = null; return client.PutAsync(requestUri, value, formatter, mediaType, cancellationToken, options); } /// <summary>Sends a PUT request as an asynchronous operation, with a specified value serialized using the given formatter and media type string.</summary> /// <returns>A task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The URI the request is sent to.</param> /// <param name="value">The value to write into the entity body of the request.</param> /// <param name="formatter">The formatter used to serialize the value.</param> /// <param name="mediaType">The authoritative value of the Content-Type header. Can be null, in which case the default content type of the formatter will be used.</param> /// <param name="options">The options for the request.</param> /// <typeparam name="T">The type of object to serialize.</typeparam> private static Task<HttpResponseMessage> PutAsync<T>(this HttpMessageInvoker client, string requestUri, T value, MediaTypeFormatter formatter, string mediaType, RequestOptions options) { return client.PutAsync(requestUri, value, formatter, mediaType, CancellationToken.None, options); } /// <summary>Sends a PUT request as an asynchronous operation, with a specified value serialized using the given formatter and media type string. Includes a cancellation token to cancel the request.</summary> /// <returns>A task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The URI the request is sent to.</param> /// <param name="value">The value to write into the entity body of the request.</param> /// <param name="formatter">The formatter used to serialize the value.</param> /// <param name="mediaType">The authoritative value of the Content-Type header. Can be null, in which case the default content type of the formatter will be used.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <param name="options">The options for the request.</param> /// <typeparam name="T">The type of object to serialize.</typeparam> private static Task<HttpResponseMessage> PutAsync<T>(this HttpMessageInvoker client, string requestUri, T value, MediaTypeFormatter formatter, string mediaType, CancellationToken cancellationToken, RequestOptions options) { return client.PutAsync(requestUri, value, formatter, ObjectContent.BuildHeaderValue(mediaType), cancellationToken, options); } /// <summary> Sends a PUT request as an asynchronous operation, with a specified value serialized using the given formatter and media type. Includes a cancellation token to cancel the request.</summary> /// <returns>A task object representing the asynchronous operation.</returns> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The URI the request is sent to.</param> /// <param name="value">The value to write into the entity body of the request.</param> /// <param name="formatter">The formatter used to serialize the value.</param> /// <param name="mediaType">The authoritative value of the Content-Type header. Can be null, in which case the default content type of the formatter will be used.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <param name="options">The options for the request.</param> /// <typeparam name="T">The type of object to serialize.</typeparam> private static Task<HttpResponseMessage> PutAsync<T>(this HttpMessageInvoker client, string requestUri, T value, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, CancellationToken cancellationToken, RequestOptions options) { if (client == null) throw new ArgumentNullException("client"); ObjectContent<T> objectContent = new ObjectContent<T>(value, formatter, mediaType); return client.PutAsync(requestUri, objectContent, cancellationToken, options); } #endregion #region Helper Methods static Uri GetUri(string uri) { if (string.IsNullOrEmpty(uri)) { return null; } return new Uri(uri, UriKind.RelativeOrAbsolute); } static HttpRequestMessage CreateRequest(HttpMethod method, Uri uri, HttpContent content, RequestOptions options) { var request = new HttpRequestMessage(method, uri) { Content = content }; AttachOptions(request, options); return request; } private static void AttachOptions(HttpRequestMessage request, RequestOptions options) { if (options != null && options.Headers != null) { //Copy headers over foreach (var header in options.Headers) { if (request.Headers.Contains(header.Key)) { request.Headers.Remove(header.Key); } request.Headers.Add(header.Key, header.Value); } } //Attach options to request MessageInvokerBase.SetRequestOptions(request, options); } #endregion } }
// // SliderBackend.cs // // Author: // Lluis Sanchez <[email protected]> // Vsevolod Kukol <[email protected]> // // Copyright (c) 2013 Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using AppKit; using CoreGraphics; using Xwt.Backends; namespace Xwt.Mac { public class SliderBackend: ViewBackend<NSSlider,ISliderEventSink>, ISliderBackend { Orientation orientation; public SliderBackend () { } public void Initialize (Orientation dir) { orientation = dir; // starting with macOS Sierra, for NSSlider, the orientation (.IsVertical readonly property) // is set in the constructor based on the frame size (if width > height or not). // (Cannot set frame size AFTER constructor.) CGRect rect = new CGRect(0, 0, 80, 30); if (dir == Orientation.Vertical) { rect = new CGRect(0, 0, 30, 80); } ViewObject = new MacSlider (rect); } MacSlider Slider { get { return (MacSlider)Widget; } } protected override void OnSizeToFit () { Widget.SizeToFit (); } public override void EnableEvent (object eventId) { base.EnableEvent (eventId); if (eventId is SliderEvent) Widget.Activated += HandleActivated;; } public override void DisableEvent (object eventId) { base.DisableEvent (eventId); if (eventId is SliderEvent) Widget.Activated -= HandleActivated; } void HandleActivated (object sender, EventArgs e) { ApplicationContext.InvokeUserCode (EventSink.ValueChanged); } #region ISliderBackend implementation public double Value { get { return Slider.DoubleValue; } set { Slider.DoubleValue = value; } } public double MinimumValue { get { return Slider.MinValue; } set { Slider.MinValue = value; } } public double MaximumValue { get { return Slider.MaxValue; } set { Slider.MaxValue = value; } } public double StepIncrement { get { return Slider.StepIncrement; } set { Slider.StepIncrement = value; } } public bool SnapToTicks { get { return Slider.AllowsTickMarkValuesOnly; } set { Slider.AllowsTickMarkValuesOnly = value; } } public double SliderPosition { get { double prct = 0; if (MinimumValue >= 0) { prct = (Value / (MaximumValue - MinimumValue)); } else if (MaximumValue <= 0) { prct = (Math.Abs (Value) / Math.Abs (MinimumValue - MaximumValue)); } else if (MinimumValue < 0) { if (Value >= 0) prct = 0.5 + ((Value / 2) / MaximumValue); else prct = 0.5 - Math.Abs ((Value / 2) / MinimumValue); } double tickStart, tickEnd; if (Slider.TickMarksCount > 1) { var rectTickStart = Slider.RectOfTick (0); var rectTickEnd = Slider.RectOfTick (Widget.TickMarksCount - 1); if (orientation == Orientation.Horizontal) { tickStart = Math.Min (rectTickStart.X, rectTickEnd.X); tickEnd = Math.Max (rectTickStart.X, rectTickEnd.X); } else { tickStart = Math.Min (rectTickStart.Y, rectTickEnd.Y); tickEnd = Math.Max (rectTickStart.Y, rectTickEnd.Y); } } else { double orientationSize = 0; if (orientation == Orientation.Horizontal) orientationSize = Frontend.Size.Width; else orientationSize = Frontend.Size.Height; tickStart = (Widget.KnobThickness / 2) + 1; tickEnd = orientationSize - tickStart; } if (orientation == Orientation.Vertical) prct = 1 - prct; return ((tickEnd - tickStart) * prct) + (tickStart); } } #endregion } public class MacSlider: NSSlider, IViewObject { public MacSlider(CGRect rect) : base(rect) { Cell = new MacSliderCell (); } public NSView View { get { return this; } } public ViewBackend Backend { get; set; } public override void ResetCursorRects () { base.ResetCursorRects (); if (Backend.Cursor != null) AddCursorRect (Bounds, Backend.Cursor); } public double StepIncrement { get { return ((MacSliderCell)Cell).StepIncrement; } set { ((MacSliderCell)Cell).StepIncrement = value; } } public override bool AllowsVibrancy { get { // we don't support vibrancy if (EffectiveAppearance.AllowsVibrancy) return false; return base.AllowsVibrancy; } } } public class MacSliderCell : NSSliderCell { readonly List<double> Ticks = new List<double>(); public override double MaxValue { get { return base.MaxValue; } set { base.MaxValue = value; UpdateTicks (); } } public override double MinValue { get { return base.MinValue; } set { base.MinValue = value; UpdateTicks (); } } double stepIncrement; public double StepIncrement { get { return stepIncrement; } set { stepIncrement = value; UpdateTicks (); } } public override bool AllowsTickMarkValuesOnly { get { return base.AllowsTickMarkValuesOnly; } set { base.AllowsTickMarkValuesOnly = value; UpdateTicks (); } } void UpdateTicks() { Ticks.Clear (); if (AllowsTickMarkValuesOnly) { if (MinValue >= 0) { var ticksCount = (int)((MaxValue - MinValue) / StepIncrement) + 1; for (int i = 0; i < ticksCount; i++) { Ticks.Add (MinValue + (i * StepIncrement)); } } else if (MaxValue <= 0) { var ticksCount = (int)((MaxValue - MinValue) / StepIncrement) + 1; for (int i = 0; i < ticksCount; i++) { Ticks.Add (-(i * StepIncrement)); } } else if (MinValue < 0) { var ticksCountN = (int)(Math.Abs(MinValue) / StepIncrement); for (int i = ticksCountN; i >= 1; i--) { Ticks.Add (-(i * StepIncrement)); } var ticksCount = (int)(MaxValue / StepIncrement) + 1; for (int i = 0; i < ticksCount; i++) { Ticks.Add (i * StepIncrement); } } } TickMarks = Ticks.Count; } public override double TickMarkValue (nint index) { return Ticks [(int)index]; } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Globalization; using System.Runtime.Serialization.Formatters; using uWebshop.Newtonsoft.Json.Utilities; using System.Runtime.Serialization; namespace uWebshop.Newtonsoft.Json.Serialization { internal class JsonSerializerProxy : JsonSerializer { private readonly JsonSerializerInternalReader _serializerReader; private readonly JsonSerializerInternalWriter _serializerWriter; private readonly JsonSerializer _serializer; public override event EventHandler<ErrorEventArgs> Error { add { _serializer.Error += value; } remove { _serializer.Error -= value; } } public override IReferenceResolver ReferenceResolver { get { return _serializer.ReferenceResolver; } set { _serializer.ReferenceResolver = value; } } public override ITraceWriter TraceWriter { get { return _serializer.TraceWriter; } set { _serializer.TraceWriter = value; } } public override JsonConverterCollection Converters { get { return _serializer.Converters; } } public override DefaultValueHandling DefaultValueHandling { get { return _serializer.DefaultValueHandling; } set { _serializer.DefaultValueHandling = value; } } public override IContractResolver ContractResolver { get { return _serializer.ContractResolver; } set { _serializer.ContractResolver = value; } } public override MissingMemberHandling MissingMemberHandling { get { return _serializer.MissingMemberHandling; } set { _serializer.MissingMemberHandling = value; } } public override NullValueHandling NullValueHandling { get { return _serializer.NullValueHandling; } set { _serializer.NullValueHandling = value; } } public override ObjectCreationHandling ObjectCreationHandling { get { return _serializer.ObjectCreationHandling; } set { _serializer.ObjectCreationHandling = value; } } public override ReferenceLoopHandling ReferenceLoopHandling { get { return _serializer.ReferenceLoopHandling; } set { _serializer.ReferenceLoopHandling = value; } } public override PreserveReferencesHandling PreserveReferencesHandling { get { return _serializer.PreserveReferencesHandling; } set { _serializer.PreserveReferencesHandling = value; } } public override TypeNameHandling TypeNameHandling { get { return _serializer.TypeNameHandling; } set { _serializer.TypeNameHandling = value; } } public override FormatterAssemblyStyle TypeNameAssemblyFormat { get { return _serializer.TypeNameAssemblyFormat; } set { _serializer.TypeNameAssemblyFormat = value; } } public override ConstructorHandling ConstructorHandling { get { return _serializer.ConstructorHandling; } set { _serializer.ConstructorHandling = value; } } public override SerializationBinder Binder { get { return _serializer.Binder; } set { _serializer.Binder = value; } } public override StreamingContext Context { get { return _serializer.Context; } set { _serializer.Context = value; } } public override Formatting Formatting { get { return _serializer.Formatting; } set { _serializer.Formatting = value; } } public override DateFormatHandling DateFormatHandling { get { return _serializer.DateFormatHandling; } set { _serializer.DateFormatHandling = value; } } public override DateTimeZoneHandling DateTimeZoneHandling { get { return _serializer.DateTimeZoneHandling; } set { _serializer.DateTimeZoneHandling = value; } } public override DateParseHandling DateParseHandling { get { return _serializer.DateParseHandling; } set { _serializer.DateParseHandling = value; } } public override FloatFormatHandling FloatFormatHandling { get { return _serializer.FloatFormatHandling; } set { _serializer.FloatFormatHandling = value; } } public override FloatParseHandling FloatParseHandling { get { return _serializer.FloatParseHandling; } set { _serializer.FloatParseHandling = value; } } public override StringEscapeHandling StringEscapeHandling { get { return _serializer.StringEscapeHandling; } set { _serializer.StringEscapeHandling = value; } } public override string DateFormatString { get { return _serializer.DateFormatString; } set { _serializer.DateFormatString = value; } } public override CultureInfo Culture { get { return _serializer.Culture; } set { _serializer.Culture = value; } } public override int? MaxDepth { get { return _serializer.MaxDepth; } set { _serializer.MaxDepth = value; } } public override bool CheckAdditionalContent { get { return _serializer.CheckAdditionalContent; } set { _serializer.CheckAdditionalContent = value; } } internal JsonSerializerInternalBase GetInternalSerializer() { if (_serializerReader != null) return _serializerReader; else return _serializerWriter; } public JsonSerializerProxy(JsonSerializerInternalReader serializerReader) { ValidationUtils.ArgumentNotNull(serializerReader, "serializerReader"); _serializerReader = serializerReader; _serializer = serializerReader.Serializer; } public JsonSerializerProxy(JsonSerializerInternalWriter serializerWriter) { ValidationUtils.ArgumentNotNull(serializerWriter, "serializerWriter"); _serializerWriter = serializerWriter; _serializer = serializerWriter.Serializer; } internal override object DeserializeInternal(JsonReader reader, Type objectType) { if (_serializerReader != null) return _serializerReader.Deserialize(reader, objectType, false); else return _serializer.Deserialize(reader, objectType); } internal override void PopulateInternal(JsonReader reader, object target) { if (_serializerReader != null) _serializerReader.Populate(reader, target); else _serializer.Populate(reader, target); } internal override void SerializeInternal(JsonWriter jsonWriter, object value, Type rootType) { if (_serializerWriter != null) _serializerWriter.Serialize(jsonWriter, value, rootType); else _serializer.Serialize(jsonWriter, value); } } }
namespace AnimalRegister.EntityFramework.Migrations { using System.Collections.Generic; using System.Data.Entity.Migrations; public partial class Update : DbMigration { public override void Up() { CreateTable( "dbo.AuditLogs", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(), ServiceName = c.String(maxLength: 256), MethodName = c.String(maxLength: 256), Parameters = c.String(maxLength: 1024), ExecutionTime = c.DateTime(nullable: false), ExecutionDuration = c.Int(nullable: false), ClientIpAddress = c.String(maxLength: 64), ClientName = c.String(maxLength: 128), BrowserInfo = c.String(maxLength: 256), Exception = c.String(maxLength: 2000), ImpersonatorUserId = c.Long(), ImpersonatorTenantId = c.Int(), CustomData = c.String(maxLength: 2000), }, annotations: new Dictionary<string, object> { { "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.BackgroundJobs", c => new { Id = c.Long(nullable: false, identity: true), JobType = c.String(nullable: false, maxLength: 512), JobArgs = c.String(nullable: false), TryCount = c.Short(nullable: false), NextTryTime = c.DateTime(nullable: false), LastTryTime = c.DateTime(), IsAbandoned = c.Boolean(nullable: false), Priority = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id) .Index(t => new { t.IsAbandoned, t.NextTryTime }); CreateTable( "dbo.Features", c => new { Id = c.Long(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 128), Value = c.String(nullable: false, maxLength: 2000), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), EditionId = c.Int(), TenantId = c.Int(), Discriminator = c.String(nullable: false, maxLength: 128), }, annotations: new Dictionary<string, object> { { "DynamicFilter_TenantFeatureSetting_MustHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Editions", t => t.EditionId, cascadeDelete: true) .Index(t => t.EditionId); CreateTable( "dbo.Editions", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 32), DisplayName = c.String(nullable: false, maxLength: 64), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Edition_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Entries", c => new { Id = c.Long(nullable: false, identity: true), DateIn = c.DateTime(), Specy = c.String(), Location = c.String(), Via = c.String(), Diagnose = c.String(), DateOut = c.DateTime(), Result = c.String(), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Entry_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Languages", c => new { Id = c.Int(nullable: false, identity: true), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 10), DisplayName = c.String(nullable: false, maxLength: 64), Icon = c.String(maxLength: 128), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_ApplicationLanguage_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_ApplicationLanguage_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.LanguageTexts", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), LanguageName = c.String(nullable: false, maxLength: 10), Source = c.String(nullable: false, maxLength: 128), Key = c.String(nullable: false, maxLength: 256), Value = c.String(nullable: false), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_ApplicationLanguageText_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Notifications", c => new { Id = c.Guid(nullable: false), NotificationName = c.String(nullable: false, maxLength: 96), Data = c.String(), DataTypeName = c.String(maxLength: 512), EntityTypeName = c.String(maxLength: 250), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 96), Severity = c.Byte(nullable: false), UserIds = c.String(), ExcludedUserIds = c.String(), TenantIds = c.String(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.NotificationSubscriptions", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), UserId = c.Long(nullable: false), NotificationName = c.String(maxLength: 96), EntityTypeName = c.String(maxLength: 250), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 96), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_NotificationSubscriptionInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .Index(t => new { t.NotificationName, t.EntityTypeName, t.EntityId, t.UserId }); CreateTable( "dbo.OrganizationUnits", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), ParentId = c.Long(), Code = c.String(nullable: false, maxLength: 95), DisplayName = c.String(nullable: false, maxLength: 128), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_OrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_OrganizationUnit_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.OrganizationUnits", t => t.ParentId) .Index(t => t.ParentId); CreateTable( "dbo.Permissions", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 128), IsGranted = c.Boolean(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), RoleId = c.Int(), UserId = c.Long(), Discriminator = c.String(nullable: false, maxLength: 128), }, annotations: new Dictionary<string, object> { { "DynamicFilter_PermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_RolePermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_UserPermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Users", t => t.UserId, cascadeDelete: true) .ForeignKey("dbo.Roles", t => t.RoleId, cascadeDelete: true) .Index(t => t.RoleId) .Index(t => t.UserId); CreateTable( "dbo.Roles", c => new { Id = c.Int(nullable: false, identity: true), DisplayName = c.String(nullable: false, maxLength: 64), IsStatic = c.Boolean(nullable: false), IsDefault = c.Boolean(nullable: false), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 32), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Users", t => t.CreatorUserId) .ForeignKey("dbo.Users", t => t.DeleterUserId) .ForeignKey("dbo.Users", t => t.LastModifierUserId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); CreateTable( "dbo.Users", c => new { Id = c.Long(nullable: false, identity: true), AuthenticationSource = c.String(maxLength: 64), Name = c.String(nullable: false, maxLength: 32), Surname = c.String(nullable: false, maxLength: 32), Password = c.String(nullable: false, maxLength: 128), IsEmailConfirmed = c.Boolean(nullable: false), EmailConfirmationCode = c.String(maxLength: 328), PasswordResetCode = c.String(maxLength: 328), LockoutEndDateUtc = c.DateTime(), AccessFailedCount = c.Int(nullable: false), IsLockoutEnabled = c.Boolean(nullable: false), PhoneNumber = c.String(), IsPhoneNumberConfirmed = c.Boolean(nullable: false), SecurityStamp = c.String(), IsTwoFactorEnabled = c.Boolean(nullable: false), IsActive = c.Boolean(nullable: false), UserName = c.String(nullable: false, maxLength: 32), TenantId = c.Int(), EmailAddress = c.String(nullable: false, maxLength: 256), LastLoginTime = c.DateTime(), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Users", t => t.CreatorUserId) .ForeignKey("dbo.Users", t => t.DeleterUserId) .ForeignKey("dbo.Users", t => t.LastModifierUserId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); CreateTable( "dbo.UserClaims", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), ClaimType = c.String(), ClaimValue = c.String(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserClaim_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Users", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.UserLogins", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 256), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserLogin_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Users", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.UserRoles", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), RoleId = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserRole_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Users", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.Settings", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(), Name = c.String(nullable: false, maxLength: 256), Value = c.String(maxLength: 2000), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Setting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Users", t => t.UserId) .Index(t => t.UserId); CreateTable( "dbo.TenantNotifications", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), NotificationName = c.String(nullable: false, maxLength: 96), Data = c.String(), DataTypeName = c.String(maxLength: 512), EntityTypeName = c.String(maxLength: 250), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 96), Severity = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_TenantNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Tenants", c => new { Id = c.Int(nullable: false, identity: true), EditionId = c.Int(), Name = c.String(nullable: false, maxLength: 128), IsActive = c.Boolean(nullable: false), TenancyName = c.String(nullable: false, maxLength: 64), ConnectionString = c.String(maxLength: 1024), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Users", t => t.CreatorUserId) .ForeignKey("dbo.Users", t => t.DeleterUserId) .ForeignKey("dbo.Editions", t => t.EditionId) .ForeignKey("dbo.Users", t => t.LastModifierUserId) .Index(t => t.EditionId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); CreateTable( "dbo.UserAccounts", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), UserLinkId = c.Long(), UserName = c.String(), EmailAddress = c.String(), LastLoginTime = c.DateTime(), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserAccount_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.UserLoginAttempts", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), TenancyName = c.String(maxLength: 64), UserId = c.Long(), UserNameOrEmailAddress = c.String(maxLength: 255), ClientIpAddress = c.String(maxLength: 64), ClientName = c.String(maxLength: 128), BrowserInfo = c.String(maxLength: 256), Result = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserLoginAttempt_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .Index(t => new { t.UserId, t.TenantId }) .Index(t => new { t.TenancyName, t.UserNameOrEmailAddress, t.Result }); CreateTable( "dbo.UserNotifications", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), UserId = c.Long(nullable: false), TenantNotificationId = c.Guid(nullable: false), State = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .Index(t => new { t.UserId, t.State, t.CreationTime }); CreateTable( "dbo.UserOrganizationUnits", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), OrganizationUnitId = c.Long(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserOrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); } public override void Down() { DropForeignKey("dbo.Tenants", "LastModifierUserId", "dbo.Users"); DropForeignKey("dbo.Tenants", "EditionId", "dbo.Editions"); DropForeignKey("dbo.Tenants", "DeleterUserId", "dbo.Users"); DropForeignKey("dbo.Tenants", "CreatorUserId", "dbo.Users"); DropForeignKey("dbo.Permissions", "RoleId", "dbo.Roles"); DropForeignKey("dbo.Roles", "LastModifierUserId", "dbo.Users"); DropForeignKey("dbo.Roles", "DeleterUserId", "dbo.Users"); DropForeignKey("dbo.Roles", "CreatorUserId", "dbo.Users"); DropForeignKey("dbo.Settings", "UserId", "dbo.Users"); DropForeignKey("dbo.UserRoles", "UserId", "dbo.Users"); DropForeignKey("dbo.Permissions", "UserId", "dbo.Users"); DropForeignKey("dbo.UserLogins", "UserId", "dbo.Users"); DropForeignKey("dbo.Users", "LastModifierUserId", "dbo.Users"); DropForeignKey("dbo.Users", "DeleterUserId", "dbo.Users"); DropForeignKey("dbo.Users", "CreatorUserId", "dbo.Users"); DropForeignKey("dbo.UserClaims", "UserId", "dbo.Users"); DropForeignKey("dbo.OrganizationUnits", "ParentId", "dbo.OrganizationUnits"); DropForeignKey("dbo.Features", "EditionId", "dbo.Editions"); DropIndex("dbo.UserNotifications", new[] { "UserId", "State", "CreationTime" }); DropIndex("dbo.UserLoginAttempts", new[] { "TenancyName", "UserNameOrEmailAddress", "Result" }); DropIndex("dbo.UserLoginAttempts", new[] { "UserId", "TenantId" }); DropIndex("dbo.Tenants", new[] { "CreatorUserId" }); DropIndex("dbo.Tenants", new[] { "LastModifierUserId" }); DropIndex("dbo.Tenants", new[] { "DeleterUserId" }); DropIndex("dbo.Tenants", new[] { "EditionId" }); DropIndex("dbo.Settings", new[] { "UserId" }); DropIndex("dbo.UserRoles", new[] { "UserId" }); DropIndex("dbo.UserLogins", new[] { "UserId" }); DropIndex("dbo.UserClaims", new[] { "UserId" }); DropIndex("dbo.Users", new[] { "CreatorUserId" }); DropIndex("dbo.Users", new[] { "LastModifierUserId" }); DropIndex("dbo.Users", new[] { "DeleterUserId" }); DropIndex("dbo.Roles", new[] { "CreatorUserId" }); DropIndex("dbo.Roles", new[] { "LastModifierUserId" }); DropIndex("dbo.Roles", new[] { "DeleterUserId" }); DropIndex("dbo.Permissions", new[] { "UserId" }); DropIndex("dbo.Permissions", new[] { "RoleId" }); DropIndex("dbo.OrganizationUnits", new[] { "ParentId" }); DropIndex("dbo.NotificationSubscriptions", new[] { "NotificationName", "EntityTypeName", "EntityId", "UserId" }); DropIndex("dbo.Features", new[] { "EditionId" }); DropIndex("dbo.BackgroundJobs", new[] { "IsAbandoned", "NextTryTime" }); DropTable("dbo.UserOrganizationUnits", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserOrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.UserNotifications", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.UserLoginAttempts", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserLoginAttempt_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.UserAccounts", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserAccount_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.Tenants", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.TenantNotifications", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_TenantNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.Settings", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Setting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.UserRoles", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserRole_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.UserLogins", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserLogin_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.UserClaims", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserClaim_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.Users", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.Roles", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.Permissions", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_PermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_RolePermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_UserPermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.OrganizationUnits", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_OrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_OrganizationUnit_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.NotificationSubscriptions", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_NotificationSubscriptionInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.Notifications"); DropTable("dbo.LanguageTexts", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_ApplicationLanguageText_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.Languages", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_ApplicationLanguage_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_ApplicationLanguage_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.Entries", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Entry_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.Editions", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Edition_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.Features", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_TenantFeatureSetting_MustHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.BackgroundJobs"); DropTable("dbo.AuditLogs", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); } } }
using System; using System.Collections.Generic; using GitTools.Testing; using GitVersion; using GitVersion.Extensions; using GitVersion.Model.Configuration; using GitVersion.VersionCalculation; using GitVersionCore.Tests.Helpers; using GitVersionCore.Tests.Mocks; using LibGit2Sharp; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using NUnit.Framework; using Shouldly; namespace GitVersionCore.Tests.VersionCalculation { [TestFixture] public class BaseVersionCalculatorTests : TestBase { [Test] public void ChoosesHighestVersionReturnedFromStrategies() { var dateTimeOffset = DateTimeOffset.Now; var versionCalculator = GetBaseVersionCalculator(contextBuilder => { contextBuilder.OverrideServices(services => { services.RemoveAll<IVersionStrategy>(); services.AddSingleton<IVersionStrategy>(new V1Strategy(DateTimeOffset.Now)); services.AddSingleton<IVersionStrategy>(new V2Strategy(dateTimeOffset)); }); }); var baseVersion = versionCalculator.GetBaseVersion(); baseVersion.SemanticVersion.ToString().ShouldBe("2.0.0"); baseVersion.ShouldIncrement.ShouldBe(true); baseVersion.BaseVersionSource.When().ShouldBe(dateTimeOffset); } [Test] public void UsesWhenFromNextBestMatchIfHighestDoesntHaveWhen() { var when = DateTimeOffset.Now; var versionCalculator = GetBaseVersionCalculator(contextBuilder => { contextBuilder.OverrideServices(services => { services.RemoveAll<IVersionStrategy>(); services.AddSingleton<IVersionStrategy>(new V1Strategy(when)); services.AddSingleton<IVersionStrategy>(new V2Strategy(null)); }); }); var baseVersion = versionCalculator.GetBaseVersion(); baseVersion.SemanticVersion.ToString().ShouldBe("2.0.0"); baseVersion.ShouldIncrement.ShouldBe(true); baseVersion.BaseVersionSource.When().ShouldBe(when); } [Test] public void UsesWhenFromNextBestMatchIfHighestDoesntHaveWhenReversedOrder() { var when = DateTimeOffset.Now; var versionCalculator = GetBaseVersionCalculator(contextBuilder => { contextBuilder.OverrideServices(services => { services.RemoveAll<IVersionStrategy>(); services.AddSingleton<IVersionStrategy>(new V1Strategy(null)); services.AddSingleton<IVersionStrategy>(new V2Strategy(when)); }); }); var baseVersion = versionCalculator.GetBaseVersion(); baseVersion.SemanticVersion.ToString().ShouldBe("2.0.0"); baseVersion.ShouldIncrement.ShouldBe(true); baseVersion.BaseVersionSource.When().ShouldBe(when); } [Test] public void ShouldNotFilterVersion() { var fakeIgnoreConfig = new TestIgnoreConfig(new ExcludeSourcesContainingExclude()); var version = new BaseVersion("dummy", false, new SemanticVersion(2), new MockCommit(), null); var versionCalculator = GetBaseVersionCalculator(contextBuilder => { contextBuilder .WithConfig(new Config { Ignore = fakeIgnoreConfig }) .OverrideServices(services => { services.RemoveAll<IVersionStrategy>(); services.AddSingleton<IVersionStrategy>(new TestVersionStrategy(version)); }); }); var baseVersion = versionCalculator.GetBaseVersion(); baseVersion.Source.ShouldBe(version.Source); baseVersion.ShouldIncrement.ShouldBe(version.ShouldIncrement); baseVersion.SemanticVersion.ShouldBe(version.SemanticVersion); } [Test] public void ShouldFilterVersion() { var fakeIgnoreConfig = new TestIgnoreConfig(new ExcludeSourcesContainingExclude()); var higherVersion = new BaseVersion("exclude", false, new SemanticVersion(2), new MockCommit(), null); var lowerVersion = new BaseVersion("dummy", false, new SemanticVersion(1), new MockCommit(), null); var versionCalculator = GetBaseVersionCalculator(contextBuilder => { contextBuilder .WithConfig(new Config { Ignore = fakeIgnoreConfig }) .OverrideServices(services => { services.RemoveAll<IVersionStrategy>(); services.AddSingleton<IVersionStrategy>(new TestVersionStrategy(higherVersion, lowerVersion)); }); }); var baseVersion = versionCalculator.GetBaseVersion(); baseVersion.Source.ShouldNotBe(higherVersion.Source); baseVersion.SemanticVersion.ShouldNotBe(higherVersion.SemanticVersion); baseVersion.Source.ShouldBe(lowerVersion.Source); baseVersion.SemanticVersion.ShouldBe(lowerVersion.SemanticVersion); } private static IBaseVersionCalculator GetBaseVersionCalculator(Action<GitVersionContextBuilder> contextBuilderAction) { var contextBuilder = new GitVersionContextBuilder(); contextBuilderAction?.Invoke(contextBuilder); contextBuilder.Build(); return contextBuilder.ServicesProvider.GetService<IBaseVersionCalculator>(); } private class TestIgnoreConfig : IgnoreConfig { private readonly IVersionFilter filter; public TestIgnoreConfig(IVersionFilter filter) { this.filter = filter; } public override IEnumerable<IVersionFilter> ToFilters() { yield return filter; } } private class ExcludeSourcesContainingExclude : IVersionFilter { public bool Exclude(BaseVersion version, out string reason) { reason = null; if (version.Source.Contains("exclude")) { reason = "was excluded"; return true; } return false; } } private sealed class V1Strategy : IVersionStrategy { private readonly Commit when; public V1Strategy(DateTimeOffset? when) { this.when = when == null ? null : new MockCommit { CommitterEx = Generate.Signature(when.Value) }; } public IEnumerable<BaseVersion> GetVersions() { yield return new BaseVersion("Source 1", false, new SemanticVersion(1), when, null); } } private sealed class V2Strategy : IVersionStrategy { private readonly Commit when; public V2Strategy(DateTimeOffset? when) { this.when = when == null ? null : new MockCommit { CommitterEx = Generate.Signature(when.Value) }; } public IEnumerable<BaseVersion> GetVersions() { yield return new BaseVersion("Source 2", true, new SemanticVersion(2), when, null); } } private sealed class TestVersionStrategy : IVersionStrategy { private readonly IEnumerable<BaseVersion> versions; public TestVersionStrategy(params BaseVersion[] versions) { this.versions = versions; } public IEnumerable<BaseVersion> GetVersions() { return versions; } } } }
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Runtime.Caching; using System.Threading; using System.Web; using Umbraco.Core.Models.EntityBase; namespace Umbraco.Core.Persistence.Caching { /// <summary> /// The Runtime Cache provider looks up objects in the Runtime cache for fast retrival /// </summary> /// <remarks> /// /// If a web session is detected then the HttpRuntime.Cache will be used for the runtime cache, otherwise a custom /// MemoryCache instance will be used. It is important to use the HttpRuntime.Cache when a web session is detected so /// that the memory management of cache in IIS can be handled appopriately. /// /// When a web sessions is detected we will pre-fix all HttpRuntime.Cache entries so that when we clear it we are only /// clearing items that have been inserted by this provider. /// /// NOTE: These changes are all temporary until we finalize the ApplicationCache implementation which will support static cache, runtime cache /// and request based cache which will all live in one central location so it is easily managed. /// /// Also note that we don't always keep checking if HttpContext.Current == null and instead check for _memoryCache != null. This is because /// when there are async requests being made even in the context of a web request, the HttpContext.Current will be null but the HttpRuntime.Cache will /// always be available. /// /// TODO: Each item that get's added to this cache will be a clone of the original with it's dirty properties reset, and every item that is resolved from the cache /// is a clone of the item that is in there, otherwise we end up with thread safety issues since multiple thread would be working on the exact same entity at the same time. /// /// </remarks> internal sealed class RuntimeCacheProvider : IRepositoryCacheProvider { #region Singleton private static readonly Lazy<RuntimeCacheProvider> lazy = new Lazy<RuntimeCacheProvider>(() => new RuntimeCacheProvider()); public static RuntimeCacheProvider Current { get { return lazy.Value; } } private RuntimeCacheProvider() { if (HttpContext.Current == null) { _memoryCache = new MemoryCache("in-memory"); } } #endregion //TODO Save this in cache as well, so its not limited to a single server usage private readonly ConcurrentHashSet<string> _keyTracker = new ConcurrentHashSet<string>(); private ObjectCache _memoryCache; private static readonly ReaderWriterLockSlim ClearLock = new ReaderWriterLockSlim(); public IEntity GetById(Type type, Guid id) { var key = GetCompositeId(type, id); var item = _memoryCache != null ? _memoryCache.Get(key) : HttpRuntime.Cache.Get(key); var result = item as IEntity; if (result == null) { //ensure the key doesn't exist anymore in the tracker _keyTracker.Remove(key); return null; } //IMPORTANT: we must clone to resolve, see: http://issues.umbraco.org/issue/U4-4259 return (IEntity)result.DeepClone(); } public IEnumerable<IEntity> GetByIds(Type type, List<Guid> ids) { var collection = new List<IEntity>(); foreach (var guid in ids) { var key = GetCompositeId(type, guid); var item = _memoryCache != null ? _memoryCache.Get(key) : HttpRuntime.Cache.Get(key); var result = item as IEntity; if (result == null) { //ensure the key doesn't exist anymore in the tracker _keyTracker.Remove(key); } else { //IMPORTANT: we must clone to resolve, see: http://issues.umbraco.org/issue/U4-4259 collection.Add((IEntity)result.DeepClone()); } } return collection; } public IEnumerable<IEntity> GetAllByType(Type type) { var collection = new List<IEntity>(); foreach (var key in _keyTracker) { if (key.StartsWith(string.Format("{0}{1}-", CacheItemPrefix, type.Name))) { var item = _memoryCache != null ? _memoryCache.Get(key) : HttpRuntime.Cache.Get(key); var result = item as IEntity; if (result == null) { //ensure the key doesn't exist anymore in the tracker _keyTracker.Remove(key); } else { //IMPORTANT: we must clone to resolve, see: http://issues.umbraco.org/issue/U4-4259 collection.Add((IEntity)result.DeepClone()); } } } return collection; } public void Save(Type type, IEntity entity) { //IMPORTANT: we must clone to store, see: http://issues.umbraco.org/issue/U4-4259 entity = (IEntity)entity.DeepClone(); var key = GetCompositeId(type, entity.Id); _keyTracker.TryAdd(key); //NOTE: Before we were checking if it already exists but the MemoryCache.Set handles this implicitly and does // an add or update, same goes for HttpRuntime.Cache.Insert. if (_memoryCache != null) { _memoryCache.Set(key, entity, new CacheItemPolicy { SlidingExpiration = TimeSpan.FromMinutes(5) }); } else { HttpRuntime.Cache.Insert(key, entity, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(5)); } } public void Delete(Type type, IEntity entity) { var key = GetCompositeId(type, entity.Id); if (_memoryCache != null) { _memoryCache.Remove(key); } else { HttpRuntime.Cache.Remove(key); } _keyTracker.Remove(key); } public void Delete(Type type, int entityId) { var key = GetCompositeId(type, entityId); if (_memoryCache != null) { _memoryCache.Remove(key); } else { HttpRuntime.Cache.Remove(key); } _keyTracker.Remove(key); } /// <summary> /// Clear cache by type /// </summary> /// <param name="type"></param> public void Clear(Type type) { using (new WriteLock(ClearLock)) { var keys = new string[_keyTracker.Count]; _keyTracker.CopyTo(keys, 0); var keysToRemove = new List<string>(); foreach (var key in keys.Where(x => x.StartsWith(string.Format("{0}{1}-", CacheItemPrefix, type.Name)))) { _keyTracker.Remove(key); keysToRemove.Add(key); } foreach (var key in keysToRemove) { if (_memoryCache != null) { _memoryCache.Remove(key); } else { HttpRuntime.Cache.Remove(key); } } } } public void Clear() { using (new WriteLock(ClearLock)) { _keyTracker.Clear(); ClearDataCache(); } } //DO not call this unless it's for testing since it clears the data cached but not the keys internal void ClearDataCache() { if (_memoryCache != null) { _memoryCache.DisposeIfDisposable(); _memoryCache = new MemoryCache("in-memory"); } else { foreach (DictionaryEntry c in HttpRuntime.Cache) { if (c.Key is string && ((string)c.Key).InvariantStartsWith(CacheItemPrefix)) { if (HttpRuntime.Cache[(string)c.Key] == null) return; HttpRuntime.Cache.Remove((string)c.Key); } } } } /// <summary> /// We prefix all cache keys with this so that we know which ones this class has created when /// using the HttpRuntime cache so that when we clear it we don't clear other entries we didn't create. /// </summary> private const string CacheItemPrefix = "umbrtmche_"; private string GetCompositeId(Type type, Guid id) { return string.Format("{0}{1}-{2}", CacheItemPrefix, type.Name, id.ToString()); } private string GetCompositeId(Type type, int id) { return string.Format("{0}{1}-{2}", CacheItemPrefix, type.Name, id.ToGuid()); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Spa.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/field_mask.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 Google.Protobuf.WellKnownTypes { /// <summary>Holder for reflection information generated from google/protobuf/field_mask.proto</summary> public static partial class FieldMaskReflection { #region Descriptor /// <summary>File descriptor for google/protobuf/field_mask.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static FieldMaskReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiBnb29nbGUvcHJvdG9idWYvZmllbGRfbWFzay5wcm90bxIPZ29vZ2xlLnBy", "b3RvYnVmIhoKCUZpZWxkTWFzaxINCgVwYXRocxgBIAMoCUKJAQoTY29tLmdv", "b2dsZS5wcm90b2J1ZkIORmllbGRNYXNrUHJvdG9QAVo5Z29vZ2xlLmdvbGFu", "Zy5vcmcvZ2VucHJvdG8vcHJvdG9idWYvZmllbGRfbWFzaztmaWVsZF9tYXNr", "ogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90", "bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.FieldMask), global::Google.Protobuf.WellKnownTypes.FieldMask.Parser, new[]{ "Paths" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// `FieldMask` represents a set of symbolic field paths, for example: /// /// paths: "f.a" /// paths: "f.b.d" /// /// Here `f` represents a field in some root message, `a` and `b` /// fields in the message found in `f`, and `d` a field found in the /// message in `f.b`. /// /// Field masks are used to specify a subset of fields that should be /// returned by a get operation or modified by an update operation. /// Field masks also have a custom JSON encoding (see below). /// /// # Field Masks in Projections /// /// When used in the context of a projection, a response message or /// sub-message is filtered by the API to only contain those fields as /// specified in the mask. For example, if the mask in the previous /// example is applied to a response message as follows: /// /// f { /// a : 22 /// b { /// d : 1 /// x : 2 /// } /// y : 13 /// } /// z: 8 /// /// The result will not contain specific values for fields x,y and z /// (their value will be set to the default, and omitted in proto text /// output): /// /// f { /// a : 22 /// b { /// d : 1 /// } /// } /// /// A repeated field is not allowed except at the last position of a /// paths string. /// /// If a FieldMask object is not present in a get operation, the /// operation applies to all fields (as if a FieldMask of all fields /// had been specified). /// /// Note that a field mask does not necessarily apply to the /// top-level response message. In case of a REST get operation, the /// field mask applies directly to the response, but in case of a REST /// list operation, the mask instead applies to each individual message /// in the returned resource list. In case of a REST custom method, /// other definitions may be used. Where the mask applies will be /// clearly documented together with its declaration in the API. In /// any case, the effect on the returned resource/resources is required /// behavior for APIs. /// /// # Field Masks in Update Operations /// /// A field mask in update operations specifies which fields of the /// targeted resource are going to be updated. The API is required /// to only change the values of the fields as specified in the mask /// and leave the others untouched. If a resource is passed in to /// describe the updated values, the API ignores the values of all /// fields not covered by the mask. /// /// If a repeated field is specified for an update operation, the existing /// repeated values in the target resource will be overwritten by the new values. /// Note that a repeated field is only allowed in the last position of a `paths` /// string. /// /// If a sub-message is specified in the last position of the field mask for an /// update operation, then the existing sub-message in the target resource is /// overwritten. Given the target message: /// /// f { /// b { /// d : 1 /// x : 2 /// } /// c : 1 /// } /// /// And an update message: /// /// f { /// b { /// d : 10 /// } /// } /// /// then if the field mask is: /// /// paths: "f.b" /// /// then the result will be: /// /// f { /// b { /// d : 10 /// } /// c : 1 /// } /// /// However, if the update mask was: /// /// paths: "f.b.d" /// /// then the result would be: /// /// f { /// b { /// d : 10 /// x : 2 /// } /// c : 1 /// } /// /// In order to reset a field's value to the default, the field must /// be in the mask and set to the default value in the provided resource. /// Hence, in order to reset all fields of a resource, provide a default /// instance of the resource and set all fields in the mask, or do /// not provide a mask as described below. /// /// If a field mask is not present on update, the operation applies to /// all fields (as if a field mask of all fields has been specified). /// Note that in the presence of schema evolution, this may mean that /// fields the client does not know and has therefore not filled into /// the request will be reset to their default. If this is unwanted /// behavior, a specific service may require a client to always specify /// a field mask, producing an error if not. /// /// As with get operations, the location of the resource which /// describes the updated values in the request message depends on the /// operation kind. In any case, the effect of the field mask is /// required to be honored by the API. /// /// ## Considerations for HTTP REST /// /// The HTTP kind of an update operation which uses a field mask must /// be set to PATCH instead of PUT in order to satisfy HTTP semantics /// (PUT must only be used for full updates). /// /// # JSON Encoding of Field Masks /// /// In JSON, a field mask is encoded as a single string where paths are /// separated by a comma. Fields name in each path are converted /// to/from lower-camel naming conventions. /// /// As an example, consider the following message declarations: /// /// message Profile { /// User user = 1; /// Photo photo = 2; /// } /// message User { /// string display_name = 1; /// string address = 2; /// } /// /// In proto a field mask for `Profile` may look as such: /// /// mask { /// paths: "user.display_name" /// paths: "photo" /// } /// /// In JSON, the same mask is represented as below: /// /// { /// mask: "user.displayName,photo" /// } /// /// # Field Masks and Oneof Fields /// /// Field masks treat fields in oneofs just as regular fields. Consider the /// following message: /// /// message SampleMessage { /// oneof test_oneof { /// string name = 4; /// SubMessage sub_message = 9; /// } /// } /// /// The field mask can be: /// /// mask { /// paths: "name" /// } /// /// Or: /// /// mask { /// paths: "sub_message" /// } /// /// Note that oneof type names ("test_oneof" in this case) cannot be used in /// paths. /// /// ## Field Mask Verification /// /// The implementation of the all the API methods, which have any FieldMask type /// field in the request, should verify the included field paths, and return /// `INVALID_ARGUMENT` error if any path is duplicated or unmappable. /// </summary> public sealed partial class FieldMask : pb::IMessage<FieldMask> { private static readonly pb::MessageParser<FieldMask> _parser = new pb::MessageParser<FieldMask>(() => new FieldMask()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<FieldMask> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.FieldMaskReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FieldMask() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FieldMask(FieldMask other) : this() { paths_ = other.paths_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FieldMask Clone() { return new FieldMask(this); } /// <summary>Field number for the "paths" field.</summary> public const int PathsFieldNumber = 1; private static readonly pb::FieldCodec<string> _repeated_paths_codec = pb::FieldCodec.ForString(10); private readonly pbc::RepeatedField<string> paths_ = new pbc::RepeatedField<string>(); /// <summary> /// The set of field mask paths. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<string> Paths { get { return paths_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as FieldMask); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(FieldMask other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!paths_.Equals(other.paths_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= paths_.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) { paths_.WriteTo(output, _repeated_paths_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += paths_.CalculateSize(_repeated_paths_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(FieldMask other) { if (other == null) { return; } paths_.Add(other.paths_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { paths_.AddEntriesFrom(input, _repeated_paths_codec); break; } } } } } #endregion } #endregion Designer generated code
// <copyright file=FilteredSmoothing.cs // <copyright> // Copyright (c) 2016, University of Stuttgart // 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> // <license>MIT License</license> // <main contributors> // Markus Funk, Thomas Kosch, Sven Mayer // </main contributors> // <co-contributors> // Paul Brombosch, Mai El-Komy, Juana Heusler, // Matthias Hoppe, Robert Konrad, Alexander Martin // </co-contributors> // <patent information> // We are aware that this software implements patterns and ideas, // which might be protected by patents in your country. // Example patents in Germany are: // Patent reference number: DE 103 20 557.8 // Patent reference number: DE 10 2013 220 107.9 // Please make sure when using this software not to violate any existing patents in your country. // </patent information> // <date> 11/2/2016 12:25:56 PM</date> using System.Threading.Tasks; using System; namespace HciLab.Kinect.DepthSmoothing { internal class FilteredSmoothing { /// <summary> /// Will specify how many non-zero pixels within a 1 pixel band /// around the origin there should be before a filter is applied /// </summary> private int m_InnerBandThreshold; /// <summary> /// Will specify how many non-zero pixels within a 2 pixel band /// around the origin there should be before a filter is applied /// </summary> private int m_OuterBandThreshold; public static readonly int MaxInnerBandThreshold = 8; public static readonly int MaxOuterBandThreshold = 16; public FilteredSmoothing() { this.m_InnerBandThreshold = 2; this.m_OuterBandThreshold = 5; } public FilteredSmoothing(int InnerBandThreshold, int OuterbandThreshold) : this() { this.InnerBandThreshold = InnerBandThreshold; this.OuterBandThreshold = OuterBandThreshold; } public Int32[] CreateFilteredDepthArray(Int32[] pDepthArray, int pWidth, int pHeight) { ///////////////////////////////////////////////////////////////////////////////////// // I will try to comment this as well as I can in here, but you should probably refer // to my Code Project article for a more in depth description of the method. ///////////////////////////////////////////////////////////////////////////////////// Int32[] smoothDepthArray = new Int32[pDepthArray.Length]; // We will be using these numbers for constraints on indexes int widthBound = pWidth - 1; int heightBound = pHeight - 1; // We process each row in parallel Parallel.For(0, pHeight, depthArrayRowIndex => { // Process each pixel in the row for (int depthArrayColumnIndex = 0; depthArrayColumnIndex < pWidth; depthArrayColumnIndex++) { var depthIndex = depthArrayColumnIndex + (depthArrayRowIndex * pWidth); // We are only concerned with eliminating 'white' noise from the data. // We consider any pixel with a depth of 0 as a possible candidate for filtering. if (pDepthArray[depthIndex] != 0) { // From the depth index, we can determine the X and Y coordinates that the index // will appear in the image. We use this to help us define our filter matrix. int x = depthIndex % pWidth; int y = (depthIndex - x) / pWidth; // The filter collection is used to count the frequency of each // depth value in the filter array. This is used later to determine // the statistical mode for possible assignment to the candidate. Int32[,] filterCollection = new Int32[24, 2]; // The inner and outer band counts are used later to compare against the threshold // values set in the UI to identify a positive filter result. int innerBandCount = 0; int outerBandCount = 0; // The following loops will loop through a 5 X 5 matrix of pixels surrounding the // candidate pixel. This defines 2 distinct 'bands' around the candidate pixel. // If any of the pixels in this matrix are non-0, we will accumulate them and count // how many non-0 pixels are in each band. If the number of non-0 pixels breaks the // threshold in either band, then the average of all non-0 pixels in the matrix is applied // to the candidate pixel. for (int yi = -2; yi < 3; yi++) { for (int xi = -2; xi < 3; xi++) { // yi and xi are modifiers that will be subtracted from and added to the // candidate pixel's x and y coordinates that we calculated earlier. From the // resulting coordinates, we can calculate the index to be addressed for processing. // We do not want to consider the candidate pixel (xi = 0, yi = 0) in our process at this point. // We already know that it's 0 if (xi != 0 || yi != 0) { // We then create our modified coordinates for each pass var xSearch = x + xi; var ySearch = y + yi; // While the modified coordinates may in fact calculate out to an actual index, it // might not be the one we want. Be sure to check to make sure that the modified coordinates // match up with our image bounds. if (xSearch >= 0 && xSearch <= widthBound && ySearch >= 0 && ySearch <= heightBound) { var index = xSearch + (ySearch * pWidth); // We only want to look for non-0 values if (pDepthArray[depthIndex] != 0) { // We want to find count the frequency of each depth for (int i = 0; i < 24; i++) { if (filterCollection[i, 0] == pDepthArray[index]) { // When the depth is already in the filter collection // we will just increment the frequency. filterCollection[i, 1]++; break; } else if (filterCollection[i, 0] == 0) { // When we encounter a 0 depth in the filter collection // this means we have reached the end of values already counted. // We will then add the new depth and start it's frequency at 1. filterCollection[i, 0] = pDepthArray[index]; filterCollection[i, 1]++; break; } } // We will then determine which band the non-0 pixel // was found in, and increment the band counters. if (yi != 2 && yi != -2 && xi != 2 && xi != -2) innerBandCount++; else outerBandCount++; } } } } } // Once we have determined our inner and outer band non-zero counts, and accumulated all of those values, // we can compare it against the threshold to determine if our candidate pixel will be changed to the // statistical mode of the non-zero surrounding pixels. if (innerBandCount >= m_InnerBandThreshold || outerBandCount >= m_OuterBandThreshold) { Int32 frequencyDepth = 0; Int32 depth = 0; // This loop will determine the statistical mode // of the surrounding pixels for assignment to // the candidate. for (int i = 0; i < 24; i++) { // This means we have reached the end of our // frequency distribution and can break out of the // loop to save time. if (filterCollection[i, 0] == 0) break; if (filterCollection[i, 1] > frequencyDepth) { depth = filterCollection[i, 0]; frequencyDepth = filterCollection[i, 1]; } } smoothDepthArray[depthIndex] = depth; } } else { // If the pixel is not zero, we will keep the original depth. smoothDepthArray[depthIndex] = pDepthArray[depthIndex]; } } }); return smoothDepthArray; } #region Getter/Tetter public int OuterBandThreshold { get { return m_OuterBandThreshold; } set { if (value > 0 && value <= MaxOuterBandThreshold) m_OuterBandThreshold = value; } } public int InnerBandThreshold { get { return m_InnerBandThreshold; } set { if (value > 0 && value <= MaxInnerBandThreshold) m_InnerBandThreshold = value; } } #endregion } }
// // Copyright 2010, Novell, Inc. // Copyright 2011, 2012 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; using MonoMac.ObjCRuntime; namespace MonoMac.Foundation { public partial class NSDictionary : IDictionary, IDictionary<NSObject, NSObject> { public NSDictionary (NSObject first, NSObject second, params NSObject [] args) : this (PickOdd (second, args), PickEven (first, args)) { } public NSDictionary (object first, object second, params object [] args) : this (PickOdd (second, args), PickEven (first, args)) { } static NSArray PickEven (NSObject f, NSObject [] args) { int al = args.Length; if ((al % 2) != 0) throw new ArgumentException ("The arguments to NSDictionary should be a multiple of two", "args"); var ret = new NSObject [1+al/2]; ret [0] = f; for (int i = 0, target = 1; i < al; i += 2) ret [target++] = args [i]; return NSArray.FromNSObjects (ret); } static NSArray PickOdd (NSObject f, NSObject [] args) { var ret = new NSObject [1+args.Length/2]; ret [0] = f; for (int i = 1, target = 1; i < args.Length; i += 2) ret [target++] = args [i]; return NSArray.FromNSObjects (ret); } static NSArray PickEven (object f, object [] args) { int al = args.Length; if ((al % 2) != 0) throw new ArgumentException ("The arguments to NSDictionary should be a multiple of two", "args"); var ret = new object [1+al/2]; ret [0] = f; for (int i = 0, target = 1; i < al; i += 2) ret [target++] = args [i]; return NSArray.FromObjects (ret); } static NSArray PickOdd (object f, object [] args) { var ret = new object [1+args.Length/2]; ret [0] = f; for (int i = 1, target = 1; i < args.Length; i += 2) ret [target++] = args [i]; return NSArray.FromObjects (ret); } public static NSDictionary FromObjectsAndKeys (NSObject [] objects, NSObject [] keys) { if (objects.Length != keys.Length) throw new ArgumentException ("objects and keys arrays have different sizes"); var no = NSArray.FromNSObjects (objects); var nk = NSArray.FromNSObjects (keys); var r = FromObjectsAndKeysInternal (no, nk); no.Dispose (); nk.Dispose (); return r; } public static NSDictionary FromObjectsAndKeys (object [] objects, object [] keys) { if (objects.Length != keys.Length) throw new ArgumentException ("objects and keys arrays have different sizes"); var no = NSArray.FromObjects (objects); var nk = NSArray.FromObjects (keys); var r = FromObjectsAndKeysInternal (no, nk); no.Dispose (); nk.Dispose (); return r; } public static NSDictionary FromObjectsAndKeys (NSObject [] objects, NSObject [] keys, int count) { if (objects.Length != keys.Length) throw new ArgumentException ("objects and keys arrays have different sizes"); if (count < 1 || objects.Length < count || keys.Length < count) throw new ArgumentException ("count"); var no = NSArray.FromNSObjects ((IList<NSObject>) objects, count); var nk = NSArray.FromNSObjects ((IList<NSObject>) keys, count); var r = FromObjectsAndKeysInternal (no, nk); no.Dispose (); nk.Dispose (); return r; } public static NSDictionary FromObjectsAndKeys (object [] objects, object [] keys, int count) { if (objects.Length != keys.Length) throw new ArgumentException ("objects and keys arrays have different sizes"); if (count < 1 || objects.Length < count || keys.Length < count) throw new ArgumentException ("count"); var no = NSArray.FromObjects (count, objects); var nk = NSArray.FromObjects (count, keys); var r = FromObjectsAndKeysInternal (no, nk); no.Dispose (); nk.Dispose (); return r; } internal bool ContainsKeyValuePair (KeyValuePair<NSObject, NSObject> pair) { NSObject value; if (!TryGetValue (pair.Key, out value)) return false; return EqualityComparer<NSObject>.Default.Equals (pair.Value, value); } #region ICollection void ICollection.CopyTo (Array array, int arrayIndex) { if (array == null) throw new ArgumentNullException ("array"); if (arrayIndex < 0) throw new ArgumentOutOfRangeException ("arrayIndex"); if (array.Rank > 1) throw new ArgumentException ("array is multidimensional"); if ((array.Length > 0) && (arrayIndex >= array.Length)) throw new ArgumentException ("arrayIndex is equal to or greater than array.Length"); if (arrayIndex + Count > array.Length) throw new ArgumentException ("Not enough room from arrayIndex to end of array for this Hashtable"); IDictionaryEnumerator e = ((IDictionary) this).GetEnumerator (); int i = arrayIndex; while (e.MoveNext ()) array.SetValue (e.Entry, i++); } int ICollection.Count { get {return (int) Count;} } bool ICollection.IsSynchronized { get {return false;} } object ICollection.SyncRoot { get {return this;} } #endregion #region ICollection<KeyValuePair<NSObject, NSObject>> void ICollection<KeyValuePair<NSObject, NSObject>>.Add (KeyValuePair<NSObject, NSObject> item) { throw new NotSupportedException (); } void ICollection<KeyValuePair<NSObject, NSObject>>.Clear () { throw new NotSupportedException (); } bool ICollection<KeyValuePair<NSObject, NSObject>>.Contains (KeyValuePair<NSObject, NSObject> keyValuePair) { return ContainsKeyValuePair (keyValuePair); } void ICollection<KeyValuePair<NSObject, NSObject>>.CopyTo (KeyValuePair<NSObject, NSObject>[] array, int index) { if (array == null) throw new ArgumentNullException ("array"); if (index < 0) throw new ArgumentOutOfRangeException ("index"); // we want no exception for index==array.Length && Count == 0 if (index > array.Length) throw new ArgumentException ("index larger than largest valid index of array"); if (array.Length - index < Count) throw new ArgumentException ("Destination array cannot hold the requested elements!"); var e = GetEnumerator (); while (e.MoveNext ()) array [index++] = e.Current; } bool ICollection<KeyValuePair<NSObject, NSObject>>.Remove (KeyValuePair<NSObject, NSObject> keyValuePair) { throw new NotSupportedException (); } int ICollection<KeyValuePair<NSObject, NSObject>>.Count { get {return (int) Count;} } bool ICollection<KeyValuePair<NSObject, NSObject>>.IsReadOnly { get {return true;} } #endregion #region IDictionary void IDictionary.Add (object key, object value) { throw new NotSupportedException (); } void IDictionary.Clear () { throw new NotSupportedException (); } bool IDictionary.Contains (object key) { if (key == null) throw new ArgumentNullException ("key"); NSObject _key = key as NSObject; if (_key == null) return false; return ContainsKey (_key); } IDictionaryEnumerator IDictionary.GetEnumerator () { return new ShimEnumerator (this); } [Serializable] class ShimEnumerator : IDictionaryEnumerator, IDisposable, IEnumerator { IEnumerator<KeyValuePair<NSObject, NSObject>> e; public ShimEnumerator (NSDictionary host) { e = host.GetEnumerator (); } public void Dispose () { e.Dispose (); } public bool MoveNext () { return e.MoveNext (); } public DictionaryEntry Entry { get { return new DictionaryEntry { Key = e.Current.Key, Value = e.Current.Value }; } } public object Key { get { return e.Current.Key; } } public object Value { get { return e.Current.Value; } } public object Current { get {return Entry;} } public void Reset () { e.Reset (); } } void IDictionary.Remove (object key) { throw new NotSupportedException (); } bool IDictionary.IsFixedSize { get {return true;} } bool IDictionary.IsReadOnly { get {return true;} } object IDictionary.this [object key] { get { NSObject _key = key as NSObject; if (_key == null) return null; return ObjectForKey (_key); } set { throw new NotSupportedException (); } } ICollection IDictionary.Keys { get {return Keys;} } ICollection IDictionary.Values { get {return Values;} } #endregion #region IDictionary<NSObject, NSObject> void IDictionary<NSObject, NSObject>.Add (NSObject key, NSObject value) { throw new NotSupportedException (); } static readonly NSObject marker = new NSObject (); public bool ContainsKey (NSObject key) { if (key == null) throw new ArgumentNullException ("key"); return ObjectForKey (key) != null; } bool IDictionary<NSObject, NSObject>.Remove (NSObject key) { throw new NotSupportedException (); } public bool TryGetValue (NSObject key, out NSObject value) { if (key == null) throw new ArgumentNullException ("key"); value = ObjectForKey (key); // NSDictionary can not contain NULLs, if you want a NULL, it exists as an NSNulln if (value == null) return false; return true; } public virtual NSObject this [NSObject key] { get { if (key == null) throw new ArgumentNullException ("key"); return ObjectForKey (key); } set { throw new NotSupportedException (); } } public virtual NSObject this [NSString key] { get { if (key == null) throw new ArgumentNullException ("key"); return ObjectForKey (key); } set { throw new NotSupportedException (); } } public virtual NSObject this [string key] { get { if (key == null) throw new ArgumentNullException ("key"); using (var nss = new NSString (key)){ return ObjectForKey (nss); } } set { throw new NotSupportedException (); } } ICollection<NSObject> IDictionary<NSObject, NSObject>.Keys { get {return Keys;} } ICollection<NSObject> IDictionary<NSObject, NSObject>.Values { get {return Values;} } #endregion IEnumerator IEnumerable.GetEnumerator () { return GetEnumerator (); } public IEnumerator<KeyValuePair<NSObject, NSObject>> GetEnumerator () { foreach (var key in Keys) { yield return new KeyValuePair<NSObject, NSObject> (key, ObjectForKey (key)); } } public IntPtr LowlevelObjectForKey (IntPtr key) { #if MONOMAC return MonoMac.ObjCRuntime.Messaging.IntPtr_objc_msgSend_IntPtr (this.Handle, selObjectForKey_Handle, key); #else return MonoMac.ObjCRuntime.Messaging.IntPtr_objc_msgSend_IntPtr (this.Handle, Selector.GetHandle (selObjectForKey_), key); #endif } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Microsoft.Build.Tasks; using Xunit; using Xunit.Abstractions; namespace Microsoft.Build.UnitTests { sealed public class ResolveNonMSBuildProjectOutput_Tests { private const string attributeProject = "Project"; private readonly ITestOutputHelper _output; public ResolveNonMSBuildProjectOutput_Tests(ITestOutputHelper output) { _output = output; } static internal ITaskItem CreateReferenceItem(string itemSpec, string projectGuid, string package, string name) { TaskItem reference = new TaskItem(itemSpec); if (projectGuid != null) reference.SetMetadata(attributeProject, projectGuid); if (package != null) reference.SetMetadata("Package", package); if (name != null) reference.SetMetadata("Name", name); return reference; } private void TestVerifyReferenceAttributesHelper(string itemSpec, string projectGuid, string package, string name, bool expectedResult, string expectedMissingAttribute) { ITaskItem reference = CreateReferenceItem(itemSpec, projectGuid, package, name); ResolveNonMSBuildProjectOutput rvpo = new ResolveNonMSBuildProjectOutput(); string missingAttr; bool result = rvpo.VerifyReferenceAttributes(reference, out missingAttr); string message = string.Format("Reference \"{0}\" [project \"{1}\", package \"{2}\", name \"{3}\"], " + "expected result \"{4}\", actual result \"{5}\", expected missing attr \"{6}\", actual missing attr \"{7}\".", itemSpec, projectGuid, package, name, expectedResult, result, expectedMissingAttribute, missingAttr); Assert.Equal(result, expectedResult); if (!result) { Assert.Equal(missingAttr, expectedMissingAttribute); } else { Assert.Null(missingAttr); } } [Fact] public void TestVerifyReferenceAttributes() { // a correct reference TestVerifyReferenceAttributesHelper("proj1.csproj", "{CFF438C3-51D1-4E61-BECD-D7D3A6193DF7}", "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}", "CSDep", true, null); // incorrect project guid - should not work TestVerifyReferenceAttributesHelper("proj1.csproj", "{invalid guid}", "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}", "CSDep", false, "Project"); } static internal string CreatePregeneratedPathDoc(IDictionary projectOutputs) { string xmlString = "<VSIDEResolvedNonMSBuildProjectOutputs>"; foreach (DictionaryEntry entry in projectOutputs) { xmlString += string.Format("<ProjectRef Project=\"{0}\">{1}</ProjectRef>", entry.Key, entry.Value); } xmlString += "</VSIDEResolvedNonMSBuildProjectOutputs>"; return xmlString; } private void TestResolveHelper(string itemSpec, string projectGuid, string package, string name, Hashtable pregenOutputs, bool expectedResult, string expectedPath) { ITaskItem reference = CreateReferenceItem(itemSpec, projectGuid, package, name); string xmlString = CreatePregeneratedPathDoc(pregenOutputs); ITaskItem resolvedPath; ResolveNonMSBuildProjectOutput rvpo = new ResolveNonMSBuildProjectOutput(); rvpo.CacheProjectElementsFromXml(xmlString); bool result = rvpo.ResolveProject(reference, out resolvedPath); string message = string.Format("Reference \"{0}\" [project \"{1}\", package \"{2}\", name \"{3}\"] Pregen Xml string : \"{4}\"" + "expected result \"{5}\", actual result \"{6}\", expected path \"{7}\", actual path \"{8}\".", itemSpec, projectGuid, package, name, xmlString, expectedResult, result, expectedPath, resolvedPath); Assert.Equal(result, expectedResult); if (result) { Assert.Equal(resolvedPath.ItemSpec, expectedPath); } else { Assert.Null(resolvedPath); } } [Fact] [Trait("Category", "mono-osx-failing")] public void TestResolve() { // empty pre-generated string Hashtable projectOutputs = new Hashtable(); TestResolveHelper("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1", projectOutputs, false, null); // non matching project in string projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", Path.Combine("obj", "wrong.dll")); TestResolveHelper("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1", projectOutputs, false, null); // matching project in string projectOutputs = new Hashtable(); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", Path.Combine("obj", "correct.dll")); TestResolveHelper("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1", projectOutputs, true, Path.Combine("obj", "correct.dll")); // multiple non matching projects in string projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", Path.Combine("obj", "wrong.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111112}", Path.Combine("obj", "wrong2.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111113}", Path.Combine("obj", "wrong3.dll")); TestResolveHelper("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1", projectOutputs, false, null); // multiple non matching projects in string, one matching projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", Path.Combine("obj", "wrong.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111112}", Path.Combine("obj", "wrong2.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111113}", Path.Combine("obj", "wrong3.dll")); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", Path.Combine("obj", "correct.dll")); TestResolveHelper("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1", projectOutputs, true, Path.Combine("obj", "correct.dll")); } private void TestUnresolvedReferencesHelper(ArrayList projectRefs, Hashtable pregenOutputs, out Hashtable unresolvedOutputs, out Hashtable resolvedOutputs) { TestUnresolvedReferencesHelper(projectRefs, pregenOutputs, null, out unresolvedOutputs, out resolvedOutputs); } private void TestUnresolvedReferencesHelper(ArrayList projectRefs, Hashtable pregenOutputs, Func<string, bool> isManaged, out Hashtable unresolvedOutputs, out Hashtable resolvedOutputs) { ResolveNonMSBuildProjectOutput.GetAssemblyNameDelegate pretendGetAssemblyName = path => { if (isManaged != null && isManaged(path)) { return null; // just don't throw an exception } else { throw new BadImageFormatException(); // the hint that the caller takes for an unmanaged binary. } }; string xmlString = CreatePregeneratedPathDoc(pregenOutputs); MockEngine engine = new MockEngine(_output); ResolveNonMSBuildProjectOutput rvpo = new ResolveNonMSBuildProjectOutput(); rvpo.GetAssemblyName = pretendGetAssemblyName; rvpo.BuildEngine = engine; rvpo.PreresolvedProjectOutputs = xmlString; rvpo.ProjectReferences = (ITaskItem[])projectRefs.ToArray(typeof(ITaskItem)); bool result = rvpo.Execute(); unresolvedOutputs = new Hashtable(); for (int i = 0; i < rvpo.UnresolvedProjectReferences.Length; i++) { unresolvedOutputs[rvpo.UnresolvedProjectReferences[i].ItemSpec] = rvpo.UnresolvedProjectReferences[i]; } resolvedOutputs = new Hashtable(); for (int i = 0; i < rvpo.ResolvedOutputPaths.Length; i++) { resolvedOutputs[rvpo.ResolvedOutputPaths[i].ItemSpec] = rvpo.ResolvedOutputPaths[i]; } } [Fact] [Trait("Category", "mono-osx-failing")] public void TestManagedCheck() { Hashtable unresolvedOutputs = null; Hashtable resolvedOutputs = null; Hashtable projectOutputs = null; ArrayList projectRefs = new ArrayList(); projectRefs.Add(CreateReferenceItem("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-000000000000}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1")); projectRefs.Add(CreateReferenceItem("MCDep2.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep2")); // 1. multiple project refs, none resolvable projectOutputs = new Hashtable(); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-000000000000}", Path.Combine("obj", "managed.dll")); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", Path.Combine("obj", "unmanaged.dll")); TestUnresolvedReferencesHelper(projectRefs, projectOutputs, path => (path == Path.Combine("obj", "managed.dll")), out unresolvedOutputs, out resolvedOutputs); Assert.NotNull(resolvedOutputs); Assert.True(resolvedOutputs.Contains(Path.Combine("obj", "managed.dll"))); Assert.True(resolvedOutputs.Contains(Path.Combine("obj", "unmanaged.dll"))); Assert.Equal("true", ((ITaskItem)resolvedOutputs[Path.Combine("obj", "managed.dll")]).GetMetadata("ManagedAssembly")); Assert.NotEqual("true", ((ITaskItem)resolvedOutputs[Path.Combine("obj", "unmanaged.dll")]).GetMetadata("ManagedAssembly")); } /// <summary> /// Verifies that the UnresolvedProjectReferences output parameter is populated correctly. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestUnresolvedReferences() { ArrayList projectRefs = new ArrayList(); projectRefs.Add(CreateReferenceItem("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-000000000000}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1")); projectRefs.Add(CreateReferenceItem("MCDep2.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep2")); // 1. multiple project refs, none resolvable Hashtable projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", Path.Combine("obj", "wrong.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111112}", Path.Combine("obj", "wrong2.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111113}", Path.Combine("obj", "wrong3.dll")); Hashtable unresolvedOutputs; Hashtable resolvedOutputs; TestUnresolvedReferencesHelper(projectRefs, projectOutputs, out unresolvedOutputs, out resolvedOutputs); Assert.Empty(resolvedOutputs); // "No resolved refs expected for case 1" Assert.Equal(2, unresolvedOutputs.Count); // "Two unresolved refs expected for case 1" Assert.Equal(unresolvedOutputs["MCDep1.vcproj"], projectRefs[0]); Assert.Equal(unresolvedOutputs["MCDep2.vcproj"], projectRefs[1]); // 2. multiple project refs, one resolvable projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", Path.Combine("obj", "wrong.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111112}", Path.Combine("obj", "wrong2.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111113}", Path.Combine("obj", "wrong3.dll")); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", Path.Combine("obj", "correct.dll")); TestUnresolvedReferencesHelper(projectRefs, projectOutputs, out unresolvedOutputs, out resolvedOutputs); Assert.Single(resolvedOutputs); // "One resolved ref expected for case 2" Assert.True(resolvedOutputs.ContainsKey(Path.Combine("obj", "correct.dll"))); Assert.Single(unresolvedOutputs); // "One unresolved ref expected for case 2" Assert.Equal(unresolvedOutputs["MCDep1.vcproj"], projectRefs[0]); // 3. multiple project refs, all resolvable projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", Path.Combine("obj", "wrong.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111112}", Path.Combine("obj", "wrong2.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111113}", Path.Combine("obj", "wrong3.dll")); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", Path.Combine("obj", "correct.dll")); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-000000000000}", Path.Combine("obj", "correct2.dll")); TestUnresolvedReferencesHelper(projectRefs, projectOutputs, out unresolvedOutputs, out resolvedOutputs); Assert.Equal(2, resolvedOutputs.Count); // "Two resolved refs expected for case 3" Assert.True(resolvedOutputs.ContainsKey(Path.Combine("obj", "correct.dll"))); Assert.True(resolvedOutputs.ContainsKey(Path.Combine("obj", "correct2.dll"))); Assert.Empty(unresolvedOutputs); // "No unresolved refs expected for case 3" // 4. multiple project refs, all failed to resolve projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", Path.Combine("obj", "wrong.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111112}", Path.Combine("obj", "wrong2.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111113}", Path.Combine("obj", "wrong3.dll")); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", @""); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-000000000000}", @""); TestUnresolvedReferencesHelper(projectRefs, projectOutputs, out unresolvedOutputs, out resolvedOutputs); Assert.Empty(resolvedOutputs); // "No resolved refs expected for case 4" Assert.Empty(unresolvedOutputs); // "No unresolved refs expected for case 4" // 5. multiple project refs, one resolvable, one failed to resolve projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", Path.Combine("obj", "wrong.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111112}", Path.Combine("obj", "wrong2.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111113}", Path.Combine("obj", "wrong3.dll")); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", Path.Combine("obj", "correct.dll")); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-000000000000}", @""); TestUnresolvedReferencesHelper(projectRefs, projectOutputs, out unresolvedOutputs, out resolvedOutputs); Assert.Single(resolvedOutputs); // "One resolved ref expected for case 5" Assert.True(resolvedOutputs.ContainsKey(Path.Combine("obj", "correct.dll"))); Assert.Empty(unresolvedOutputs); // "No unresolved refs expected for case 5" // 6. multiple project refs, one unresolvable, one failed to resolve projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", Path.Combine("obj", "wrong.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111112}", Path.Combine("obj", "wrong2.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111113}", Path.Combine("obj", "wrong3.dll")); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-000000000000}", @""); TestUnresolvedReferencesHelper(projectRefs, projectOutputs, out unresolvedOutputs, out resolvedOutputs); Assert.Empty(resolvedOutputs); // "No resolved refs expected for case 6" Assert.Single(unresolvedOutputs); // "One unresolved ref expected for case 6" Assert.Equal(unresolvedOutputs["MCDep2.vcproj"], projectRefs[1]); } [Fact] public void TestVerifyProjectReferenceItem() { ResolveNonMSBuildProjectOutput rvpo = new ResolveNonMSBuildProjectOutput(); ITaskItem[] taskItems = new ITaskItem[1]; // bad GUID - this reference is invalid taskItems[0] = new TaskItem("projectReference"); taskItems[0].SetMetadata(attributeProject, "{invalid guid}"); MockEngine engine = new MockEngine(_output); rvpo.BuildEngine = engine; Assert.True(rvpo.VerifyProjectReferenceItems(taskItems, false /* treat problems as warnings */)); Assert.Equal(1, engine.Warnings); Assert.Equal(0, engine.Errors); engine.AssertLogContains("MSB3107"); engine = new MockEngine(_output); rvpo.BuildEngine = engine; Assert.False(rvpo.VerifyProjectReferenceItems(taskItems, true /* treat problems as errors */)); Assert.Equal(0, engine.Warnings); Assert.Equal(1, engine.Errors); engine.AssertLogContains("MSB3107"); } } }
namespace Nancy.Bootstrappers.Windsor { using System; using System.Collections.Generic; using System.Linq; using Castle.Core; using Castle.MicroKernel.Lifestyle; using Castle.MicroKernel.Lifestyle.Scoped; using Castle.MicroKernel.Registration; using Castle.MicroKernel.Resolvers.SpecializedResolvers; using Castle.Facilities.TypedFactory; using Castle.Windsor; using Configuration; using Diagnostics; using Bootstrapper; using Routing; /// <summary> /// Nancy bootstrapper for the Windsor container. /// </summary> public abstract class WindsorNancyBootstrapper : NancyBootstrapperBase<IWindsorContainer> { private bool modulesRegistered; /// <summary> /// Gets the diagnostics for intialisation /// </summary> /// <returns>IDiagnostics implementation</returns> protected override IDiagnostics GetDiagnostics() { return this.ApplicationContainer.Resolve<IDiagnostics>(); } /// <summary> /// Get all NancyModule implementation instances /// </summary> /// <param name="context">The current context</param> /// <returns>An <see cref="IEnumerable{T}"/> instance containing <see cref="NancyModule"/> instances.</returns> public override IEnumerable<INancyModule> GetAllModules(NancyContext context) { var currentScope = CallContextLifetimeScope.ObtainCurrentScope(); if (currentScope != null) { return this.ApplicationContainer.ResolveAll<INancyModule>(); } using (this.ApplicationContainer.BeginScope()) { return this.ApplicationContainer.ResolveAll<INancyModule>(); } } /// <summary> /// Gets the application level container /// </summary> /// <returns>Container instance</returns> protected override IWindsorContainer GetApplicationContainer() { if (this.ApplicationContainer != null) { return this.ApplicationContainer; } var container = new WindsorContainer(); return container; } /// <summary> /// Configures the container for use with Nancy. /// </summary> /// <param name="existingContainer"> /// An existing container. /// </param> protected override void ConfigureApplicationContainer(IWindsorContainer existingContainer) { var factoryType = typeof(TypedFactoryFacility); if (!existingContainer.Kernel.GetFacilities() .Any(x => x.GetType() == factoryType)) { existingContainer.AddFacility<TypedFactoryFacility>(); } existingContainer.Kernel.Resolver.AddSubResolver(new CollectionResolver(existingContainer.Kernel, true)); existingContainer.Register(Component.For<IWindsorContainer>().Instance(existingContainer)); existingContainer.Register(Component.For<NancyRequestScopeInterceptor>()); existingContainer.Kernel.ProxyFactory.AddInterceptorSelector(new NancyRequestScopeInterceptorSelector()); foreach (var requestStartupType in this.RequestStartupTasks) { this.ApplicationContainer.Register( Component.For(requestStartupType, typeof(IRequestStartup)) .LifestyleScoped(typeof(NancyPerWebRequestScopeAccessor)) .ImplementedBy(requestStartupType)); } base.ConfigureApplicationContainer(existingContainer); } /// <summary> /// Gets all registered application registration tasks /// </summary> /// <returns>An <see cref="System.Collections.Generic.IEnumerable{T}"/> instance containing <see cref="IRegistrations"/> instances.</returns> protected override IEnumerable<IRegistrations> GetRegistrationTasks() { return this.ApplicationContainer.ResolveAll<IRegistrations>(); } /// <summary> /// Gets all registered application startup tasks /// </summary> /// <returns>An <see cref="IEnumerable{T}"/> instance containing <see cref="IApplicationStartup"/> instances.</returns> protected override IEnumerable<IApplicationStartup> GetApplicationStartupTasks() { return this.ApplicationContainer.ResolveAll<IApplicationStartup>(); } /// <summary> /// Gets the <see cref="INancyEnvironmentConfigurator"/> used by th. /// </summary> /// <returns>An <see cref="INancyEnvironmentConfigurator"/> instance.</returns> protected override INancyEnvironmentConfigurator GetEnvironmentConfigurator() { return this.ApplicationContainer.Resolve<INancyEnvironmentConfigurator>(); } /// <summary> /// Registers an <see cref="INancyEnvironment"/> instance in the container. /// </summary> /// <param name="container">The container to register into.</param> /// <param name="environment">The <see cref="INancyEnvironment"/> instance to register.</param> protected override void RegisterNancyEnvironment(IWindsorContainer container, INancyEnvironment environment) { container.Register(Component.For<INancyEnvironment>().Instance(environment)); } /// <summary> /// Gets all registered request startup tasks /// </summary> /// <returns>An <see cref="IEnumerable{T}"/> instance containing <see cref="IRequestStartup"/> instances.</returns> protected override IEnumerable<IRequestStartup> RegisterAndGetRequestStartupTasks(IWindsorContainer container, Type[] requestStartupTypes) { return container.ResolveAll<IRequestStartup>(); } /// <summary> /// Resolve INancyEngine /// </summary> /// <returns>INancyEngine implementation</returns> protected override INancyEngine GetEngineInternal() { return this.ApplicationContainer.Resolve<INancyEngine>(); } /// <summary> /// Retrieves a specific <see cref="INancyModule"/> implementation - should be per-request lifetime /// </summary> /// <param name="moduleType">Module type</param> /// <param name="context">The current context</param> /// <returns>The <see cref="INancyModule"/> instance</returns> public override INancyModule GetModule(Type moduleType, NancyContext context) { var currentScope = CallContextLifetimeScope.ObtainCurrentScope(); if (currentScope != null) { return this.ApplicationContainer.Resolve<INancyModule>(moduleType.FullName); } using (this.ApplicationContainer.BeginScope()) { return this.ApplicationContainer.Resolve<INancyModule>(moduleType.FullName); } } /// <summary> /// Register the given module types into the container /// </summary> /// <param name="container">Container to register into</param> /// <param name="moduleRegistrationTypes">NancyModule types</param> protected override void RegisterModules(IWindsorContainer container, IEnumerable<ModuleRegistration> moduleRegistrationTypes) { if (this.modulesRegistered) { return; } this.modulesRegistered = true; var components = moduleRegistrationTypes.Select(r => Component.For(typeof(INancyModule)) .ImplementedBy(r.ModuleType).Named(r.ModuleType.FullName).LifeStyle.Scoped<NancyPerWebRequestScopeAccessor>()) .Cast<IRegistration>().ToArray(); this.ApplicationContainer.Register(components); } /// <summary> /// Register the bootstrapper's implemented types into the container. /// This is necessary so a user can pass in a populated container but not have /// to take the responsibility of registering things like INancyModuleCatalog manually. /// </summary> /// <param name="applicationContainer">Application container to register into</param> protected override void RegisterBootstrapperTypes(IWindsorContainer applicationContainer) { applicationContainer.Register(Component.For<INancyModuleCatalog>().Instance(this)); // DefaultRouteCacheProvider doesn't have a parameterless constructor. // It has a Func<IRouteCache> parameter, which Castle Windsor doesn't know how to handle var routeCacheFactory = new Func<IRouteCache>(applicationContainer.Resolve<IRouteCache>); applicationContainer.Register(Component.For<Func<IRouteCache>>().Instance(routeCacheFactory)); } /// <summary> /// Register the default implementations of internally used types into the container as singletons /// </summary> /// <param name="container"> Container to register into </param> /// <param name="typeRegistrations"> Type registrations to register </param> protected override void RegisterTypes(IWindsorContainer container, IEnumerable<TypeRegistration> typeRegistrations) { foreach (var typeRegistration in typeRegistrations) { RegisterNewOrAddService(container, typeRegistration.RegistrationType, typeRegistration.ImplementationType, typeRegistration.Lifetime); } } /// <summary> /// Register the various collections into the container as singletons to later be resolved by IEnumerable{Type} constructor dependencies. /// </summary> /// <param name="container"> Container to register into </param> /// <param name="collectionTypeRegistrations"> Collection type registrations to register </param> protected override void RegisterCollectionTypes(IWindsorContainer container, IEnumerable<CollectionTypeRegistration> collectionTypeRegistrations) { foreach (var typeRegistration in collectionTypeRegistrations) { foreach (var implementationType in typeRegistration.ImplementationTypes) { RegisterNewOrAddService(container, typeRegistration.RegistrationType, implementationType, typeRegistration.Lifetime); } } } /// <summary> /// Register the given instances into the container /// </summary> /// <param name="container">Container to register into</param> /// <param name="instanceRegistrations">Instance registration types</param> protected override void RegisterInstances(IWindsorContainer container, IEnumerable<InstanceRegistration> instanceRegistrations) { foreach (var instanceRegistration in instanceRegistrations) { container.Register(Component.For(instanceRegistration.RegistrationType) .Instance(instanceRegistration.Implementation)); } } private static void RegisterNewOrAddService(IWindsorContainer container, Type registrationType, Type implementationType, Lifetime lifetime) { var handler = container.Kernel.GetHandler(implementationType); if (handler != null) { handler.ComponentModel.AddService(registrationType); return; } var lifeStyle = LifestyleType.Singleton; switch (lifetime) { case Lifetime.Transient: container.Register( Component.For(implementationType, registrationType) .LifestyleTransient() .ImplementedBy(implementationType)); break; case Lifetime.Singleton: container.Register( Component.For(implementationType, registrationType) .LifestyleSingleton() .ImplementedBy(implementationType)); break; case Lifetime.PerRequest: container.Register( Component.For(implementationType, registrationType) .LifestyleScoped(typeof(NancyPerWebRequestScopeAccessor)) .ImplementedBy(implementationType)); break; default: throw new ArgumentOutOfRangeException("lifetime"); } } } }
namespace RRLab.PhysiologyWorkbench { partial class RecordingInfoControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param genotype="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.RecordingBindingSource = new System.Windows.Forms.BindingSource(this.components); this.TitleLabel = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.TitleTextbox = new System.Windows.Forms.TextBox(); this.CreatedTimePicker = new System.Windows.Forms.DateTimePicker(); this.label3 = new System.Windows.Forms.Label(); this.UsersBindingSource = new System.Windows.Forms.BindingSource(this.components); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.BathSolutionComboBox = new System.Windows.Forms.ComboBox(); this.PipetteSolutionComboBox = new System.Windows.Forms.ComboBox(); this.DescriptionTextbox = new System.Windows.Forms.TextBox(); this.tableLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.RecordingBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.UsersBindingSource)).BeginInit(); this.SuspendLayout(); // // tableLayoutPanel1 // this.tableLayoutPanel1.AutoSize = true; this.tableLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.tableLayoutPanel1.ColumnCount = 3; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 95F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 200F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel1.Controls.Add(this.DescriptionTextbox, 4, 1); this.tableLayoutPanel1.Controls.Add(this.TitleLabel, 0, 0); this.tableLayoutPanel1.Controls.Add(this.label2, 0, 1); this.tableLayoutPanel1.Controls.Add(this.TitleTextbox, 1, 0); this.tableLayoutPanel1.Controls.Add(this.CreatedTimePicker, 1, 1); this.tableLayoutPanel1.Controls.Add(this.label3, 2, 0); this.tableLayoutPanel1.Controls.Add(this.label4, 0, 2); this.tableLayoutPanel1.Controls.Add(this.label5, 0, 3); this.tableLayoutPanel1.Controls.Add(this.BathSolutionComboBox, 1, 2); this.tableLayoutPanel1.Controls.Add(this.PipetteSolutionComboBox, 1, 3); this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 5; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.Size = new System.Drawing.Size(516, 133); this.tableLayoutPanel1.TabIndex = 0; // // RecordingBindingSource // this.RecordingBindingSource.DataSource = typeof(RRLab.PhysiologyWorkbench.Data.Recording); // // TitleLabel // this.TitleLabel.AutoSize = true; this.TitleLabel.Dock = System.Windows.Forms.DockStyle.Fill; this.TitleLabel.Location = new System.Drawing.Point(3, 0); this.TitleLabel.Name = "TitleLabel"; this.TitleLabel.Size = new System.Drawing.Size(89, 26); this.TitleLabel.TabIndex = 0; this.TitleLabel.Text = "Title"; this.TitleLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label2 // this.label2.AutoSize = true; this.label2.Dock = System.Windows.Forms.DockStyle.Fill; this.label2.Location = new System.Drawing.Point(3, 26); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(89, 26); this.label2.TabIndex = 2; this.label2.Text = "Recorded"; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // TitleTextbox // this.TitleTextbox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.RecordingBindingSource, "Title", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); this.TitleTextbox.Dock = System.Windows.Forms.DockStyle.Fill; this.TitleTextbox.Location = new System.Drawing.Point(98, 3); this.TitleTextbox.Name = "TitleTextbox"; this.TitleTextbox.Size = new System.Drawing.Size(194, 20); this.TitleTextbox.TabIndex = 3; // // CreatedTimePicker // this.CreatedTimePicker.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.RecordingBindingSource, "Recorded", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); this.CreatedTimePicker.Dock = System.Windows.Forms.DockStyle.Fill; this.CreatedTimePicker.Format = System.Windows.Forms.DateTimePickerFormat.Time; this.CreatedTimePicker.Location = new System.Drawing.Point(98, 29); this.CreatedTimePicker.Name = "CreatedTimePicker"; this.CreatedTimePicker.Size = new System.Drawing.Size(194, 20); this.CreatedTimePicker.TabIndex = 5; // // label3 // this.label3.AutoSize = true; this.label3.Dock = System.Windows.Forms.DockStyle.Fill; this.label3.Location = new System.Drawing.Point(298, 0); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(215, 26); this.label3.TabIndex = 7; this.label3.Text = "Description"; this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // UsersBindingSource // this.UsersBindingSource.DataMember = "Users"; this.UsersBindingSource.DataSource = typeof(RRLab.PhysiologyWorkbench.Data.PhysiologyData); // // label4 // this.label4.AutoSize = true; this.label4.Dock = System.Windows.Forms.DockStyle.Fill; this.label4.Location = new System.Drawing.Point(3, 52); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(89, 27); this.label4.TabIndex = 11; this.label4.Text = "Bath Solution"; this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label5 // this.label5.AutoSize = true; this.label5.Dock = System.Windows.Forms.DockStyle.Fill; this.label5.Location = new System.Drawing.Point(3, 79); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(89, 27); this.label5.TabIndex = 12; this.label5.Text = "Pipette Solution"; this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // BathSolutionComboBox // this.BathSolutionComboBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.RecordingBindingSource, "BathSolution", true)); this.BathSolutionComboBox.Dock = System.Windows.Forms.DockStyle.Fill; this.BathSolutionComboBox.DropDownWidth = 350; this.BathSolutionComboBox.FormattingEnabled = true; this.BathSolutionComboBox.Items.AddRange(new object[] { "1 mM CaCl2, 120 mM NaCl, 5 mM KCl, 10 mM HEPES, 4 mM MgCl2, 24 mM proline, 5 mM a" + "lanine pH 7.15", "0 mM CaCl2, 120 mM NaCl, 5 mM KCl, 10 mM HEPES, 4 mM MgCl2, 24 mM proline, 5 mM a" + "lanine pH 7.15", "50 uM CaCl2, 120 mM NaCl, 5 mM KCl, 10 mM HEPES, 4 mM MgCl2, 24 mM proline, 5 mM " + "alanine pH 7.15", "100 uM CaCl2, 120 mM NaCl, 5 mM KCl, 10 mM HEPES, 4 mM MgCl2, 24 mM proline, 5 mM" + " alanine pH 7.15", "200 uM CaCl2, 120 mM NaCl, 5 mM KCl, 10 mM HEPES, 4 mM MgCl2, 24 mM proline, 5 mM" + " alanine pH 7.15", "0.5 mM CaCl2, 120 mM NaCl, 5 mM KCl, 10 mM HEPES, 4 mM MgCl2, 24 mM proline, 5 mM" + " alanine pH 7.15", "5 mM CaCl2, 120 mM NaCl, 5 mM KCl, 10 mM HEPES, 4 mM MgCl2, 24 mM proline, 5 mM a" + "lanine pH 7.15", "10 mM CaCl2, 120 mM NaCl, 5 mM KCl, 10 mM HEPES, 4 mM MgCl2, 24 mM proline, 5 mM " + "alanine pH 7.15", "20 mM CaCl2, 120 mM NaCl, 5 mM KCl, 10 mM HEPES, 4 mM MgCl2, 24 mM proline, 5 mM " + "alanine pH 7.15"}); this.BathSolutionComboBox.Location = new System.Drawing.Point(98, 55); this.BathSolutionComboBox.Name = "BathSolutionComboBox"; this.BathSolutionComboBox.Size = new System.Drawing.Size(194, 21); this.BathSolutionComboBox.TabIndex = 13; // // PipetteSolutionComboBox // this.PipetteSolutionComboBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.RecordingBindingSource, "PipetteSolution", true)); this.PipetteSolutionComboBox.Dock = System.Windows.Forms.DockStyle.Fill; this.PipetteSolutionComboBox.DropDownWidth = 350; this.PipetteSolutionComboBox.FormattingEnabled = true; this.PipetteSolutionComboBox.Items.AddRange(new object[] { "95 mM KGluconate, 40 mM KCl, 10 mM HEPES, 2 mM MgCl2, 4 mM MgATP, 0.5 mM NaGTP, 1" + " mM NAD+, pH 7.15"}); this.PipetteSolutionComboBox.Location = new System.Drawing.Point(98, 82); this.PipetteSolutionComboBox.Name = "PipetteSolutionComboBox"; this.PipetteSolutionComboBox.Size = new System.Drawing.Size(194, 21); this.PipetteSolutionComboBox.TabIndex = 14; // // DescriptionTextbox // this.DescriptionTextbox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.RecordingBindingSource, "Description", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); this.DescriptionTextbox.Dock = System.Windows.Forms.DockStyle.Fill; this.DescriptionTextbox.Location = new System.Drawing.Point(298, 29); this.DescriptionTextbox.Multiline = true; this.DescriptionTextbox.Name = "DescriptionTextbox"; this.tableLayoutPanel1.SetRowSpan(this.DescriptionTextbox, 4); this.DescriptionTextbox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.DescriptionTextbox.Size = new System.Drawing.Size(215, 101); this.DescriptionTextbox.TabIndex = 6; // // RecordingInfoControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoSize = true; this.Controls.Add(this.tableLayoutPanel1); this.Name = "RecordingInfoControl"; this.Size = new System.Drawing.Size(516, 133); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.RecordingBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.UsersBindingSource)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.Label TitleLabel; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox TitleTextbox; private System.Windows.Forms.DateTimePicker CreatedTimePicker; private System.Windows.Forms.Label label3; private System.Windows.Forms.BindingSource RecordingBindingSource; private System.Windows.Forms.BindingSource UsersBindingSource; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.ComboBox BathSolutionComboBox; private System.Windows.Forms.ComboBox PipetteSolutionComboBox; private System.Windows.Forms.TextBox DescriptionTextbox; } }
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Text; using UnityEngine; namespace NUnitLite.Unity { public class TextUIOptionBuilder { #region inner classes, enum, and structs public enum XmlReportFormat : int { NUnit2, NUnit3 } #endregion #region constants #endregion #region properties public List<string> AssembleFileNames { get; private set; } public string ReportFileName { get; private set; } public TextUIOptionBuilder.XmlReportFormat ReportFormat { get; private set; } public bool FullPrinting { get; private set; } public bool NoHeader { get; private set; } public string OutputFileName { get; private set; } public string IncludeCategory { get; private set; } public string ExcludeCategory { get; private set; } #endregion #region public methods public TextUIOptionBuilder() { AssembleFileNames = new List<string>(); ReportFileName = string.Empty; ReportFormat = TextUIOptionBuilder.XmlReportFormat.NUnit2; FullPrinting = true; NoHeader = false; OutputFileName = string.Empty; IncludeCategory = string.Empty; ExcludeCategory = string.Empty; } public string[] Build() { // default assemble files if (AssembleFileNames.Count == 0) { AssembleFileNames.Add(Assembly.GetCallingAssembly().FullName); } // required List<string> options = new List<string>(AssembleFileNames.ToArray()); string reportFileName = BuildReportFileName(ReportFileName); options.Add(reportFileName); string format = BuildFormat(ReportFormat); options.Add(format); // optionals string fullPrinting = BuildFullPrinting(FullPrinting); if (fullPrinting != string.Empty) { options.Add(fullPrinting); } string noHeader = BuildNoHeader(NoHeader); if (noHeader != string.Empty) { options.Add(noHeader); } string outputFileName = BuildOutPutFileName(OutputFileName); if (outputFileName != string.Empty) { options.Add(outputFileName); } string includeCategory = BuildIncludeCategory(IncludeCategory); if (includeCategory != string.Empty) { options.Add(includeCategory); } string excludeCategory = BuildExcludeCategory(ExcludeCategory); if (excludeCategory != string.Empty) { options.Add(excludeCategory); } return options.ToArray(); } public TextUIOptionBuilder AddAssembleFileName(string value) { AssembleFileNames.Add(value); return this; } public TextUIOptionBuilder SetReportFileName(string value) { ReportFileName = value; return this; } public TextUIOptionBuilder SetReportFormat(TextUIOptionBuilder.XmlReportFormat value) { ReportFormat = value; return this; } public TextUIOptionBuilder SetFullPrinting(bool value) { FullPrinting = value; return this; } public TextUIOptionBuilder SetNoHeader(bool value) { NoHeader = value; return this; } public TextUIOptionBuilder SetOutputFileName(string value) { OutputFileName = value; return this; } public TextUIOptionBuilder SetIncludeCategory(string value) { IncludeCategory = value; return this; } public TextUIOptionBuilder SetExcludeCategory(string value) { ExcludeCategory = value; return this; } #endregion #region override unity methods #endregion #region methods string BuildReportFileName(string value) { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Invalid required argument => " + value.ToString()); } StringBuilder builder = new StringBuilder(); builder.AppendFormat("-result:{0}", value); return builder.ToString(); } string BuildFormat(TextUIOptionBuilder.XmlReportFormat value) { string result = string.Empty; switch (value) { case TextUIOptionBuilder.XmlReportFormat.NUnit2: result = "-format:nunit2"; break; case TextUIOptionBuilder.XmlReportFormat.NUnit3: result = "-format:nunit3"; break; default: throw new ArgumentException("The argument format was not supported => " + value.ToString()); } return result; } string BuildFullPrinting(bool value) { return value ? "-full" : string.Empty; } string BuildNoHeader(bool value) { return value ? "-noheader" : string.Empty; } string BuildOutPutFileName(string value) { if (string.IsNullOrEmpty(value)) { return string.Empty; } StringBuilder builder = new StringBuilder(); builder.AppendFormat("-out:{0}", value); return builder.ToString(); } string BuildIncludeCategory(string value) { if (string.IsNullOrEmpty(value)) { return string.Empty; } StringBuilder builder = new StringBuilder(); builder.AppendFormat("-include:{0}", value); return builder.ToString(); } string BuildExcludeCategory(string value) { if (string.IsNullOrEmpty(value)) { return string.Empty; } StringBuilder builder = new StringBuilder(); builder.AppendFormat("-exclude:{0}", value); return builder.ToString(); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Linq; using Xunit; namespace System.Tests { public abstract partial class ArraySegment_Tests<T> { [Fact] public void CopyTo_Default_ThrowsInvalidOperationException() { // Source is default Assert.Throws<InvalidOperationException>(() => default(ArraySegment<T>).CopyTo(new T[0])); Assert.Throws<InvalidOperationException>(() => default(ArraySegment<T>).CopyTo(new T[0], 0)); Assert.Throws<InvalidOperationException>(() => ((ICollection<T>)default(ArraySegment<T>)).CopyTo(new T[0], 0)); Assert.Throws<InvalidOperationException>(() => default(ArraySegment<T>).CopyTo(new ArraySegment<T>(new T[0]))); // Destination is default Assert.Throws<InvalidOperationException>(() => new ArraySegment<T>(new T[0]).CopyTo(default(ArraySegment<T>))); } [Fact] public void Empty() { ArraySegment<T> empty = ArraySegment<T>.Empty; // Assert.NotEqual uses its own Comparer, when it is comparing IEnumerables it calls GetEnumerator() // ArraySegment<T>.GetEnumerator() throws InvalidOperationException when the array is null and default() returns null Assert.True(default(ArraySegment<T>) != empty); // Check that two Empty invocations return equal ArraySegments. Assert.Equal(empty, ArraySegment<T>.Empty); // Check that two Empty invocations return ArraySegments with a cached empty array. // An empty array is necessary to ensure that someone doesn't use the indexer to store data in the array Empty refers to. Assert.Same(empty.Array, ArraySegment<T>.Empty.Array); Assert.Equal(0, empty.Array.Length); Assert.Equal(0, empty.Offset); Assert.Equal(0, empty.Count); } [Fact] public void GetEnumerator_TypeProperties() { var arraySegment = new ArraySegment<T>(new T[1], 0, 1); var ienumerableoft = (IEnumerable<T>)arraySegment; var ienumerable = (IEnumerable)arraySegment; ArraySegment<T>.Enumerator enumerator = arraySegment.GetEnumerator(); Assert.IsType<ArraySegment<T>.Enumerator>(enumerator); Assert.IsAssignableFrom<IEnumerator<T>>(enumerator); Assert.IsAssignableFrom<IEnumerator>(enumerator); IEnumerator<T> ienumeratoroft = ienumerableoft.GetEnumerator(); IEnumerator ienumerator = ienumerable.GetEnumerator(); Assert.Equal(enumerator.GetType(), ienumeratoroft.GetType()); Assert.Equal(ienumeratoroft.GetType(), ienumerator.GetType()); } [Fact] public void GetEnumerator_Default_ThrowsInvalidOperationException() { Assert.Throws<InvalidOperationException>(() => default(ArraySegment<T>).GetEnumerator()); } [Fact] public void Slice_Default_ThrowsInvalidOperationException() { Assert.Throws<InvalidOperationException>(() => default(ArraySegment<T>).Slice(0)); Assert.Throws<InvalidOperationException>(() => default(ArraySegment<T>).Slice(0, 0)); } [Fact] public void ToArray_Default_ThrowsInvalidOperationException() { Assert.Throws<InvalidOperationException>(() => default(ArraySegment<T>).ToArray()); } [Fact] public void ToArray_Empty_ReturnsSameArray() { T[] cachedArray = ArraySegment<T>.Empty.ToArray(); Assert.Same(cachedArray, ArraySegment<T>.Empty.ToArray()); Assert.Same(cachedArray, new ArraySegment<T>(new T[0]).ToArray()); Assert.Same(cachedArray, new ArraySegment<T>(new T[1], 0, 0).ToArray()); } [Fact] public void ToArray_NonEmptyArray_DoesNotReturnSameArray() { // Prevent a faulty implementation like `if (Count == 0) { return Array; }` var emptyArraySegment = new ArraySegment<T>(new T[1], 0, 0); Assert.NotSame(emptyArraySegment.Array, emptyArraySegment.ToArray()); } [Fact] public void Cast_FromNullArray_ReturnsDefault() { ArraySegment<T> fromNull = null; Assert.Null(fromNull.Array); Assert.Equal(0, fromNull.Offset); Assert.Equal(0, fromNull.Count); Assert.True(default(ArraySegment<T>) == null); Assert.True(new ArraySegment<T>(Array.Empty<T>()) != null); } [Fact] public void Cast_FromValidArray_ReturnsSegmentForWholeArray() { var array = new T[42]; ArraySegment<T> fromArray = array; Assert.Same(array, fromArray.Array); Assert.Equal(0, fromArray.Offset); Assert.Equal(42, fromArray.Count); } } public static partial class ArraySegment_Tests { [Theory] [MemberData(nameof(Conversion_FromArray_TestData))] public static void Conversion_FromArray(int[] array) { ArraySegment<int> implicitlyConverted = array; ArraySegment<int> explicitlyConverted = (ArraySegment<int>)array; var expected = new ArraySegment<int>(array); Assert.Equal(expected, implicitlyConverted); Assert.Equal(expected, explicitlyConverted); } public static IEnumerable<object[]> Conversion_FromArray_TestData() { yield return new object[] { new int[0] }; yield return new object[] { new int[1] }; } [Theory] [MemberData(nameof(ArraySegment_TestData))] public static void CopyTo(ArraySegment<int> arraySegment) { const int CopyPadding = 5; const int DestinationSegmentPadding = 3; int count = arraySegment.Count; var destinationModel = new int[count + 2 * CopyPadding]; // CopyTo(T[]) CopyAndInvoke(destinationModel, destination => { arraySegment.CopyTo(destination); Assert.Equal(Enumerable.Repeat(default(int), 2 * CopyPadding), destination.Skip(count)); Assert.Equal(arraySegment, destination.Take(count)); }); // CopyTo(T[], int) CopyAndInvoke(destinationModel, destination => { arraySegment.CopyTo(destination, CopyPadding); Assert.Equal(Enumerable.Repeat(default(int), CopyPadding), destination.Take(CopyPadding)); Assert.Equal(Enumerable.Repeat(default(int), CopyPadding), destination.Skip(CopyPadding + count)); Assert.Equal(arraySegment, destination.Skip(CopyPadding).Take(count)); }); // ICollection<T>.CopyTo(T[], int) CopyAndInvoke(destinationModel, destination => { ((ICollection<int>)arraySegment).CopyTo(destination, CopyPadding); Assert.Equal(Enumerable.Repeat(default(int), CopyPadding), destination.Take(CopyPadding)); Assert.Equal(Enumerable.Repeat(default(int), CopyPadding), destination.Skip(CopyPadding + count)); Assert.Equal(arraySegment, destination.Skip(CopyPadding).Take(count)); }); // CopyTo(ArraySegment<T>) CopyAndInvoke(destinationModel, destination => { // We want to make sure this overload is handling edge cases correctly, like ArraySegments that // do not begin at the array's start, do not end at the array's end, or have a bigger count than // the source ArraySegment. Construct an ArraySegment that will test all of these conditions. int destinationIndex = DestinationSegmentPadding; int destinationCount = destination.Length - 2 * DestinationSegmentPadding; var destinationSegment = new ArraySegment<int>(destination, destinationIndex, destinationCount); arraySegment.CopyTo(destinationSegment); Assert.Equal(Enumerable.Repeat(default(int), destinationIndex), destination.Take(destinationIndex)); int remainder = destination.Length - destinationIndex - count; Assert.Equal(Enumerable.Repeat(default(int), remainder), destination.Skip(destinationIndex + count)); Assert.Equal(arraySegment, destination.Skip(destinationIndex).Take(count)); }); } private static void CopyAndInvoke<T>(T[] array, Action<T[]> action) => action(array.ToArray()); [Theory] [MemberData(nameof(ArraySegment_TestData))] public static void CopyTo_Invalid(ArraySegment<int> arraySegment) { int count = arraySegment.Count; // ArraySegment.CopyTo calls Array.Copy internally, so the exception parameter names come from there. // Destination is null AssertExtensions.Throws<ArgumentNullException>("destinationArray", () => arraySegment.CopyTo(null)); AssertExtensions.Throws<ArgumentNullException>("destinationArray", () => arraySegment.CopyTo(null, 0)); // Destination index not within range AssertExtensions.Throws<ArgumentOutOfRangeException>("destinationIndex", () => arraySegment.CopyTo(new int[0], -1)); // Destination array too small arraySegment.Count + destinationIndex > destinationArray.Length AssertExtensions.Throws<ArgumentException>("destinationArray", () => arraySegment.CopyTo(new int[arraySegment.Count * 2], arraySegment.Count + 1)); if (arraySegment.Any()) { // Destination not large enough AssertExtensions.Throws<ArgumentException>("destinationArray", () => arraySegment.CopyTo(new int[count - 1])); AssertExtensions.Throws<ArgumentException>("destinationArray", () => arraySegment.CopyTo(new int[count - 1], 0)); AssertExtensions.Throws<ArgumentException>("destination", null, () => arraySegment.CopyTo(new ArraySegment<int>(new int[count - 1]))); // Don't write beyond the limits of the destination in cases where source.Count > destination.Count AssertExtensions.Throws<ArgumentException>("destination", null, () => arraySegment.CopyTo(new ArraySegment<int>(new int[count], 1, 0))); // destination.Array can't fit source at destination.Offset AssertExtensions.Throws<ArgumentException>("destination", null, () => arraySegment.CopyTo(new ArraySegment<int>(new int[count], 0, count - 1))); // destination.Array can fit source at destination.Offset, but destination can't } } [Theory] [MemberData(nameof(ArraySegment_TestData))] public static void GetEnumerator(ArraySegment<int> arraySegment) { int[] array = arraySegment.Array; int index = arraySegment.Offset; int count = arraySegment.Count; ArraySegment<int>.Enumerator enumerator = arraySegment.GetEnumerator(); var actual = new List<int>(); while (enumerator.MoveNext()) { actual.Add(enumerator.Current); } // After MoveNext returns false once, it should return false the second time. Assert.False(enumerator.MoveNext()); IEnumerable<int> expected = array.Skip(index).Take(count); Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(ArraySegment_TestData))] public static void GetEnumerator_Dispose(ArraySegment<int> arraySegment) { int[] array = arraySegment.Array; int index = arraySegment.Offset; ArraySegment<int>.Enumerator enumerator = arraySegment.GetEnumerator(); bool expected = arraySegment.Count > 0; // Dispose shouldn't do anything. Call it twice and then assert like nothing happened. enumerator.Dispose(); enumerator.Dispose(); Assert.Equal(expected, enumerator.MoveNext()); if (expected) { Assert.Equal(array[index], enumerator.Current); } } [Theory] [MemberData(nameof(ArraySegment_TestData))] public static void GetEnumerator_Reset(ArraySegment<int> arraySegment) { int[] array = arraySegment.Array; int index = arraySegment.Offset; int count = arraySegment.Count; var enumerator = (IEnumerator<int>)arraySegment.GetEnumerator(); int[] expected = array.Skip(index).Take(count).ToArray(); // Reset at a variety of different positions to ensure the implementation // isn't something like `position -= CONSTANT`. for (int i = 0; i < 3; i++) { for (int j = 0; j < i; j++) { if (enumerator.MoveNext()) { Assert.Equal(expected[j], enumerator.Current); } } enumerator.Reset(); } } [Theory] [MemberData(nameof(ArraySegment_TestData))] public static void GetEnumerator_Invalid(ArraySegment<int> arraySegment) { ArraySegment<int>.Enumerator enumerator = arraySegment.GetEnumerator(); // Before beginning Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => ((IEnumerator<int>)enumerator).Current); Assert.Throws<InvalidOperationException>(() => ((IEnumerator)enumerator).Current); while (enumerator.MoveNext()) ; // After end Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => ((IEnumerator<int>)enumerator).Current); Assert.Throws<InvalidOperationException>(() => ((IEnumerator)enumerator).Current); } [Theory] [MemberData(nameof(ArraySegment_TestData))] public static void GetSetItem_InRange(ArraySegment<int> arraySegment) { int[] array = arraySegment.Array; int index = arraySegment.Offset; int count = arraySegment.Count; int[] expected = array.Skip(index).Take(count).ToArray(); for (int i = 0; i < count; i++) { Assert.Equal(expected[i], arraySegment[i]); Assert.Equal(expected[i], ((IList<int>)arraySegment)[i]); Assert.Equal(expected[i], ((IReadOnlyList<int>)arraySegment)[i]); } var r = new Random(0); for (int i = 0; i < count; i++) { int next = r.Next(int.MinValue, int.MaxValue); // When we modify the underlying array, the indexer should return the updated values. array[arraySegment.Offset + i] ^= next; Assert.Equal(expected[i] ^ next, arraySegment[i]); // When the indexer's set method is called, the underlying array should be modified. arraySegment[i] ^= next; Assert.Equal(expected[i], array[arraySegment.Offset + i]); } } [Theory] [MemberData(nameof(ArraySegment_TestData))] public static void GetSetItem_NotInRange_Invalid(ArraySegment<int> arraySegment) { int[] array = arraySegment.Array; // Before array start Assert.Throws<ArgumentOutOfRangeException>(() => arraySegment[-arraySegment.Offset - 1]); Assert.Throws<ArgumentOutOfRangeException>(() => arraySegment[-arraySegment.Offset - 1] = default(int)); // After array start (if Offset > 0), before start Assert.Throws<ArgumentOutOfRangeException>(() => arraySegment[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => arraySegment[-1] = default(int)); // Before array end (if Offset + Count < Array.Length), after end Assert.Throws<ArgumentOutOfRangeException>(() => arraySegment[arraySegment.Count]); Assert.Throws<ArgumentOutOfRangeException>(() => arraySegment[arraySegment.Count] = default(int)); // After array end Assert.Throws<ArgumentOutOfRangeException>(() => arraySegment[-arraySegment.Offset + array.Length]); Assert.Throws<ArgumentOutOfRangeException>(() => arraySegment[-arraySegment.Offset + array.Length] = default(int)); } [Theory] [MemberData(nameof(Slice_TestData))] public static void Slice(ArraySegment<int> arraySegment, int index, int count) { var expected = new ArraySegment<int>(arraySegment.Array, arraySegment.Offset + index, count); if (index + count == arraySegment.Count) { Assert.Equal(expected, arraySegment.Slice(index)); } Assert.Equal(expected, arraySegment.Slice(index, count)); } public static IEnumerable<object[]> Slice_TestData() { IEnumerable<ArraySegment<int>> arraySegments = ArraySegment_TestData().Select(array => array.Single()).Cast<ArraySegment<int>>(); foreach (ArraySegment<int> arraySegment in arraySegments) { yield return new object[] { arraySegment, 0, 0 }; // Preserve start, no items yield return new object[] { arraySegment, 0, arraySegment.Count }; // Preserve start, preserve count (noop) yield return new object[] { arraySegment, arraySegment.Count, 0 }; // Start at end, no items if (arraySegment.Any()) { yield return new object[] { arraySegment, 1, 0 }; // Start at middle or end, no items yield return new object[] { arraySegment, 1, arraySegment.Count - 1 }; // Start at middle or end, rest of items yield return new object[] { arraySegment, arraySegment.Count - 1, 1 }; // Preserve start or start at middle, one item } yield return new object[] { arraySegment, 0, arraySegment.Count / 2 }; // Preserve start, multiple items, end at middle yield return new object[] { arraySegment, arraySegment.Count / 2, arraySegment.Count / 2 }; // Start at middle, multiple items, end at middle (due to integer division truncation) or preserve end yield return new object[] { arraySegment, arraySegment.Count / 4, arraySegment.Count / 2 }; // Start at middle, multiple items, end at middle } } [Theory] [MemberData(nameof(Slice_Invalid_TestData))] public static void Slice_Invalid(ArraySegment<int> arraySegment, int index, int count) { if (index + count == arraySegment.Count) { AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => arraySegment.Slice(index)); } AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => arraySegment.Slice(index, count)); } public static IEnumerable<object[]> Slice_Invalid_TestData() { var arraySegment = new ArraySegment<int>(new int[3], offset: 1, count: 1); yield return new object[] { arraySegment, -arraySegment.Offset, arraySegment.Offset }; yield return new object[] { arraySegment, -arraySegment.Offset, arraySegment.Offset + arraySegment.Count }; yield return new object[] { arraySegment, -arraySegment.Offset, arraySegment.Array.Length }; yield return new object[] { arraySegment, 0, arraySegment.Array.Length - arraySegment.Offset }; yield return new object[] { arraySegment, arraySegment.Count, arraySegment.Array.Length - arraySegment.Offset - arraySegment.Count }; } [Theory] [MemberData(nameof(ArraySegment_TestData))] public static void ToArray(ArraySegment<int> arraySegment) { // ToList is called here so we copy the data and raise an assert if ToArray modifies the underlying array. List<int> expected = arraySegment.Array.Skip(arraySegment.Offset).Take(arraySegment.Count).ToList(); Assert.Equal(expected, arraySegment.ToArray()); } public static IEnumerable<object[]> ArraySegment_TestData() { var arraySegments = new (int[] array, int index, int count)[] { (array: new int[0], index: 0, 0), // Empty array (array: new[] { 3, 4, 5, 6 }, index: 0, count: 4), // Full span of non-empty array (array: new[] { 3, 4, 5, 6 }, index: 0, count: 3), // Starts at beginning, ends in middle (array: new[] { 3, 4, 5, 6 }, index: 1, count: 3), // Starts in middle, ends at end (array: new[] { 3, 4, 5, 6 }, index: 1, count: 2), // Starts in middle, ends in middle (array: new[] { 3, 4, 5, 6 }, index: 1, count: 0) // Non-empty array, count == 0 }; return arraySegments.Select(aseg => new object[] { new ArraySegment<int>(aseg.array, aseg.index, aseg.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.Reflection; using System.Reflection.Emit; using Xunit; namespace System.Reflection.Emit.Tests { public class TypeBuilderCreateType2 { private const int MinAsmName = 1; private const int MaxAsmName = 260; private const int MinModName = 1; private const int MaxModName = 260; private const int MinTypName = 1; private const int MaxTypName = 1024; private const int NumLoops = 5; private TypeAttributes[] _typesPos = new TypeAttributes[17] { TypeAttributes.Abstract | TypeAttributes.NestedPublic, TypeAttributes.AnsiClass | TypeAttributes.NestedPublic, TypeAttributes.AutoClass | TypeAttributes.NestedPublic, TypeAttributes.AutoLayout | TypeAttributes.NestedPublic, TypeAttributes.BeforeFieldInit | TypeAttributes.NestedPublic, TypeAttributes.Class | TypeAttributes.NestedPublic, TypeAttributes.ClassSemanticsMask | TypeAttributes.Abstract | TypeAttributes.NestedPublic, TypeAttributes.ExplicitLayout | TypeAttributes.NestedPublic, TypeAttributes.Import | TypeAttributes.NestedPublic, TypeAttributes.Interface | TypeAttributes.Abstract | TypeAttributes.NestedPublic, TypeAttributes.Sealed | TypeAttributes.NestedPublic, TypeAttributes.SequentialLayout | TypeAttributes.NestedPublic, TypeAttributes.Serializable | TypeAttributes.NestedPublic, TypeAttributes.SpecialName | TypeAttributes.NestedPublic, TypeAttributes.StringFormatMask | TypeAttributes.NestedPublic, TypeAttributes.UnicodeClass | TypeAttributes.NestedPublic, TypeAttributes.VisibilityMask, }; [Fact] public void TestDefineNestedType() { ModuleBuilder modBuilder; TypeBuilder typeBuilder; TypeBuilder nestedType = null; Type newType; string typeName = ""; string nestedTypeName = ""; modBuilder = CreateModule( TestLibrary.Generator.GetString(true, MinAsmName, MaxAsmName), TestLibrary.Generator.GetString(false, MinModName, MaxModName)); typeName = TestLibrary.Generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls typeBuilder = modBuilder.DefineType(typeName); for (int i = 0; i < NumLoops; i++) { nestedTypeName = TestLibrary.Generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls // create nested type if (null != nestedType && 0 == (TestLibrary.Generator.GetInt32() % 2)) { nestedType.DefineNestedType(nestedTypeName, TypeAttributes.Abstract | TypeAttributes.NestedPublic); } else { nestedType = typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.Abstract | TypeAttributes.NestedPublic); } } newType = typeBuilder.CreateTypeInfo().AsType(); Assert.True(newType.Name.Equals(typeName)); } [Fact] public void TestDefineNestedTypeWithEmbeddedNullsInName() { ModuleBuilder modBuilder; TypeBuilder typeBuilder; Type newType; string typeName = ""; string nestedTypeName = ""; for (int i = 0; i < NumLoops; i++) { modBuilder = CreateModule( TestLibrary.Generator.GetString(true, MinAsmName, MaxAsmName), TestLibrary.Generator.GetString(false, MinModName, MaxModName)); typeName = TestLibrary.Generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls nestedTypeName = TestLibrary.Generator.GetString(true, MinTypName, MaxTypName / 4) + '\0' + TestLibrary.Generator.GetString(true, MinTypName, MaxTypName / 4) + '\0' + TestLibrary.Generator.GetString(true, MinTypName, MaxTypName / 4); typeBuilder = modBuilder.DefineType(typeName); // create nested type typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.Abstract | TypeAttributes.NestedPublic); newType = typeBuilder.CreateTypeInfo().AsType(); Assert.True(newType.Name.Equals(typeName)); } } [Fact] public void TestDefineNestedTypeWithTypeAttributes() { ModuleBuilder modBuilder; TypeBuilder typeBuilder; TypeBuilder nestedType = null; Type newType; string typeName = ""; string nestedTypeName = ""; TypeAttributes typeAttrib = (TypeAttributes)0; int i = 0; modBuilder = CreateModule( TestLibrary.Generator.GetString(true, MinAsmName, MaxAsmName), TestLibrary.Generator.GetString(false, MinModName, MaxModName)); typeName = TestLibrary.Generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls typeBuilder = modBuilder.DefineType(typeName, typeAttrib); for (i = 0; i < _typesPos.Length; i++) { typeAttrib = _typesPos[i]; nestedTypeName = TestLibrary.Generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls // create nested type if (null != nestedType && 0 == (TestLibrary.Generator.GetInt32() % 2)) { nestedType.DefineNestedType(nestedTypeName, _typesPos[i]); } else { nestedType = typeBuilder.DefineNestedType(nestedTypeName, _typesPos[i]); } } newType = typeBuilder.CreateTypeInfo().AsType(); Assert.True(newType.Name.Equals(typeName)); } [Fact] public void TestThrowsExceptionForNullName() { ModuleBuilder modBuilder; TypeBuilder typeBuilder; Type newType; string typeName = ""; string nestedTypeName = ""; modBuilder = CreateModule( TestLibrary.Generator.GetString(true, MinAsmName, MaxAsmName), TestLibrary.Generator.GetString(false, MinModName, MaxModName)); typeName = TestLibrary.Generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls nestedTypeName = null; typeBuilder = modBuilder.DefineType(typeName); Assert.Throws<ArgumentNullException>(() => { // create nested type typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.NestedPublic | TypeAttributes.Class); newType = typeBuilder.CreateTypeInfo().AsType(); }); } [Fact] public void TestThrowsExceptionForEmptyName() { ModuleBuilder modBuilder; TypeBuilder typeBuilder; Type newType; string typeName = ""; string nestedTypeName = ""; modBuilder = CreateModule( TestLibrary.Generator.GetString(true, MinAsmName, MaxAsmName), TestLibrary.Generator.GetString(false, MinModName, MaxModName)); typeName = TestLibrary.Generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls nestedTypeName = string.Empty; typeBuilder = modBuilder.DefineType(typeName); Assert.Throws<ArgumentException>(() => { // create nested type typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.NestedPublic | TypeAttributes.Class); newType = typeBuilder.CreateTypeInfo().AsType(); }); } public ModuleBuilder CreateModule(string assemblyName, string modName) { AssemblyName asmName; AssemblyBuilder asmBuilder; ModuleBuilder modBuilder; // create the dynamic module asmName = new AssemblyName(assemblyName); asmBuilder = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run); modBuilder = TestLibrary.Utilities.GetModuleBuilder(asmBuilder, "Module1"); return modBuilder; } } }
using System; using System.Collections.Generic; using System.Text; using System.Data.Common; using SolarWinds.InformationService.Contract2; using System.Data; using System.ServiceModel; namespace SolarWinds.InformationService.InformationServiceClient { /// <summary> /// Represents a connection to a SolarWinds Information Service /// </summary> public sealed class InformationServiceConnection : DbConnection { private string endpointName; private string remoteAddress; private InfoServiceProxy proxy; private ServiceCredentials credentials; private bool bProxyOwner = true; private IInformationService service; private bool open = false; public InformationServiceConnection() : this(string.Empty) { } public InformationServiceConnection(string endpointName) { if (endpointName == null) throw new ArgumentNullException("endpointName"); Initialize(endpointName, null, null); } //This is required by NCM. NCM provide it's own proxy object public InformationServiceConnection(InfoServiceProxy proxy) : this(proxy, false) { } public InformationServiceConnection(InfoServiceProxy proxy, bool takeOwnership) { this.service = proxy; bProxyOwner = takeOwnership; if (bProxyOwner) { this.proxy = proxy; } } public InformationServiceConnection(IInformationService service) { if (service == null) throw new ArgumentNullException("service"); this.service = service; bProxyOwner = false; } public InformationServiceConnection(string endpointName, string remoteAddress) { if (endpointName == null) throw new ArgumentNullException("endpointName"); if (remoteAddress == null) throw new ArgumentNullException("remoteAddress"); Initialize(endpointName, remoteAddress, null); } public InformationServiceConnection(string endpointName, string remoteAddress, ServiceCredentials credentials) { if (endpointName == null) throw new ArgumentNullException("endpointName"); if (remoteAddress == null) throw new ArgumentNullException("remoteAddress"); if (credentials == null) throw new ArgumentNullException("credentials"); Initialize(endpointName, remoteAddress, credentials); } public InformationServiceConnection(string endpointName, ServiceCredentials credentials) { if (endpointName == null) throw new ArgumentNullException("endpointName"); if (credentials == null) throw new ArgumentNullException("credentials"); Initialize(endpointName, null, credentials); } protected override DbTransaction BeginDbTransaction(System.Data.IsolationLevel isolationLevel) { throw new NotSupportedException(); } public override void ChangeDatabase(string databaseName) { throw new NotSupportedException(); } public override void Close() { if (!bProxyOwner) return; if (proxy != null) { try { this.proxy.Dispose(); } catch (TimeoutException) { this.proxy.Abort(); } catch (CommunicationException) { this.proxy.Abort(); } } this.proxy = null; this.service = null; this.open = false; } protected override void Dispose(bool disposing) { if (disposing) { Close(); } base.Dispose(disposing); } public override string ConnectionString { get { return this.endpointName; } set { Initialize(value, this.remoteAddress, this.credentials); } } public ServiceCredentials Credentials { get { return this.credentials; } set { Initialize(this.endpointName, this.remoteAddress, value); } } public new InformationServiceCommand CreateCommand() { return new InformationServiceCommand(this); } protected override DbCommand CreateDbCommand() { return CreateCommand(); } public override string DataSource { get { return string.Empty; } } public override string Database { get { return string.Empty; } } public override void Open() { if (this.proxy == null && this.service != null) return; // Must be in-process. Nothing to do for Open(). if (this.proxy == null && !this.open) CreateProxy(); if ((this.proxy.Channel != null) && (this.proxy.Channel.State != System.ServiceModel.CommunicationState.Created)) throw new InvalidOperationException("Cannot open an opened or previously closed connection"); this.proxy.Open(); if (this.proxy.Channel.State != System.ServiceModel.CommunicationState.Opened) throw new InvalidOperationException("Could not open the connection"); this.open = true; } public override string ServerVersion { get { return "1.0"; } } public override System.Data.ConnectionState State { get { if ((this.proxy != null) && (this.proxy.Channel != null) && (this.proxy.Channel.State == System.ServiceModel.CommunicationState.Opened)) return ConnectionState.Open; else return ConnectionState.Closed; } } private void Initialize(string endpointName, string remoteAddress, ServiceCredentials credentials) { if ((this.proxy != null) && (this.bProxyOwner != true)) throw new InvalidOperationException("The Proxy Connection is not owned by InformationServiceConnection object"); if ((this.proxy != null) && (this.proxy.Channel.State != CommunicationState.Created)) throw new InvalidOperationException("Cannot change the endpoint for an existing connection"); if (this.proxy != null) Close(); this.endpointName = endpointName; this.remoteAddress = remoteAddress; this.credentials = credentials; CreateProxy(); } private void CreateProxy() { if (endpointName.Length != 0) { if (remoteAddress != null) { if (credentials != null) this.proxy = new InfoServiceProxy(endpointName, remoteAddress, credentials); else this.proxy = new InfoServiceProxy(endpointName, remoteAddress); } else { if (credentials != null) this.proxy = new InfoServiceProxy(endpointName, credentials); else this.proxy = new InfoServiceProxy(endpointName); } this.service = this.proxy; } } internal IInformationService Service { get { return this.service; } } } }
// SPDX-License-Identifier: MIT // Copyright [email protected] // Copyright iced contributors using System; using System.Collections.Generic; using System.Text; using Generator.Constants; namespace Generator.Enums { enum EnumTypeFlags : uint { None = 0, Public = 0x00000001, NoInitialize = 0x00000002, Flags = 0x00000004, } sealed class EnumType { public TypeId TypeId { get; } public string RawName { get; } public string Name(IdentifierConverter idConverter) => idConverter.Type(RawName); public string? Documentation { get; } public EnumValue[] Values => values; EnumValue[] values; readonly bool initialized; readonly Dictionary<string, EnumValue> toEnumValue; internal void ResetValues(EnumValue[] newValues) { foreach (var value in newValues) { if (value.DeclaringType != this) throw new InvalidOperationException(); } Initialize(newValues); } public EnumValue this[string name] { get { if (toEnumValue.TryGetValue(name, out var value)) return value; throw new InvalidOperationException($"Couldn't find enum field {RawName}.{name}"); } } public bool IsPublic { get; } public bool IsFlags { get; } public bool IsMissingDocs { get { if (string.IsNullOrEmpty(Documentation)) return true; foreach (var value in Values) { if (string.IsNullOrEmpty(value.Documentation)) return true; } return false; } } public EnumType(TypeId typeId, string? documentation, EnumValue[] values, EnumTypeFlags flags) : this(typeId.ToString(), typeId, documentation, values, flags) { } public EnumType(string name, TypeId typeId, string? documentation, EnumValue[] values, EnumTypeFlags flags) { toEnumValue = new Dictionary<string, EnumValue>(values.Length, StringComparer.Ordinal); IsPublic = (flags & EnumTypeFlags.Public) != 0; IsFlags = (flags & EnumTypeFlags.Flags) != 0; TypeId = typeId; RawName = name; Documentation = documentation; this.values = values; initialized = (flags & EnumTypeFlags.NoInitialize) == 0; Initialize(values); } void Initialize(EnumValue[] values) { toEnumValue.Clear(); this.values = values; foreach (var value in values) { value.DeclaringType = this; toEnumValue.Add(value.RawName, value); } if (initialized) { if (IsFlags) { uint value = 0; foreach (var enumValue in values) { if (enumValue.DeprecatedInfo.IsDeprecatedAndRenamed) continue; if (enumValue.RawName == "None") enumValue.Value = 0; else { if (value == 0) value = 1; else if (value == 0x80000000) throw new InvalidOperationException("Too many enum values"); else value <<= 1; enumValue.Value = value; } } } else { uint value = 0; for (int i = 0; i < values.Length; i++) { if (values[i].DeprecatedInfo.IsDeprecatedAndRenamed) continue; values[i].Value = value++; } } } foreach (var enumValue in values) { if (!enumValue.DeprecatedInfo.IsDeprecatedAndRenamed) continue; if (enumValue.DeprecatedInfo.NewName is null) throw new InvalidOperationException(); if (!toEnumValue.TryGetValue(enumValue.DeprecatedInfo.NewName, out var newValue)) throw new InvalidOperationException($"Couldn't find enum {enumValue.RawName}"); enumValue.Value = newValue.Value; if (enumValue.Documentation is null) enumValue.Documentation = newValue.Documentation; } } public ConstantsType ToConstantsType(ConstantKind constantKind) { var flags = ConstantsTypeFlags.None; if (IsPublic) flags |= ConstantsTypeFlags.Public; if (IsFlags) flags |= ConstantsTypeFlags.Hex; var constants = new Constant[Values.Length]; for (int i = 0; i < constants.Length; i++) { var value = Values[i]; var constant = new Constant(constantKind, value.RawName, value.Value, flags, value.Documentation, value.DeprecatedInfo); constants[i] = constant; } return new ConstantsType(RawName, TypeId, flags, Documentation, constants); } } interface IEnumValue { EnumType DeclaringType { get; } uint Value { get; } string ToStringValue(IdentifierConverter idConverter); } sealed class OrEnumValue : IEnumValue { public EnumValue[] Values => values; readonly EnumValue[] values; public EnumType DeclaringType { get; } public uint Value { get; } public string ToStringValue(IdentifierConverter idConverter) { var sb = new StringBuilder(); foreach (var value in values) { if (sb.Length > 0) sb.Append(", "); sb.Append(value.Name(idConverter)); } return sb.ToString(); } public OrEnumValue(EnumType enumType, params string[] values) { DeclaringType = enumType; var newValues = new EnumValue[values.Length]; for (int i = 0; i < values.Length; i++) { var value = values[i]; var enumValue = enumType[value]; newValues[i] = enumValue; Value |= enumValue.Value; } this.values = newValues; } public OrEnumValue(EnumType enumType, params EnumValue[] values) { DeclaringType = enumType; for (int i = 0; i < values.Length; i++) { var value = values[i]; if (value.DeclaringType != enumType) throw new ArgumentException(); Value |= value.Value; } this.values = values; } // Need to override this since the decoder/formatter table generators call Equals() public override bool Equals(object? obj) { if (obj is not OrEnumValue other) return false; if (DeclaringType != other.DeclaringType) return false; return Value == other.Value; } public override int GetHashCode() => DeclaringType.GetHashCode() ^ (int)Value; } sealed class EnumValue : IEnumValue { public EnumType DeclaringType { get; set; } public uint Value { get; set; } public string RawName { get; } public string Name(IdentifierConverter idConverter) => idConverter.EnumField(RawName); public string ToStringValue(IdentifierConverter idConverter) => idConverter.EnumField(RawName); public string? Documentation { get; internal set; } public DeprecatedInfo DeprecatedInfo { get; } public EnumValue(uint value, string name, string? documentation) : this(value, name, documentation, default) { } public EnumValue(uint value, string name, string? documentation, DeprecatedInfo deprecatedInfo) { DeclaringType = null!; Value = value; RawName = name; if (deprecatedInfo.IsDeprecated && deprecatedInfo.NewName is null && documentation is null) Documentation = "Don't use it!"; else Documentation = documentation; DeprecatedInfo = deprecatedInfo; } } }
using Lucene.Net.Support; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using CodecUtil = Lucene.Net.Codecs.CodecUtil; using Directory = Lucene.Net.Store.Directory; using IndexInput = Lucene.Net.Store.IndexInput; using IndexOutput = Lucene.Net.Store.IndexOutput; using IOContext = Lucene.Net.Store.IOContext; using IOUtils = Lucene.Net.Util.IOUtils; /// <summary> /// A <see cref="SnapshotDeletionPolicy"/> which adds a persistence layer so that /// snapshots can be maintained across the life of an application. The snapshots /// are persisted in a <see cref="Directory"/> and are committed as soon as /// <see cref="Snapshot()"/> or <see cref="Release(IndexCommit)"/> is called. /// <para/> /// <b>NOTE:</b> Sharing <see cref="PersistentSnapshotDeletionPolicy"/>s that write to /// the same directory across <see cref="IndexWriter"/>s will corrupt snapshots. You /// should make sure every <see cref="IndexWriter"/> has its own /// <see cref="PersistentSnapshotDeletionPolicy"/> and that they all write to a /// different <see cref="Directory"/>. It is OK to use the same /// <see cref="Directory"/> that holds the index. /// /// <para/> This class adds a <see cref="Release(long)"/> method to /// release commits from a previous snapshot's <see cref="IndexCommit.Generation"/>. /// <para/> /// @lucene.experimental /// </summary> public class PersistentSnapshotDeletionPolicy : SnapshotDeletionPolicy { /// <summary> /// Prefix used for the save file. </summary> public static readonly string SNAPSHOTS_PREFIX = "snapshots_"; private static readonly int VERSION_START = 0; private static readonly int VERSION_CURRENT = VERSION_START; private static readonly string CODEC_NAME = "snapshots"; // The index writer which maintains the snapshots metadata private long nextWriteGen; private readonly Directory dir; /// <summary> /// <see cref="PersistentSnapshotDeletionPolicy"/> wraps another /// <see cref="IndexDeletionPolicy"/> to enable flexible /// snapshotting, passing <see cref="OpenMode.CREATE_OR_APPEND"/> /// by default. /// </summary> /// <param name="primary"> /// the <see cref="IndexDeletionPolicy"/> that is used on non-snapshotted /// commits. Snapshotted commits, by definition, are not deleted until /// explicitly released via <see cref="Release(IndexCommit)"/>. </param> /// <param name="dir"> /// the <see cref="Directory"/> which will be used to persist the snapshots /// information. </param> public PersistentSnapshotDeletionPolicy(IndexDeletionPolicy primary, Directory dir) : this(primary, dir, OpenMode.CREATE_OR_APPEND) { } /// <summary> /// <see cref="PersistentSnapshotDeletionPolicy"/> wraps another /// <see cref="IndexDeletionPolicy"/> to enable flexible snapshotting. /// </summary> /// <param name="primary"> /// the <see cref="IndexDeletionPolicy"/> that is used on non-snapshotted /// commits. Snapshotted commits, by definition, are not deleted until /// explicitly released via <see cref="Release(IndexCommit)"/>. </param> /// <param name="dir"> /// the <see cref="Directory"/> which will be used to persist the snapshots /// information. </param> /// <param name="mode"> /// specifies whether a new index should be created, deleting all /// existing snapshots information (immediately), or open an existing /// index, initializing the class with the snapshots information. </param> public PersistentSnapshotDeletionPolicy(IndexDeletionPolicy primary, Directory dir, OpenMode mode) : base(primary) { this.dir = dir; if (mode == OpenMode.CREATE) { ClearPriorSnapshots(); } LoadPriorSnapshots(); if (mode == OpenMode.APPEND && nextWriteGen == 0) { throw new InvalidOperationException("no snapshots stored in this directory"); } } /// <summary> /// Snapshots the last commit. Once this method returns, the /// snapshot information is persisted in the directory. /// </summary> /// <seealso cref="SnapshotDeletionPolicy.Snapshot()"/> public override IndexCommit Snapshot() { lock (this) { IndexCommit ic = base.Snapshot(); bool success = false; try { Persist(); success = true; } finally { if (!success) { try { base.Release(ic); } #pragma warning disable 168 catch (Exception e) #pragma warning restore 168 { // Suppress so we keep throwing original exception } } } return ic; } } /// <summary> /// Deletes a snapshotted commit. Once this method returns, the snapshot /// information is persisted in the directory. /// </summary> /// <seealso cref="SnapshotDeletionPolicy.Release(IndexCommit)"/> public override void Release(IndexCommit commit) { lock (this) { base.Release(commit); bool success = false; try { Persist(); success = true; } finally { if (!success) { try { IncRef(commit); } #pragma warning disable 168 catch (Exception e) #pragma warning restore 168 { // Suppress so we keep throwing original exception } } } } } /// <summary> /// Deletes a snapshotted commit by generation. Once this method returns, the snapshot /// information is persisted in the directory. /// </summary> /// <seealso cref="IndexCommit.Generation"/> /// <seealso cref="SnapshotDeletionPolicy.Release(IndexCommit)"/> public virtual void Release(long gen) { lock (this) { base.ReleaseGen(gen); Persist(); } } [MethodImpl(MethodImplOptions.NoInlining)] internal void Persist() { lock (this) { string fileName = SNAPSHOTS_PREFIX + nextWriteGen; IndexOutput @out = dir.CreateOutput(fileName, IOContext.DEFAULT); bool success = false; try { CodecUtil.WriteHeader(@out, CODEC_NAME, VERSION_CURRENT); @out.WriteVInt32(m_refCounts.Count); foreach (KeyValuePair<long, int> ent in m_refCounts) { @out.WriteVInt64(ent.Key); @out.WriteVInt32(ent.Value); } success = true; } finally { if (!success) { IOUtils.DisposeWhileHandlingException(@out); try { dir.DeleteFile(fileName); } #pragma warning disable 168 catch (Exception e) #pragma warning restore 168 { // Suppress so we keep throwing original exception } } else { IOUtils.Dispose(@out); } } dir.Sync(/*Collections.singletonList(*/new[] { fileName }/*)*/); if (nextWriteGen > 0) { string lastSaveFile = SNAPSHOTS_PREFIX + (nextWriteGen - 1); try { dir.DeleteFile(lastSaveFile); } #pragma warning disable 168 catch (IOException ioe) #pragma warning restore 168 { // OK: likely it didn't exist } } nextWriteGen++; } } private void ClearPriorSnapshots() { lock (this) { foreach (string file in dir.ListAll()) { if (file.StartsWith(SNAPSHOTS_PREFIX, StringComparison.Ordinal)) { dir.DeleteFile(file); } } } } /// <summary> /// Returns the file name the snapshots are currently /// saved to, or <c>null</c> if no snapshots have been saved. /// </summary> public virtual string LastSaveFile { get { if (nextWriteGen == 0) { return null; } else { return SNAPSHOTS_PREFIX + (nextWriteGen - 1); } } } /// <summary> /// Reads the snapshots information from the given <see cref="Directory"/>. This /// method can be used if the snapshots information is needed, however you /// cannot instantiate the deletion policy (because e.g., some other process /// keeps a lock on the snapshots directory). /// </summary> private void LoadPriorSnapshots() { lock (this) { long genLoaded = -1; IOException ioe = null; IList<string> snapshotFiles = new List<string>(); foreach (string file in dir.ListAll()) { if (file.StartsWith(SNAPSHOTS_PREFIX, StringComparison.Ordinal)) { long gen = Convert.ToInt64(file.Substring(SNAPSHOTS_PREFIX.Length), CultureInfo.InvariantCulture); if (genLoaded == -1 || gen > genLoaded) { snapshotFiles.Add(file); IDictionary<long, int> m = new Dictionary<long, int>(); IndexInput @in = dir.OpenInput(file, IOContext.DEFAULT); try { CodecUtil.CheckHeader(@in, CODEC_NAME, VERSION_START, VERSION_START); int count = @in.ReadVInt32(); for (int i = 0; i < count; i++) { long commitGen = @in.ReadVInt64(); int refCount = @in.ReadVInt32(); m[commitGen] = refCount; } } catch (IOException ioe2) { // Save first exception & throw in the end if (ioe == null) { ioe = ioe2; } } finally { @in.Dispose(); } genLoaded = gen; m_refCounts.Clear(); m_refCounts.PutAll(m); } } } if (genLoaded == -1) { // Nothing was loaded... if (ioe != null) { // ... not for lack of trying: throw ioe; } } else { if (snapshotFiles.Count > 1) { // Remove any broken / old snapshot files: string curFileName = SNAPSHOTS_PREFIX + genLoaded; foreach (string file in snapshotFiles) { if (!curFileName.Equals(file, StringComparison.Ordinal)) { dir.DeleteFile(file); } } } nextWriteGen = 1 + genLoaded; } } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using NUnit.Framework; using SimpleAnalyzer = Lucene.Net.Analysis.SimpleAnalyzer; using Document = Lucene.Net.Documents.Document; using Field = Lucene.Net.Documents.Field; using CorruptIndexException = Lucene.Net.Index.CorruptIndexException; using IndexReader = Lucene.Net.Index.IndexReader; using IndexWriter = Lucene.Net.Index.IndexWriter; using Term = Lucene.Net.Index.Term; using ParseException = Lucene.Net.QueryParsers.ParseException; using LockObtainFailedException = Lucene.Net.Store.LockObtainFailedException; using RAMDirectory = Lucene.Net.Store.RAMDirectory; using DocIdBitSet = Lucene.Net.Util.DocIdBitSet; using Occur = Lucene.Net.Search.BooleanClause.Occur; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; namespace Lucene.Net.Search { /// <summary> Unit tests for sorting code. /// /// <p/>Created: Feb 17, 2004 4:55:10 PM /// /// </summary> /// <since> lucene 1.4 /// </since> /// <version> $Id: TestSort.java 803676 2009-08-12 19:31:38Z hossman $ /// </version> [Serializable] [TestFixture] public class TestSort:LuceneTestCase { [Serializable] private class AnonymousClassIntParser : Lucene.Net.Search.IntParser { public AnonymousClassIntParser(TestSort enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(TestSort enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestSort enclosingInstance; public TestSort Enclosing_Instance { get { return enclosingInstance; } } public int ParseInt(System.String val) { return (val[0] - 'A') * 123456; } } [Serializable] private class AnonymousClassFloatParser : Lucene.Net.Search.FloatParser { public AnonymousClassFloatParser(TestSort enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(TestSort enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestSort enclosingInstance; public TestSort Enclosing_Instance { get { return enclosingInstance; } } public float ParseFloat(System.String val) { return (float) System.Math.Sqrt(val[0]); } } [Serializable] private class AnonymousClassLongParser : Lucene.Net.Search.LongParser { public AnonymousClassLongParser(TestSort enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(TestSort enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestSort enclosingInstance; public TestSort Enclosing_Instance { get { return enclosingInstance; } } public long ParseLong(System.String val) { return (val[0] - 'A') * 1234567890L; } } [Serializable] private class AnonymousClassDoubleParser : Lucene.Net.Search.DoubleParser { public AnonymousClassDoubleParser(TestSort enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(TestSort enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestSort enclosingInstance; public TestSort Enclosing_Instance { get { return enclosingInstance; } } public double ParseDouble(System.String val) { return System.Math.Pow(val[0], (val[0] - 'A')); } } [Serializable] private class AnonymousClassByteParser : Lucene.Net.Search.ByteParser { public AnonymousClassByteParser(TestSort enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(TestSort enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestSort enclosingInstance; public TestSort Enclosing_Instance { get { return enclosingInstance; } } public sbyte ParseByte(System.String val) { return (sbyte) (val[0] - 'A'); } } [Serializable] private class AnonymousClassShortParser : Lucene.Net.Search.ShortParser { public AnonymousClassShortParser(TestSort enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(TestSort enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestSort enclosingInstance; public TestSort Enclosing_Instance { get { return enclosingInstance; } } public short ParseShort(System.String val) { return (short) (val[0] - 'A'); } } [Serializable] private class AnonymousClassFilter:Filter { public AnonymousClassFilter(Lucene.Net.Search.TopDocs docs1, TestSort enclosingInstance) { InitBlock(docs1, enclosingInstance); } private void InitBlock(Lucene.Net.Search.TopDocs docs1, TestSort enclosingInstance) { this.docs1 = docs1; this.enclosingInstance = enclosingInstance; } private Lucene.Net.Search.TopDocs docs1; private TestSort enclosingInstance; public TestSort Enclosing_Instance { get { return enclosingInstance; } } public override DocIdSet GetDocIdSet(IndexReader reader) { System.Collections.BitArray bs = new System.Collections.BitArray((reader.MaxDoc() % 64 == 0?reader.MaxDoc() / 64:reader.MaxDoc() / 64 + 1) * 64); for (int i = 0; i < reader.MaxDoc(); i++) bs.Set(i, true); bs.Set(docs1.ScoreDocs[0].doc, true); return new DocIdBitSet(bs); } } private const int NUM_STRINGS = 6000; private Searcher full; private Searcher searchX; private Searcher searchY; private Query queryX; private Query queryY; private Query queryA; private Query queryE; private Query queryF; private Query queryG; private Sort sort; /*public TestSort(System.String name):base(name) { }*/ /*public static Test Suite() { return new TestSuite(typeof(TestSort)); }*/ // document data: // the tracer field is used to determine which document was hit // the contents field is used to search and sort by relevance // the int field to sort by int // the float field to sort by float // the string field to sort by string // the i18n field includes accented characters for testing locale-specific sorting private System.String[][] data = new System.String[][] { // tracer contents int float string custom i18n long double, 'short', byte, 'custom parser encoding' new string[]{ "A", "x a", "5", "4f", "c", "A-3", "p\u00EAche", "10", "-4.0", "3", "126", "J"},//A, x //{{See: LUCENENET-364}} Intentional diversion from Java (3.4028235E38 changed to 3.402823E38) new string[]{ "B", "y a", "5", "3.402823E38", "i", "B-10", "HAT", "1000000000", "40.0", "24", "1", "I"},//B, y //new string[]{ "B", "y a", "5", "3.4028235E38", "i", "B-10", "HAT", "1000000000", "40.0", "24", "1", "I"},//B, y new string[]{ "C", "x a b c", "2147483647", "1.0", "j", "A-2", "p\u00E9ch\u00E9", "99999999", "40.00002343", "125", "15", "H"},//C, x new string[]{ "D", "y a b c", "-1", "0.0f", "a", "C-0", "HUT", long.MaxValue.ToString(), double.MinValue.ToString("E16"), short.MinValue.ToString(), sbyte.MinValue.ToString(), "G"},//D, y new string[]{ "E", "x a b c d", "5", "2f", "h", "B-8", "peach", long.MinValue.ToString(), double.MaxValue.ToString("E16"), short.MaxValue.ToString(), sbyte.MaxValue.ToString(), "F"},//E,x new string[]{ "F", "y a b c d", "2", "3.14159f", "g", "B-1", "H\u00C5T", "-44", "343.034435444", "-3", "0", "E"},//F,y new string[]{ "G", "x a b c d", "3", "-1.0", "f", "C-100", "sin", "323254543543", "4.043544", "5", "100", "D"},//G,x new string[]{ "H", "y a b c d", "0", "1.4E-45", "e", "C-88", "H\u00D8T", "1023423423005", "4.043545", "10", "-50", "C"},//H,y new string[]{ "I", "x a b c d e f", "-2147483648", "1.0e+0", "d", "A-10", "s\u00EDn", "332422459999", "4.043546", "-340", "51", "B"},//I,x new string[]{ "J", "y a b c d e f", "4", ".5", "b", "C-7", "HOT", "34334543543", "4.0000220343", "300", "2", "A"},//J,y new string[]{ "W", "g", "1", null, null, null, null, null, null, null, null, null}, new string[]{ "X", "g", "1", "0.1", null, null, null, null, null, null, null, null}, new string[]{ "Y", "g", "1", "0.2", null, null, null, null, null, null, null, null}, new string[]{ "Z", "f g", null, null, null, null, null, null, null, null, null, null} }; // create an index of all the documents, or just the x, or just the y documents private Searcher GetIndex(bool even, bool odd) { RAMDirectory indexStore = new RAMDirectory(); IndexWriter writer = new IndexWriter(indexStore, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); writer.SetMaxBufferedDocs(2); writer.SetMergeFactor(1000); for (int i = 0; i < data.Length; ++i) { if (((i % 2) == 0 && even) || ((i % 2) == 1 && odd)) { Document doc = new Document(); doc.Add(new Field("tracer", data[i][0], Field.Store.YES, Field.Index.NO)); doc.Add(new Field("contents", data[i][1], Field.Store.NO, Field.Index.ANALYZED)); if (data[i][2] != null) doc.Add(new Field("int", data[i][2], Field.Store.NO, Field.Index.NOT_ANALYZED)); if (data[i][3] != null) doc.Add(new Field("float", data[i][3], Field.Store.NO, Field.Index.NOT_ANALYZED)); if (data[i][4] != null) doc.Add(new Field("string", data[i][4], Field.Store.NO, Field.Index.NOT_ANALYZED)); if (data[i][5] != null) doc.Add(new Field("custom", data[i][5], Field.Store.NO, Field.Index.NOT_ANALYZED)); if (data[i][6] != null) doc.Add(new Field("i18n", data[i][6], Field.Store.NO, Field.Index.NOT_ANALYZED)); if (data[i][7] != null) doc.Add(new Field("long", data[i][7], Field.Store.NO, Field.Index.NOT_ANALYZED)); if (data[i][8] != null) doc.Add(new Field("double", data[i][8], Field.Store.NO, Field.Index.NOT_ANALYZED)); if (data[i][9] != null) doc.Add(new Field("short", data[i][9], Field.Store.NO, Field.Index.NOT_ANALYZED)); if (data[i][10] != null) doc.Add(new Field("byte", data[i][10], Field.Store.NO, Field.Index.NOT_ANALYZED)); if (data[i][11] != null) doc.Add(new Field("parser", data[i][11], Field.Store.NO, Field.Index.NOT_ANALYZED)); doc.SetBoost(2); // produce some scores above 1.0 writer.AddDocument(doc); } } //writer.optimize (); writer.Close(); IndexSearcher s = new IndexSearcher(indexStore); s.SetDefaultFieldSortScoring(true, true); return s; } private Searcher GetFullIndex() { return GetIndex(true, true); } private IndexSearcher GetFullStrings() { RAMDirectory indexStore = new RAMDirectory(); IndexWriter writer = new IndexWriter(indexStore, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); writer.SetMaxBufferedDocs(4); writer.SetMergeFactor(97); for (int i = 0; i < NUM_STRINGS; i++) { Document doc = new Document(); System.String num = GetRandomCharString(GetRandomNumber(2, 8), 48, 52); doc.Add(new Field("tracer", num, Field.Store.YES, Field.Index.NO)); //doc.add (new Field ("contents", Integer.toString(i), Field.Store.NO, Field.Index.ANALYZED)); doc.Add(new Field("string", num, Field.Store.NO, Field.Index.NOT_ANALYZED)); System.String num2 = GetRandomCharString(GetRandomNumber(1, 4), 48, 50); doc.Add(new Field("string2", num2, Field.Store.NO, Field.Index.NOT_ANALYZED)); doc.Add(new Field("tracer2", num2, Field.Store.YES, Field.Index.NO)); doc.SetBoost(2); // produce some scores above 1.0 writer.SetMaxBufferedDocs(GetRandomNumber(2, 12)); writer.AddDocument(doc); } //writer.optimize (); //System.out.println(writer.getSegmentCount()); writer.Close(); return new IndexSearcher(indexStore); } public virtual System.String GetRandomNumberString(int num, int low, int high) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < num; i++) { sb.Append(GetRandomNumber(low, high)); } return sb.ToString(); } public virtual System.String GetRandomCharString(int num) { return GetRandomCharString(num, 48, 122); } public virtual System.String GetRandomCharString(int num, int start, int end) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < num; i++) { sb.Append((char) GetRandomNumber(start, end)); } return sb.ToString(); } internal System.Random r; public virtual int GetRandomNumber(int low, int high) { int randInt = (System.Math.Abs(r.Next()) % (high - low)) + low; return randInt; } private Searcher GetXIndex() { return GetIndex(true, false); } private Searcher GetYIndex() { return GetIndex(false, true); } private Searcher GetEmptyIndex() { return GetIndex(false, false); } [SetUp] public override void SetUp() { base.SetUp(); full = GetFullIndex(); searchX = GetXIndex(); searchY = GetYIndex(); queryX = new TermQuery(new Term("contents", "x")); queryY = new TermQuery(new Term("contents", "y")); queryA = new TermQuery(new Term("contents", "a")); queryE = new TermQuery(new Term("contents", "e")); queryF = new TermQuery(new Term("contents", "f")); queryG = new TermQuery(new Term("contents", "g")); sort = new Sort(); } // test the sorts by score and document number [Test] public virtual void TestBuiltInSorts() { sort = new Sort(); AssertMatches(full, queryX, sort, "ACEGI"); AssertMatches(full, queryY, sort, "BDFHJ"); sort.SetSort(SortField.FIELD_DOC); AssertMatches(full, queryX, sort, "ACEGI"); AssertMatches(full, queryY, sort, "BDFHJ"); } // test sorts where the type of field is specified [Test] public virtual void TestTypedSort() { sort.SetSort(new SortField[] { new SortField("int", SortField.INT), SortField.FIELD_DOC }); AssertMatches(full, queryX, sort, "IGAEC"); AssertMatches(full, queryY, sort, "DHFJB"); sort.SetSort(new SortField[] { new SortField("float", SortField.FLOAT), SortField.FIELD_DOC }); AssertMatches(full, queryX, sort, "GCIEA"); AssertMatches(full, queryY, sort, "DHJFB"); sort.SetSort(new SortField[] { new SortField("long", SortField.LONG), SortField.FIELD_DOC }); AssertMatches(full, queryX, sort, "EACGI"); AssertMatches(full, queryY, sort, "FBJHD"); sort.SetSort(new SortField[] { new SortField("double", SortField.DOUBLE), SortField.FIELD_DOC }); AssertMatches(full, queryX, sort, "AGICE"); AssertMatches(full, queryY, sort, "DJHBF"); sort.SetSort(new SortField[]{new SortField("byte", SortField.BYTE), SortField.FIELD_DOC}); AssertMatches(full, queryX, sort, "CIGAE"); AssertMatches(full, queryY, sort, "DHFBJ"); sort.SetSort(new SortField[]{new SortField("short", SortField.SHORT), SortField.FIELD_DOC}); AssertMatches(full, queryX, sort, "IAGCE"); AssertMatches(full, queryY, sort, "DFHBJ"); sort.SetSort(new SortField[]{new SortField("string", SortField.STRING), SortField.FIELD_DOC}); AssertMatches(full, queryX, sort, "AIGEC"); AssertMatches(full, queryY, sort, "DJHFB"); } /// <summary> Test String sorting: small queue to many matches, multi field sort, reverse sort</summary> [Test] public virtual void TestStringSort() { r = NewRandom(); ScoreDoc[] result = null; IndexSearcher searcher = GetFullStrings(); sort.SetSort(new SortField[]{new SortField("string", SortField.STRING), new SortField("string2", SortField.STRING, true), SortField.FIELD_DOC}); result = searcher.Search(new MatchAllDocsQuery(), null, 500, sort).ScoreDocs; System.Text.StringBuilder buff = new System.Text.StringBuilder(); int n = result.Length; System.String last = null; System.String lastSub = null; int lastDocId = 0; bool fail = false; for (int x = 0; x < n; ++x) { Document doc2 = searcher.Doc(result[x].doc); System.String[] v = doc2.GetValues("tracer"); System.String[] v2 = doc2.GetValues("tracer2"); for (int j = 0; j < v.Length; ++j) { if (last != null) { int cmp = String.CompareOrdinal(v[j], last); if (!(cmp >= 0)) { // ensure first field is in order fail = true; System.Console.Out.WriteLine("fail:" + v[j] + " < " + last); } if (cmp == 0) { // ensure second field is in reverse order cmp = String.CompareOrdinal(v2[j], lastSub); if (cmp > 0) { fail = true; System.Console.Out.WriteLine("rev field fail:" + v2[j] + " > " + lastSub); } else if (cmp == 0) { // ensure docid is in order if (result[x].doc < lastDocId) { fail = true; System.Console.Out.WriteLine("doc fail:" + result[x].doc + " > " + lastDocId); } } } } last = v[j]; lastSub = v2[j]; lastDocId = result[x].doc; buff.Append(v[j] + "(" + v2[j] + ")(" + result[x].doc + ") "); } } if (fail) { System.Console.Out.WriteLine("topn field1(field2)(docID):" + buff); } Assert.IsFalse(fail, "Found sort results out of order"); } /// <summary> test sorts where the type of field is specified and a custom field parser /// is used, that uses a simple char encoding. The sorted string contains a /// character beginning from 'A' that is mapped to a numeric value using some /// "funny" algorithm to be different for each data type. /// </summary> [Test] public virtual void TestCustomFieldParserSort() { // since tests explicilty uses different parsers on the same fieldname // we explicitly check/purge the FieldCache between each assertMatch FieldCache fc = Lucene.Net.Search.FieldCache_Fields.DEFAULT; sort.SetSort(new SortField[]{new SortField("parser", new AnonymousClassIntParser(this)), SortField.FIELD_DOC}); AssertMatches(full, queryA, sort, "JIHGFEDCBA"); AssertSaneFieldCaches(Lucene.Net.TestCase.GetName() + " IntParser"); fc.PurgeAllCaches(); sort.SetSort(new SortField[]{new SortField("parser", new AnonymousClassFloatParser(this)), SortField.FIELD_DOC}); AssertMatches(full, queryA, sort, "JIHGFEDCBA"); AssertSaneFieldCaches(Lucene.Net.TestCase.GetName() + " FloatParser"); fc.PurgeAllCaches(); sort.SetSort(new SortField[]{new SortField("parser", new AnonymousClassLongParser(this)), SortField.FIELD_DOC}); AssertMatches(full, queryA, sort, "JIHGFEDCBA"); AssertSaneFieldCaches(Lucene.Net.TestCase.GetName() + " LongParser"); fc.PurgeAllCaches(); sort.SetSort(new SortField[]{new SortField("parser", new AnonymousClassDoubleParser(this)), SortField.FIELD_DOC}); AssertMatches(full, queryA, sort, "JIHGFEDCBA"); AssertSaneFieldCaches(Lucene.Net.TestCase.GetName() + " DoubleParser"); fc.PurgeAllCaches(); sort.SetSort(new SortField[]{new SortField("parser", new AnonymousClassByteParser(this)), SortField.FIELD_DOC}); AssertMatches(full, queryA, sort, "JIHGFEDCBA"); AssertSaneFieldCaches(Lucene.Net.TestCase.GetName() + " ByteParser"); fc.PurgeAllCaches(); sort.SetSort(new SortField[]{new SortField("parser", new AnonymousClassShortParser(this)), SortField.FIELD_DOC}); AssertMatches(full, queryA, sort, "JIHGFEDCBA"); AssertSaneFieldCaches(Lucene.Net.TestCase.GetName() + " ShortParser"); fc.PurgeAllCaches(); } // test sorts when there's nothing in the index [Test] public virtual void TestEmptyIndex() { Searcher empty = GetEmptyIndex(); sort = new Sort(); AssertMatches(empty, queryX, sort, ""); sort.SetSort(SortField.FIELD_DOC); AssertMatches(empty, queryX, sort, ""); sort.SetSort(new SortField[]{new SortField("int", SortField.INT), SortField.FIELD_DOC}); AssertMatches(empty, queryX, sort, ""); sort.SetSort(new SortField[]{new SortField("string", SortField.STRING, true), SortField.FIELD_DOC}); AssertMatches(empty, queryX, sort, ""); sort.SetSort(new SortField[]{new SortField("float", SortField.FLOAT), new SortField("string", SortField.STRING)}); AssertMatches(empty, queryX, sort, ""); } internal class MyFieldComparator:FieldComparator { [Serializable] private class AnonymousClassIntParser1 : Lucene.Net.Search.IntParser { public AnonymousClassIntParser1(MyFieldComparator enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(MyFieldComparator enclosingInstance) { this.enclosingInstance = enclosingInstance; } private MyFieldComparator enclosingInstance; public MyFieldComparator Enclosing_Instance { get { return enclosingInstance; } } public int ParseInt(System.String val) { return (val[0] - 'A') * 123456; } } internal int[] docValues; internal int[] slotValues; internal int bottomValue; internal MyFieldComparator(int numHits) { slotValues = new int[numHits]; } public override void Copy(int slot, int doc) { slotValues[slot] = docValues[doc]; } public override int Compare(int slot1, int slot2) { return slotValues[slot1] - slotValues[slot2]; } public override int CompareBottom(int doc) { return bottomValue - docValues[doc]; } public override void SetBottom(int bottom) { bottomValue = slotValues[bottom]; } public override void SetNextReader(IndexReader reader, int docBase) { docValues = Lucene.Net.Search.FieldCache_Fields.DEFAULT.GetInts(reader, "parser", new AnonymousClassIntParser1(this)); } public override System.IComparable Value(int slot) { return (System.Int32) slotValues[slot]; } } [Serializable] internal class MyFieldComparatorSource:FieldComparatorSource { public override FieldComparator NewComparator(System.String fieldname, int numHits, int sortPos, bool reversed) { return new MyFieldComparator(numHits); } } // Test sorting w/ custom FieldComparator [Test] public virtual void TestNewCustomFieldParserSort() { sort.SetSort(new SortField[]{new SortField("parser", new MyFieldComparatorSource())}); AssertMatches(full, queryA, sort, "JIHGFEDCBA"); } // test sorts where the type of field is determined dynamically [Test] public virtual void TestAutoSort() { sort.SetSort("int"); AssertMatches(full, queryX, sort, "IGAEC"); AssertMatches(full, queryY, sort, "DHFJB"); sort.SetSort("float"); AssertMatches(full, queryX, sort, "GCIEA"); AssertMatches(full, queryY, sort, "DHJFB"); sort.SetSort("string"); AssertMatches(full, queryX, sort, "AIGEC"); AssertMatches(full, queryY, sort, "DJHFB"); } // test sorts in reverse [Test] public virtual void TestReverseSort() { sort.SetSort(new SortField[]{new SortField(null, SortField.SCORE, true), SortField.FIELD_DOC}); AssertMatches(full, queryX, sort, "IEGCA"); AssertMatches(full, queryY, sort, "JFHDB"); sort.SetSort(new SortField(null, SortField.DOC, true)); AssertMatches(full, queryX, sort, "IGECA"); AssertMatches(full, queryY, sort, "JHFDB"); sort.SetSort("int", true); AssertMatches(full, queryX, sort, "CAEGI"); AssertMatches(full, queryY, sort, "BJFHD"); sort.SetSort("float", true); AssertMatches(full, queryX, sort, "AECIG"); AssertMatches(full, queryY, sort, "BFJHD"); sort.SetSort("string", true); AssertMatches(full, queryX, sort, "CEGIA"); AssertMatches(full, queryY, sort, "BFHJD"); } // test sorting when the sort field is empty (undefined) for some of the documents [Test] public virtual void TestEmptyFieldSort() { sort.SetSort("string"); AssertMatches(full, queryF, sort, "ZJI"); sort.SetSort("string", true); AssertMatches(full, queryF, sort, "IJZ"); sort.SetSort(new SortField("i18n", new System.Globalization.CultureInfo("en"))); AssertMatches(full, queryF, sort, "ZJI"); sort.SetSort(new SortField("i18n", new System.Globalization.CultureInfo("en"), true)); AssertMatches(full, queryF, sort, "IJZ"); sort.SetSort("int"); AssertMatches(full, queryF, sort, "IZJ"); sort.SetSort("int", true); AssertMatches(full, queryF, sort, "JZI"); sort.SetSort("float"); AssertMatches(full, queryF, sort, "ZJI"); // using a nonexisting field as first sort key shouldn't make a difference: sort.SetSort(new SortField[]{new SortField("nosuchfield", SortField.STRING), new SortField("float")}); AssertMatches(full, queryF, sort, "ZJI"); sort.SetSort("float", true); AssertMatches(full, queryF, sort, "IJZ"); // When a field is null for both documents, the next SortField should be used. // Works for sort.SetSort(new SortField[]{new SortField("int"), new SortField("string", SortField.STRING), new SortField("float")}); AssertMatches(full, queryG, sort, "ZWXY"); // Reverse the last criterium to make sure the test didn't pass by chance sort.SetSort(new SortField[]{new SortField("int"), new SortField("string", SortField.STRING), new SortField("float", true)}); AssertMatches(full, queryG, sort, "ZYXW"); // Do the same for a MultiSearcher Searcher multiSearcher = new MultiSearcher(new Searchable[]{full}); sort.SetSort(new SortField[]{new SortField("int"), new SortField("string", SortField.STRING), new SortField("float")}); AssertMatches(multiSearcher, queryG, sort, "ZWXY"); sort.SetSort(new SortField[]{new SortField("int"), new SortField("string", SortField.STRING), new SortField("float", true)}); AssertMatches(multiSearcher, queryG, sort, "ZYXW"); // Don't close the multiSearcher. it would close the full searcher too! // Do the same for a ParallelMultiSearcher Searcher parallelSearcher = new ParallelMultiSearcher(new Searchable[]{full}); sort.SetSort(new SortField[]{new SortField("int"), new SortField("string", SortField.STRING), new SortField("float")}); AssertMatches(parallelSearcher, queryG, sort, "ZWXY"); sort.SetSort(new SortField[]{new SortField("int"), new SortField("string", SortField.STRING), new SortField("float", true)}); AssertMatches(parallelSearcher, queryG, sort, "ZYXW"); // Don't close the parallelSearcher. it would close the full searcher too! } // test sorts using a series of fields [Test] public virtual void TestSortCombos() { sort.SetSort(new System.String[]{"int", "float"}); AssertMatches(full, queryX, sort, "IGEAC"); sort.SetSort(new SortField[]{new SortField("int", true), new SortField(null, SortField.DOC, true)}); AssertMatches(full, queryX, sort, "CEAGI"); sort.SetSort(new System.String[]{"float", "string"}); AssertMatches(full, queryX, sort, "GICEA"); } // test using a Locale for sorting strings [Test] public virtual void TestLocaleSort() { sort.SetSort(new SortField[]{new SortField("string", new System.Globalization.CultureInfo("en-US"))}); AssertMatches(full, queryX, sort, "AIGEC"); AssertMatches(full, queryY, sort, "DJHFB"); sort.SetSort(new SortField[]{new SortField("string", new System.Globalization.CultureInfo("en-US"), true)}); AssertMatches(full, queryX, sort, "CEGIA"); AssertMatches(full, queryY, sort, "BFHJD"); } // test using various international locales with accented characters // (which sort differently depending on locale) [Test] public virtual void TestInternationalSort() { sort.SetSort(new SortField("i18n", new System.Globalization.CultureInfo("en-US"))); AssertMatches(full, queryY, sort, "BFJHD"); sort.SetSort(new SortField("i18n", new System.Globalization.CultureInfo("sv-se"))); AssertMatches(full, queryY, sort, "BJDFH"); sort.SetSort(new SortField("i18n", new System.Globalization.CultureInfo("da-dk"))); AssertMatches(full, queryY, sort, "BJDHF"); sort.SetSort(new SortField("i18n", new System.Globalization.CultureInfo("en-US"))); AssertMatches(full, queryX, sort, "ECAGI"); sort.SetSort(new SortField("i18n", new System.Globalization.CultureInfo("fr-FR"))); AssertMatches(full, queryX, sort, "EACGI"); } // Test the MultiSearcher's ability to preserve locale-sensitive ordering // by wrapping it around a single searcher [Test] public virtual void TestInternationalMultiSearcherSort() { Searcher multiSearcher = new MultiSearcher(new Searchable[]{full}); sort.SetSort(new SortField("i18n", new System.Globalization.CultureInfo("sv" + "-" + "se"))); AssertMatches(multiSearcher, queryY, sort, "BJDFH"); sort.SetSort(new SortField("i18n", new System.Globalization.CultureInfo("en-US"))); AssertMatches(multiSearcher, queryY, sort, "BFJHD"); sort.SetSort(new SortField("i18n", new System.Globalization.CultureInfo("da" + "-" + "dk"))); AssertMatches(multiSearcher, queryY, sort, "BJDHF"); } // test a custom sort function [Test] public virtual void TestCustomSorts() { sort.SetSort(new SortField("custom", SampleComparable.GetComparatorSource())); AssertMatches(full, queryX, sort, "CAIEG"); sort.SetSort(new SortField("custom", SampleComparable.GetComparatorSource(), true)); AssertMatches(full, queryY, sort, "HJDBF"); SortComparator custom = SampleComparable.GetComparator(); sort.SetSort(new SortField("custom", custom)); AssertMatches(full, queryX, sort, "CAIEG"); sort.SetSort(new SortField("custom", custom, true)); AssertMatches(full, queryY, sort, "HJDBF"); } // test a variety of sorts using more than one searcher [Test] public virtual void TestMultiSort() { MultiSearcher searcher = new MultiSearcher(new Searchable[]{searchX, searchY}); RunMultiSorts(searcher, false); } // test a variety of sorts using a parallel multisearcher [Test] public virtual void TestParallelMultiSort() { Searcher searcher = new ParallelMultiSearcher(new Searchable[]{searchX, searchY}); RunMultiSorts(searcher, false); } // test that the relevancy scores are the same even if // hits are sorted [Test] public virtual void TestNormalizedScores() { // capture relevancy scores System.Collections.Hashtable scoresX = GetScores(full.Search(queryX, null, 1000).ScoreDocs, full); System.Collections.Hashtable scoresY = GetScores(full.Search(queryY, null, 1000).ScoreDocs, full); System.Collections.Hashtable scoresA = GetScores(full.Search(queryA, null, 1000).ScoreDocs, full); // we'll test searching locally, remote and multi MultiSearcher multi = new MultiSearcher(new Searchable[]{searchX, searchY}); // change sorting and make sure relevancy stays the same sort = new Sort(); AssertSameValues(scoresX, GetScores(full.Search(queryX, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresX, GetScores(multi.Search(queryX, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresY, GetScores(full.Search(queryY, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresY, GetScores(multi.Search(queryY, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresA, GetScores(full.Search(queryA, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresA, GetScores(multi.Search(queryA, null, 1000, sort).ScoreDocs, multi)); sort.SetSort(SortField.FIELD_DOC); AssertSameValues(scoresX, GetScores(full.Search(queryX, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresX, GetScores(multi.Search(queryX, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresY, GetScores(full.Search(queryY, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresY, GetScores(multi.Search(queryY, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresA, GetScores(full.Search(queryA, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresA, GetScores(multi.Search(queryA, null, 1000, sort).ScoreDocs, multi)); sort.SetSort("int"); AssertSameValues(scoresX, GetScores(full.Search(queryX, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresX, GetScores(multi.Search(queryX, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresY, GetScores(full.Search(queryY, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresY, GetScores(multi.Search(queryY, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresA, GetScores(full.Search(queryA, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresA, GetScores(multi.Search(queryA, null, 1000, sort).ScoreDocs, multi)); sort.SetSort("float"); AssertSameValues(scoresX, GetScores(full.Search(queryX, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresX, GetScores(multi.Search(queryX, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresY, GetScores(full.Search(queryY, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresY, GetScores(multi.Search(queryY, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresA, GetScores(full.Search(queryA, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresA, GetScores(multi.Search(queryA, null, 1000, sort).ScoreDocs, multi)); sort.SetSort("string"); AssertSameValues(scoresX, GetScores(full.Search(queryX, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresX, GetScores(multi.Search(queryX, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresY, GetScores(full.Search(queryY, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresY, GetScores(multi.Search(queryY, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresA, GetScores(full.Search(queryA, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresA, GetScores(multi.Search(queryA, null, 1000, sort).ScoreDocs, multi)); sort.SetSort(new System.String[]{"int", "float"}); AssertSameValues(scoresX, GetScores(full.Search(queryX, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresX, GetScores(multi.Search(queryX, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresY, GetScores(full.Search(queryY, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresY, GetScores(multi.Search(queryY, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresA, GetScores(full.Search(queryA, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresA, GetScores(multi.Search(queryA, null, 1000, sort).ScoreDocs, multi)); sort.SetSort(new SortField[]{new SortField("int", true), new SortField(null, SortField.DOC, true)}); AssertSameValues(scoresX, GetScores(full.Search(queryX, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresX, GetScores(multi.Search(queryX, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresY, GetScores(full.Search(queryY, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresY, GetScores(multi.Search(queryY, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresA, GetScores(full.Search(queryA, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresA, GetScores(multi.Search(queryA, null, 1000, sort).ScoreDocs, multi)); sort.SetSort(new System.String[]{"float", "string"}); AssertSameValues(scoresX, GetScores(full.Search(queryX, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresX, GetScores(multi.Search(queryX, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresY, GetScores(full.Search(queryY, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresY, GetScores(multi.Search(queryY, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresA, GetScores(full.Search(queryA, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresA, GetScores(multi.Search(queryA, null, 1000, sort).ScoreDocs, multi)); } [Test] public virtual void TestTopDocsScores() { // There was previously a bug in FieldSortedHitQueue.maxscore when only a single // doc was added. That is what the following tests for. Sort sort = new Sort(); int nDocs = 10; // try to pick a query that will result in an unnormalized // score greater than 1 to test for correct normalization TopDocs docs1 = full.Search(queryE, null, nDocs, sort); // a filter that only allows through the first hit Filter filt = new AnonymousClassFilter(docs1, this); TopDocs docs2 = full.Search(queryE, filt, nDocs, sort); Assert.AreEqual(docs1.ScoreDocs[0].score, docs2.ScoreDocs[0].score, 1e-6); } [Test] public virtual void TestSortWithoutFillFields() { // There was previously a bug in TopFieldCollector when fillFields was set // to false - the same doc and score was set in ScoreDoc[] array. This test // asserts that if fillFields is false, the documents are set properly. It // does not use Searcher's default search methods (with Sort) since all set // fillFields to true. Sort[] sort = new Sort[]{new Sort(SortField.FIELD_DOC), new Sort()}; for (int i = 0; i < sort.Length; i++) { Query q = new MatchAllDocsQuery(); TopDocsCollector tdc = TopFieldCollector.create(sort[i], 10, false, false, false, true); full.Search(q, tdc); ScoreDoc[] sd = tdc.TopDocs().ScoreDocs; for (int j = 1; j < sd.Length; j++) { Assert.IsTrue(sd[j].doc != sd[j - 1].doc); } } } [Test] public virtual void TestSortWithoutScoreTracking() { // Two Sort criteria to instantiate the multi/single comparators. Sort[] sort = new Sort[]{new Sort(SortField.FIELD_DOC), new Sort()}; for (int i = 0; i < sort.Length; i++) { Query q = new MatchAllDocsQuery(); TopDocsCollector tdc = TopFieldCollector.create(sort[i], 10, true, false, false, true); full.Search(q, tdc); TopDocs td = tdc.TopDocs(); ScoreDoc[] sd = td.ScoreDocs; for (int j = 0; j < sd.Length; j++) { Assert.IsTrue(System.Single.IsNaN(sd[j].score)); } Assert.IsTrue(System.Single.IsNaN(td.GetMaxScore())); } } [Test] public virtual void TestSortWithScoreNoMaxScoreTracking() { // Two Sort criteria to instantiate the multi/single comparators. Sort[] sort = new Sort[]{new Sort(SortField.FIELD_DOC), new Sort()}; for (int i = 0; i < sort.Length; i++) { Query q = new MatchAllDocsQuery(); TopDocsCollector tdc = TopFieldCollector.create(sort[i], 10, true, true, false, true); full.Search(q, tdc); TopDocs td = tdc.TopDocs(); ScoreDoc[] sd = td.ScoreDocs; for (int j = 0; j < sd.Length; j++) { Assert.IsTrue(!System.Single.IsNaN(sd[j].score)); } Assert.IsTrue(System.Single.IsNaN(td.GetMaxScore())); } } [Test] public virtual void TestSortWithScoreAndMaxScoreTracking() { // Two Sort criteria to instantiate the multi/single comparators. Sort[] sort = new Sort[]{new Sort(SortField.FIELD_DOC), new Sort()}; for (int i = 0; i < sort.Length; i++) { Query q = new MatchAllDocsQuery(); TopDocsCollector tdc = TopFieldCollector.create(sort[i], 10, true, true, true, true); full.Search(q, tdc); TopDocs td = tdc.TopDocs(); ScoreDoc[] sd = td.ScoreDocs; for (int j = 0; j < sd.Length; j++) { Assert.IsTrue(!System.Single.IsNaN(sd[j].score)); } Assert.IsTrue(!System.Single.IsNaN(td.GetMaxScore())); } } [Test] public virtual void TestOutOfOrderDocsScoringSort() { // Two Sort criteria to instantiate the multi/single comparators. Sort[] sort = new Sort[]{new Sort(SortField.FIELD_DOC), new Sort()}; bool[][] tfcOptions = new bool[][]{new bool[]{false, false, false}, new bool[]{false, false, true}, new bool[]{false, true, false}, new bool[]{false, true, true}, new bool[]{true, false, false}, new bool[]{true, false, true}, new bool[]{true, true, false}, new bool[]{true, true, true}}; System.String[] actualTFCClasses = new System.String[]{"OutOfOrderOneComparatorNonScoringCollector", "OutOfOrderOneComparatorScoringMaxScoreCollector", "OutOfOrderOneComparatorScoringNoMaxScoreCollector", "OutOfOrderOneComparatorScoringMaxScoreCollector", "OutOfOrderOneComparatorNonScoringCollector", "OutOfOrderOneComparatorScoringMaxScoreCollector", "OutOfOrderOneComparatorScoringNoMaxScoreCollector", "OutOfOrderOneComparatorScoringMaxScoreCollector"}; // Save the original value to set later. bool origVal = BooleanQuery.GetAllowDocsOutOfOrder(); BooleanQuery.SetAllowDocsOutOfOrder(true); BooleanQuery bq = new BooleanQuery(); // Add a Query with SHOULD, since bw.scorer() returns BooleanScorer2 // which delegates to BS if there are no mandatory clauses. bq.Add(new MatchAllDocsQuery(), Occur.SHOULD); // Set minNrShouldMatch to 1 so that BQ will not optimize rewrite to return // the clause instead of BQ. bq.SetMinimumNumberShouldMatch(1); try { for (int i = 0; i < sort.Length; i++) { for (int j = 0; j < tfcOptions.Length; j++) { TopDocsCollector tdc = TopFieldCollector.create(sort[i], 10, tfcOptions[j][0], tfcOptions[j][1], tfcOptions[j][2], false); Assert.IsTrue(tdc.GetType().FullName.EndsWith("+" + actualTFCClasses[j])); full.Search(bq, tdc); TopDocs td = tdc.TopDocs(); ScoreDoc[] sd = td.ScoreDocs; Assert.AreEqual(10, sd.Length); } } } finally { // Whatever happens, reset BooleanQuery.allowDocsOutOfOrder to the // original value. Don't set it to false in case the implementation in BQ // will change some day. BooleanQuery.SetAllowDocsOutOfOrder(origVal); } } [Test] public virtual void TestSortWithScoreAndMaxScoreTrackingNoResults() { // Two Sort criteria to instantiate the multi/single comparators. Sort[] sort = new Sort[]{new Sort(SortField.FIELD_DOC), new Sort()}; for (int i = 0; i < sort.Length; i++) { TopDocsCollector tdc = TopFieldCollector.create(sort[i], 10, true, true, true, true); TopDocs td = tdc.TopDocs(); Assert.AreEqual(0, td.TotalHits); Assert.IsTrue(System.Single.IsNaN(td.GetMaxScore())); } } // runs a variety of sorts useful for multisearchers private void RunMultiSorts(Searcher multi, bool isFull) { sort.SetSort(SortField.FIELD_DOC); System.String expected = isFull?"ABCDEFGHIJ":"ACEGIBDFHJ"; AssertMatches(multi, queryA, sort, expected); sort.SetSort(new SortField("int", SortField.INT)); expected = isFull?"IDHFGJABEC":"IDHFGJAEBC"; AssertMatches(multi, queryA, sort, expected); sort.SetSort(new SortField[]{new SortField("int", SortField.INT), SortField.FIELD_DOC}); expected = isFull?"IDHFGJABEC":"IDHFGJAEBC"; AssertMatches(multi, queryA, sort, expected); sort.SetSort("int"); expected = isFull?"IDHFGJABEC":"IDHFGJAEBC"; AssertMatches(multi, queryA, sort, expected); sort.SetSort(new SortField[]{new SortField("float", SortField.FLOAT), SortField.FIELD_DOC}); AssertMatches(multi, queryA, sort, "GDHJCIEFAB"); sort.SetSort("float"); AssertMatches(multi, queryA, sort, "GDHJCIEFAB"); sort.SetSort("string"); AssertMatches(multi, queryA, sort, "DJAIHGFEBC"); sort.SetSort("int", true); expected = isFull?"CABEJGFHDI":"CAEBJGFHDI"; AssertMatches(multi, queryA, sort, expected); sort.SetSort("float", true); AssertMatches(multi, queryA, sort, "BAFECIJHDG"); sort.SetSort("string", true); AssertMatches(multi, queryA, sort, "CBEFGHIAJD"); sort.SetSort(new System.String[]{"int", "float"}); AssertMatches(multi, queryA, sort, "IDHFGJEABC"); sort.SetSort(new System.String[]{"float", "string"}); AssertMatches(multi, queryA, sort, "GDHJICEFAB"); sort.SetSort("int"); AssertMatches(multi, queryF, sort, "IZJ"); sort.SetSort("int", true); AssertMatches(multi, queryF, sort, "JZI"); sort.SetSort("float"); AssertMatches(multi, queryF, sort, "ZJI"); sort.SetSort("string"); AssertMatches(multi, queryF, sort, "ZJI"); sort.SetSort("string", true); AssertMatches(multi, queryF, sort, "IJZ"); // up to this point, all of the searches should have "sane" // FieldCache behavior, and should have reused hte cache in several cases AssertSaneFieldCaches(Lucene.Net.TestCase.GetName() + " various"); // next we'll check Locale based (String[]) for 'string', so purge first Lucene.Net.Search.FieldCache_Fields.DEFAULT.PurgeAllCaches(); sort.SetSort(new SortField[]{new SortField("string", new System.Globalization.CultureInfo("en-US"))}); AssertMatches(multi, queryA, sort, "DJAIHGFEBC"); sort.SetSort(new SortField[]{new SortField("string", new System.Globalization.CultureInfo("en-US"), true)}); AssertMatches(multi, queryA, sort, "CBEFGHIAJD"); sort.SetSort(new SortField[]{new SortField("string", new System.Globalization.CultureInfo("en-GB"))}); AssertMatches(multi, queryA, sort, "DJAIHGFEBC"); AssertSaneFieldCaches(Lucene.Net.TestCase.GetName() + " Locale.US + Locale.UK"); Lucene.Net.Search.FieldCache_Fields.DEFAULT.PurgeAllCaches(); } // make sure the documents returned by the search match the expected list private void AssertMatches(Searcher searcher, Query query, Sort sort, System.String expectedResult) { //ScoreDoc[] result = searcher.search (query, null, 1000, sort).scoreDocs; TopDocs hits = searcher.Search(query, null, expectedResult.Length, sort); ScoreDoc[] result = hits.ScoreDocs; Assert.AreEqual(hits.TotalHits, expectedResult.Length); System.Text.StringBuilder buff = new System.Text.StringBuilder(10); int n = result.Length; for (int i = 0; i < n; ++i) { Document doc = searcher.Doc(result[i].doc); System.String[] v = doc.GetValues("tracer"); for (int j = 0; j < v.Length; ++j) { buff.Append(v[j]); } } Assert.AreEqual(expectedResult, buff.ToString()); } private System.Collections.Hashtable GetScores(ScoreDoc[] hits, Searcher searcher) { System.Collections.Hashtable scoreMap = new System.Collections.Hashtable(); int n = hits.Length; for (int i = 0; i < n; ++i) { Document doc = searcher.Doc(hits[i].doc); System.String[] v = doc.GetValues("tracer"); Assert.AreEqual(v.Length, 1); scoreMap[v[0]] = (float) hits[i].score; } return scoreMap; } // make sure all the values in the maps match private void AssertSameValues(System.Collections.Hashtable m1, System.Collections.Hashtable m2) { int n = m1.Count; int m = m2.Count; Assert.AreEqual(n, m); System.Collections.IEnumerator iter = m1.Keys.GetEnumerator(); while (iter.MoveNext()) { System.Object key = iter.Current; System.Object o1 = m1[key]; System.Object o2 = m2[key]; if (o1 is System.Single) { Assert.AreEqual((float) ((System.Single) o1), (float) ((System.Single) o2), 1e-6); } else { Assert.AreEqual(m1[key], m2[key]); } } } [Test] public void TestLUCENE2142() { RAMDirectory indexStore = new RAMDirectory(); IndexWriter writer = new IndexWriter(indexStore, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); for (int i = 0; i < 5; i++) { Document doc = new Document(); doc.Add(new Field("string", "a" + i, Field.Store.NO, Field.Index.NOT_ANALYZED)); doc.Add(new Field("string", "b" + i, Field.Store.NO, Field.Index.NOT_ANALYZED)); writer.AddDocument(doc); } writer.Optimize(); // enforce one segment to have a higher unique term count in all cases writer.Close(); sort.SetSort(new SortField[]{new SortField("string", SortField.STRING),SortField.FIELD_DOC }); // this should not throw AIOOBE or RuntimeEx new IndexSearcher(indexStore, true).Search(new MatchAllDocsQuery(), null, 500, sort); } } }
// Copyright (c) 2015, Outercurve Foundation. // 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 the Outercurve Foundation 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 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.IO; using System.Data; using System.Configuration; using System.Collections; using System.Xml; using System.Xml.Serialization; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using WebsitePanel.EnterpriseServer; using WebsitePanel.Providers.HostedSolution; using WebsitePanel.Providers.Common; using WebsitePanel.Providers.ResultObjects; namespace WebsitePanel.Portal { public partial class SettingsExchangeRetentionPolicyTag : WebsitePanelControlBase, IUserSettingsEditorControl { public void BindSettings(UserSettings settings) { BindRetentionPolicy(); string[] types = Enum.GetNames(typeof(ExchangeRetentionPolicyTagType)); ddTagType.Items.Clear(); for (int i = 0; i < types.Length; i++) { string name = GetSharedLocalizedString("Text." +types[i]); ddTagType.Items.Add(new ListItem(name, i.ToString())); } string[] action = Enum.GetNames(typeof(ExchangeRetentionPolicyTagAction)); ddRetentionAction.Items.Clear(); for (int i = 0; i < action.Length; i++) { string name = GetSharedLocalizedString("Text."+action[i]); ddRetentionAction.Items.Add(new ListItem(name, i.ToString())); } txtStatus.Visible = false; } private void BindRetentionPolicy() { Providers.HostedSolution.Organization[] orgs = null; if (PanelSecurity.SelectedUserId != 1) { PackageInfo[] Packages = ES.Services.Packages.GetPackages(PanelSecurity.SelectedUserId); if ((Packages != null) & (Packages.GetLength(0) > 0)) { orgs = ES.Services.ExchangeServer.GetExchangeOrganizations(Packages[0].PackageId, false); } } else { orgs = ES.Services.ExchangeServer.GetExchangeOrganizations(1, false); } if ((orgs != null) & (orgs.GetLength(0) > 0)) { ExchangeRetentionPolicyTag[] list = ES.Services.ExchangeServer.GetExchangeRetentionPolicyTags(orgs[0].Id); gvPolicy.DataSource = list; gvPolicy.DataBind(); } btnUpdatePolicy.Enabled = (string.IsNullOrEmpty(txtPolicy.Text)) ? false : true; } public void btnAddPolicy_Click(object sender, EventArgs e) { Page.Validate("CreatePolicy"); if (!Page.IsValid) return; ExchangeRetentionPolicyTag tag = new ExchangeRetentionPolicyTag(); tag.TagName = txtPolicy.Text; tag.TagType = Convert.ToInt32(ddTagType.SelectedValue); tag.AgeLimitForRetention = ageLimitForRetention.QuotaValue; tag.RetentionAction = Convert.ToInt32(ddRetentionAction.SelectedValue); Providers.HostedSolution.Organization[] orgs = null; if (PanelSecurity.SelectedUserId != 1) { PackageInfo[] Packages = ES.Services.Packages.GetPackages(PanelSecurity.SelectedUserId); if ((Packages != null) & (Packages.GetLength(0) > 0)) { orgs = ES.Services.ExchangeServer.GetExchangeOrganizations(Packages[0].PackageId, false); } } else { orgs = ES.Services.ExchangeServer.GetExchangeOrganizations(1, false); } if ((orgs != null) & (orgs.GetLength(0) > 0)) { IntResult result = ES.Services.ExchangeServer.AddExchangeRetentionPolicyTag(orgs[0].Id, tag); if (!result.IsSuccess) { messageBox.ShowMessage(result, "EXCHANGE_UPDATEPLANS", null); return; } else { messageBox.ShowSuccessMessage("EXCHANGE_UPDATEPLANS"); } } BindRetentionPolicy(); } protected void gvPolicy_RowCommand(object sender, GridViewCommandEventArgs e) { int mailboxPlanId = Utils.ParseInt(e.CommandArgument.ToString(), 0); Providers.HostedSolution.Organization[] orgs = null; Providers.HostedSolution.ExchangeRetentionPolicyTag tag; switch (e.CommandName) { case "DeleteItem": try { if (PanelSecurity.SelectedUserId != 1) { PackageInfo[] Packages = ES.Services.Packages.GetPackages(PanelSecurity.SelectedUserId); if ((Packages != null) & (Packages.GetLength(0) > 0)) { orgs = ES.Services.ExchangeServer.GetExchangeOrganizations(Packages[0].PackageId, false); } } else { orgs = ES.Services.ExchangeServer.GetExchangeOrganizations(1, false); } tag = ES.Services.ExchangeServer.GetExchangeRetentionPolicyTag(orgs[0].Id, mailboxPlanId); if (tag.ItemID != orgs[0].Id) { messageBox.ShowErrorMessage("EXCHANGE_UNABLE_USE_SYSTEMPLAN"); BindRetentionPolicy(); return; } ResultObject result = ES.Services.ExchangeServer.DeleteExchangeRetentionPolicyTag(orgs[0].Id, mailboxPlanId); if (!result.IsSuccess) { messageBox.ShowMessage(result, "EXCHANGE_DELETE_RETENTIONPOLICY", null); return; } else { messageBox.ShowSuccessMessage("EXCHANGE_DELETE_RETENTIONPOLICY"); } ViewState["PolicyID"] = null; txtPolicy.Text = string.Empty; ageLimitForRetention.QuotaValue = 0; btnUpdatePolicy.Enabled = (string.IsNullOrEmpty(txtPolicy.Text)) ? false : true; } catch (Exception) { messageBox.ShowErrorMessage("EXCHANGE_DELETE_RETENTIONPOLICY"); } BindRetentionPolicy(); break; case "EditItem": ViewState["PolicyID"] = mailboxPlanId; if (PanelSecurity.SelectedUserId != 1) { PackageInfo[] Packages = ES.Services.Packages.GetPackages(PanelSecurity.SelectedUserId); if ((Packages != null) & (Packages.GetLength(0) > 0)) { orgs = ES.Services.ExchangeServer.GetExchangeOrganizations(Packages[0].PackageId, false); } } else { orgs = ES.Services.ExchangeServer.GetExchangeOrganizations(1, false); } tag = ES.Services.ExchangeServer.GetExchangeRetentionPolicyTag(orgs[0].Id, mailboxPlanId); txtPolicy.Text = tag.TagName; Utils.SelectListItem(ddTagType, tag.TagType); ageLimitForRetention.QuotaValue = tag.AgeLimitForRetention; Utils.SelectListItem(ddRetentionAction, tag.RetentionAction); btnUpdatePolicy.Enabled = (string.IsNullOrEmpty(txtPolicy.Text)) ? false : true; break; } } public void SaveSettings(UserSettings settings) { settings["PolicyID"] = ""; } protected void btnUpdatePolicy_Click(object sender, EventArgs e) { Page.Validate("CreatePolicy"); if (!Page.IsValid) return; if (ViewState["PolicyID"] == null) return; int mailboxPlanId = (int)ViewState["PolicyID"]; Providers.HostedSolution.Organization[] orgs = null; Providers.HostedSolution.ExchangeRetentionPolicyTag tag; if (PanelSecurity.SelectedUserId != 1) { PackageInfo[] Packages = ES.Services.Packages.GetPackages(PanelSecurity.SelectedUserId); if ((Packages != null) & (Packages.GetLength(0) > 0)) { orgs = ES.Services.ExchangeServer.GetExchangeOrganizations(Packages[0].PackageId, false); } } else { orgs = ES.Services.ExchangeServer.GetExchangeOrganizations(1, false); } tag = ES.Services.ExchangeServer.GetExchangeRetentionPolicyTag(orgs[0].Id, mailboxPlanId); if (tag.ItemID != orgs[0].Id) { messageBox.ShowErrorMessage("EXCHANGE_UNABLE_USE_SYSTEMPLAN"); BindRetentionPolicy(); return; } tag.TagName = txtPolicy.Text; tag.TagType = Convert.ToInt32(ddTagType.SelectedValue); tag.AgeLimitForRetention = ageLimitForRetention.QuotaValue; tag.RetentionAction = Convert.ToInt32(ddRetentionAction.SelectedValue); if ((orgs != null) & (orgs.GetLength(0) > 0)) { ResultObject result = ES.Services.ExchangeServer.UpdateExchangeRetentionPolicyTag(orgs[0].Id, tag); if (!result.IsSuccess) { messageBox.ShowMessage(result, "EXCHANGE_UPDATEPLANS", null); } else { messageBox.ShowSuccessMessage("EXCHANGE_UPDATEPLANS"); } } BindRetentionPolicy(); } } }
#region Apache License // // 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. // #endregion namespace NotLogging { using System; using System.Collections; using log4net; using log4net.Appender; using log4net.Layout; using log4net.Repository; using log4net.Repository.Hierarchy; public class NotLogging { #region Init Code private static int WARM_UP_CYCLES = 10000; static readonly ILog SHORT_LOG = LogManager.GetLogger("A0123456789"); static readonly ILog MEDIUM_LOG= LogManager.GetLogger("A0123456789.B0123456789"); static readonly ILog LONG_LOG = LogManager.GetLogger("A0123456789.B0123456789.C0123456789"); static readonly ILog INEXISTENT_SHORT_LOG = LogManager.GetLogger("I0123456789"); static readonly ILog INEXISTENT_MEDIUM_LOG= LogManager.GetLogger("I0123456789.B0123456789"); static readonly ILog INEXISTENT_LONG_LOG = LogManager.GetLogger("I0123456789.B0123456789.C0123456789"); static readonly ILog[] LOG_ARRAY = new ILog[] { SHORT_LOG, MEDIUM_LOG, LONG_LOG, INEXISTENT_SHORT_LOG, INEXISTENT_MEDIUM_LOG, INEXISTENT_LONG_LOG}; static readonly TimedTest[] TIMED_TESTS = new TimedTest[] { new SimpleMessage_Bare(), new SimpleMessage_Array(), new SimpleMessage_MethodGuard_Bare(), new SimpleMessage_LocalGuard_Bare(), new ComplexMessage_Bare(), new ComplexMessage_Array(), new ComplexMessage_MethodGuard_Bare(), new ComplexMessage_MethodGuard_Array(), new ComplexMessage_MemberGuard_Bare(), new ComplexMessage_LocalGuard_Bare()}; private static void Usage() { System.Console.WriteLine( "Usage: NotLogging <true|false> <runLength>" + Environment.NewLine + "\t true indicates shipped code" + Environment.NewLine + "\t false indicates code in development" + Environment.NewLine + "\t runLength is an int representing the run length of loops" + Environment.NewLine + "\t We suggest that runLength be at least 1000000 (1 million)."); Environment.Exit(1); } /// <summary> /// Program wide initialization method /// </summary> /// <param name="args"></param> private static int ProgramInit(String[] args) { int runLength = 0; try { runLength = int.Parse(args[1]); } catch(Exception e) { System.Console.Error.WriteLine(e); Usage(); } ConsoleAppender appender = new ConsoleAppender(); appender.Layout = new SimpleLayout(); ((SimpleLayout)appender.Layout).ActivateOptions(); appender.ActivateOptions(); if("false" == args[0]) { // nothing to do } else if ("true" == args[0]) { System.Console.WriteLine("Flagging as shipped code."); ((Hierarchy)LogManager.GetRepository()).Threshold = log4net.Core.Level.Warn; } else { Usage(); } ((Logger)SHORT_LOG.Logger).Level = log4net.Core.Level.Info; ((Hierarchy)LogManager.GetRepository()).Root.Level = log4net.Core.Level.Info; ((Hierarchy)LogManager.GetRepository()).Root.AddAppender(appender); return runLength; } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] argv) { if (System.Diagnostics.Debugger.IsAttached) { WARM_UP_CYCLES = 0; argv = new string[] { "false", "2" }; } if(argv.Length != 2) { Usage(); } int runLength = ProgramInit(argv); System.Console.WriteLine(); System.Console.Write("Warming Up..."); if (WARM_UP_CYCLES > 0) { foreach(ILog logger in LOG_ARRAY) { foreach(TimedTest timedTest in TIMED_TESTS) { timedTest.Run(logger, WARM_UP_CYCLES); } } } System.Console.WriteLine("Done"); System.Console.WriteLine(); // Calculate maximum description length int maxDescLen = 0; foreach(TimedTest timedTest in TIMED_TESTS) { maxDescLen = Math.Max(maxDescLen, timedTest.Description.Length); } string formatString = "{0,-"+(maxDescLen+1)+"} {1,9:G} ticks. Log: {2}"; double delta; ArrayList averageData = new ArrayList(); foreach(TimedTest timedTest in TIMED_TESTS) { double total = 0; foreach(ILog logger in LOG_ARRAY) { delta = timedTest.Run(logger, runLength); System.Console.WriteLine(string.Format(formatString, timedTest.Description, delta, ((Logger)logger.Logger).Name)); total += delta; } System.Console.WriteLine(); averageData.Add(new object[] { timedTest, total/((double)LOG_ARRAY.Length) }); } System.Console.WriteLine(); System.Console.WriteLine("Averages:"); System.Console.WriteLine(); foreach(object[] pair in averageData) { string avgFormatString = "{0,-"+(maxDescLen+1)+"} {1,9:G} ticks."; System.Console.WriteLine(string.Format(avgFormatString, ((TimedTest)pair[0]).Description, ((double)pair[1]))); } } } abstract class TimedTest { abstract public double Run(ILog log, long runLength); abstract public string Description {get;} } #region Tests calling Debug(string) class SimpleMessage_Bare : TimedTest { override public double Run(ILog log, long runLength) { DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { log.Debug("msg"); } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "log.Debug(\"msg\");"; } } } class ComplexMessage_MethodGuard_Bare : TimedTest { override public double Run(ILog log, long runLength) { DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { if(log.IsDebugEnabled) { log.Debug("msg" + i + "msg"); } } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "if(log.IsDebugEnabled) log.Debug(\"msg\" + i + \"msg\");"; } } } class ComplexMessage_Bare : TimedTest { override public double Run(ILog log, long runLength) { DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { log.Debug("msg" + i + "msg"); } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "log.Debug(\"msg\" + i + \"msg\");"; } } } #endregion #region Tests calling Debug(new object[] { ... }) class SimpleMessage_Array : TimedTest { override public double Run(ILog log, long runLength) { DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { log.Debug(new object[] { "msg" }); } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "log.Debug(new object[] { \"msg\" });"; } } } class ComplexMessage_MethodGuard_Array : TimedTest { override public double Run(ILog log, long runLength) { DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { if(log.IsDebugEnabled) { log.Debug(new object[] { "msg" , i , "msg" }); } } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "if(log.IsDebugEnabled) log.Debug(new object[] { \"msg\" , i , \"msg\" });"; } } } class ComplexMessage_Array : TimedTest { override public double Run(ILog log, long runLength) { DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { log.Debug(new object[] { "msg" , i , "msg" }); } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "log.Debug(new object[] { \"msg\" , i , \"msg\" });"; } } } #endregion #region Tests calling Debug(string) (using class members) class ComplexMessage_MemberGuard_Bare : TimedTest { override public double Run(ILog log, long runLength) { return (new Impl(log)).Run(runLength); } override public string Description { get { return "if(m_isEnabled) m_log.Debug(\"msg\" + i + \"msg\");"; } } class Impl { private readonly ILog m_log; private readonly bool m_isEnabled; public Impl(ILog log) { m_log = log; m_isEnabled = m_log.IsDebugEnabled; } public double Run(long runLength) { DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { if(m_isEnabled) { m_log.Debug("msg" + i + "msg"); } } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } } } class SimpleMessage_LocalGuard_Bare : TimedTest { override public double Run(ILog log, long runLength) { bool isEnabled = log.IsDebugEnabled; DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { if (isEnabled) log.Debug("msg"); } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "if (isEnabled) log.Debug(\"msg\");"; } } } class SimpleMessage_MethodGuard_Bare : TimedTest { override public double Run(ILog log, long runLength) { DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { if (log.IsDebugEnabled) log.Debug("msg"); } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "if (log.IsDebugEnabled) log.Debug(\"msg\");"; } } } class ComplexMessage_LocalGuard_Bare : TimedTest { override public double Run(ILog log, long runLength) { bool isEnabled = log.IsDebugEnabled; DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { if(isEnabled) log.Debug("msg" + i + "msg"); } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "if (isEnabled) log.Debug(\"msg\" + i + \"msg\");"; } } } #endregion }
// // System.Diagnostics.FileVersionInfo.cs // // Authors: // Dick Porter ([email protected]) // Sebastien Pouliot <[email protected]> // // (C) 2002 Ximian, Inc. // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.IO; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.Text; namespace System.Diagnostics { [PermissionSet (SecurityAction.LinkDemand, Unrestricted = true)] public sealed class FileVersionInfo { /* There is no public constructor for this class, it * is initialised by the runtime. All the private * variables here are looked up by name, so dont * change them without also changing the runtime */ private string comments; private string companyname; private string filedescription; private string filename; private string fileversion; private string internalname; private string language; private string legalcopyright; private string legaltrademarks; private string originalfilename; private string privatebuild; private string productname; private string productversion; private string specialbuild; private bool isdebug; private bool ispatched; private bool isprerelease; private bool isprivatebuild; private bool isspecialbuild; private int filemajorpart; private int fileminorpart; private int filebuildpart; private int fileprivatepart; private int productmajorpart; private int productminorpart; private int productbuildpart; private int productprivatepart; private FileVersionInfo () { // no nulls (for unavailable items) comments = null; companyname = null; filedescription = null; filename = null; fileversion = null; internalname = null; language = null; legalcopyright = null; legaltrademarks = null; originalfilename = null; privatebuild = null; productname = null; productversion = null; specialbuild = null; // This is here just to shut the compiler up isdebug=false; ispatched=false; isprerelease=false; isprivatebuild=false; isspecialbuild=false; filemajorpart=0; fileminorpart=0; filebuildpart=0; fileprivatepart=0; productmajorpart=0; productminorpart=0; productbuildpart=0; productprivatepart=0; } public string Comments { get { return(comments); } } public string CompanyName { get { return(companyname); } } public int FileBuildPart { get { return(filebuildpart); } } public string FileDescription { get { return(filedescription); } } public int FileMajorPart { get { return(filemajorpart); } } public int FileMinorPart { get { return(fileminorpart); } } public string FileName { get { #if !NET_2_1 if (SecurityManager.SecurityEnabled) { new FileIOPermission (FileIOPermissionAccess.PathDiscovery, filename).Demand (); } #endif return filename; } } public int FilePrivatePart { get { return(fileprivatepart); } } public string FileVersion { get { return(fileversion); } } public string InternalName { get { return(internalname); } } public bool IsDebug { get { return(isdebug); } } public bool IsPatched { get { return(ispatched); } } public bool IsPreRelease { get { return(isprerelease); } } public bool IsPrivateBuild { get { return(isprivatebuild); } } public bool IsSpecialBuild { get { return(isspecialbuild); } } public string Language { get { return(language); } } public string LegalCopyright { get { return(legalcopyright); } } public string LegalTrademarks { get { return(legaltrademarks); } } public string OriginalFilename { get { return(originalfilename); } } public string PrivateBuild { get { return(privatebuild); } } public int ProductBuildPart { get { return(productbuildpart); } } public int ProductMajorPart { get { return(productmajorpart); } } public int ProductMinorPart { get { return(productminorpart); } } public string ProductName { get { return(productname); } } public int ProductPrivatePart { get { return(productprivatepart); } } public string ProductVersion { get { return(productversion); } } public string SpecialBuild { get { return(specialbuild); } } [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern void GetVersionInfo_internal(string fileName); public static FileVersionInfo GetVersionInfo (string fileName) { #if !NET_2_1 if (SecurityManager.SecurityEnabled) { new FileIOPermission (FileIOPermissionAccess.Read, fileName).Demand (); } #endif string absolute = Path.GetFullPath (fileName); if (!File.Exists (absolute)) throw new FileNotFoundException (fileName); FileVersionInfo fvi = new FileVersionInfo (); fvi.GetVersionInfo_internal (fileName); return fvi; } // use our own AppendFormat because NET_2_1 have only this overload static void AppendFormat (StringBuilder sb, string format, params object [] args) { sb.AppendFormat (format, args); } public override string ToString () { StringBuilder sb = new StringBuilder (); // we use the FileName property so we don't skip the security check AppendFormat (sb, "File: {0}{1}", FileName, Environment.NewLine); // the other informations aren't protected so we can use the members directly AppendFormat (sb, "InternalName: {0}{1}", internalname, Environment.NewLine); AppendFormat (sb, "OriginalFilename: {0}{1}", originalfilename, Environment.NewLine); AppendFormat (sb, "FileVersion: {0}{1}", fileversion, Environment.NewLine); AppendFormat (sb, "FileDescription: {0}{1}", filedescription, Environment.NewLine); AppendFormat (sb, "Product: {0}{1}", productname, Environment.NewLine); AppendFormat (sb, "ProductVersion: {0}{1}", productversion, Environment.NewLine); AppendFormat (sb, "Debug: {0}{1}", isdebug, Environment.NewLine); AppendFormat (sb, "Patched: {0}{1}", ispatched, Environment.NewLine); AppendFormat (sb, "PreRelease: {0}{1}", isprerelease, Environment.NewLine); AppendFormat (sb, "PrivateBuild: {0}{1}", isprivatebuild, Environment.NewLine); AppendFormat (sb, "SpecialBuild: {0}{1}", isspecialbuild, Environment.NewLine); AppendFormat (sb, "Language {0}{1}", language, Environment.NewLine); return sb.ToString (); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; /// <summary> /// char.IsPunctuation(string, int) /// Indicates whether the character at the specified position in a specified string is categorized /// as a punctuation. /// </summary> public class CharIsPunctuation { private const int c_MIN_STR_LEN = 2; private const int c_MAX_STR_LEN = 256; public static int Main() { CharIsPunctuation testObj = new CharIsPunctuation(); TestLibrary.TestFramework.BeginTestCase("for method: char.IsPunctuation(string, int)"); if(testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; TestLibrary.TestFramework.LogInformation("[Negaitive]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } #region Positive tests public bool PosTest1() { //Generate a character for validate char ch = '"'; return this.DoTest("PosTest1: Punctuation character", "P001", "001", "002", ch, true); } public bool PosTest2() { //Generate a non punctuation character for validate char ch = 'A'; return this.DoTest("PosTest2: Non-punctuation character.", "P002", "003", "004", ch, false); } #endregion #region Helper method for positive tests private bool DoTest(string testDesc, string testId, string errorNum1, string errorNum2, char ch, bool expectedResult) { bool retVal = true; string errorDesc; TestLibrary.TestFramework.BeginScenario(testDesc); try { string str = new string(ch ,1); bool actualResult = char.IsPunctuation(str, 0); if (expectedResult != actualResult) { if (expectedResult) { errorDesc = string.Format("Character \\u{0:x} should belong to punctuation.", (int)ch); } else { errorDesc = string.Format("Character \\u{0:x} does not belong to punctuation.", (int)ch); } TestLibrary.TestFramework.LogError(errorNum1 + " TestId-" + testId, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; errorDesc += string.Format("\nCharacter is \\u{0:x}", ch); TestLibrary.TestFramework.LogError(errorNum2 + " TestId-" + testId, errorDesc); retVal = false; } return retVal; } #endregion #region Negative tests //ArgumentNullException public bool NegTest1() { bool retVal = true; const string c_TEST_ID = "N001"; const string c_TEST_DESC = "NegTest1: String is a null reference (Nothing in Visual Basic)."; string errorDesc; int index = 0; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { index = TestLibrary.Generator.GetInt32(-55); char.IsPunctuation(null, index); errorDesc = "ArgumentNullException is not thrown as expected, index is " + index; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e + "\n Index is " + index; TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } //ArgumentOutOfRangeException public bool NegTest2() { bool retVal = true; const string c_TEST_ID = "N002"; const string c_TEST_DESC = "NegTest2: Index is too great."; string errorDesc; string str = string.Empty; int index = 0; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN); index = str.Length + TestLibrary.Generator.GetInt16(-55); index = str.Length; char.IsPunctuation(str, index); errorDesc = "ArgumentOutOfRangeException is not thrown as expected"; TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; errorDesc += string.Format("\nThe string is {0}, and the index is {1}", str, index); TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; const string c_TEST_ID = "N003"; const string c_TEST_DESC = "NegTest3: Index is a negative value"; string errorDesc; string str = string.Empty; int index = 0; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN); index = -1 * (TestLibrary.Generator.GetInt16(-55)); char.IsPunctuation(str, index); errorDesc = "ArgumentOutOfRangeException is not thrown as expected"; TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; errorDesc += string.Format("\nThe string is {0}, and the index is {1}", str, index); TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } #endregion }
// 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.Generic; using System.Drawing; using System.Threading; using System.Diagnostics; using MonoTouch.Foundation; using MonoTouch.UIKit; using FlickrNet; using FlickrCache; using MonoTouchUtils; /// <summary> /// Author: Saxon D'Aubin /// </summary> namespace Funnier { public partial class ImageViewController : UIViewController { private const string NoConnectionMessage = "Sorry, but there's no connection available to download cartoons. Please try again with a wifi connection."; private PagingScrollView scrollView; private readonly PhotosetCache dataSource; public ImageViewController(IntPtr handle) : base (handle) { dataSource = FlickrDataSource.Get().PhotosetCache; } private void PhotoAdded(PhotosetPhoto photo) { InvokeOnMainThread (delegate { lblLoadingMessage.Hidden = true; (scrollView.DataSource as DataSource).AddPhoto(photo); }); } public override void DidReceiveMemoryWarning () { // Releases the view if it doesn't have a superview. base.DidReceiveMemoryWarning (); // Release any cached data, images, etc that aren't in use. scrollView.FreeUnusedViews(); } private void CheckConnectionAndDisplayMessage () { // when a device on a cell network first starts our app, it's often told there's no connection // only to get a reachability notification a moment later. because of that, we delay our // "No connection" message for a moment to make sure that's actually the case if (NetworkStatus.NotReachable == Reachability.RemoteHostStatus()) { var ev = new AutoResetEvent(false); ThreadPool.RegisterWaitForSingleObject(ev, delegate(Object obj, bool timedOut) { if (NetworkStatus.NotReachable == Reachability.RemoteHostStatus()) { // ok, we really don't have a connection InvokeOnMainThread(delegate { lblLoadingMessage.Text = NoConnectionMessage; }); } }, null, TimeSpan.FromSeconds(3), true); } } private void NoticeImagesChanged(int totalCount, int recentlyArrivedCount, int recentlyDownloadedCount) { if (recentlyArrivedCount == 0) return; // we only want to display a message with the initial download dataSource.ImagesChanged -= NoticeImagesChanged; string message; if (recentlyDownloadedCount == recentlyArrivedCount) { message = String.Format("{0} new cartoon{1} arrived.", recentlyArrivedCount, recentlyArrivedCount > 1 ? "s" : ""); } else { message = String.Format( "{0} new cartoon{1} arrived. {2} were downloaded. The rest will be downloaded when a wifi connection is available", recentlyArrivedCount, (recentlyDownloadedCount > 1 ? "s" : ""), recentlyDownloadedCount); } InvokeOnMainThread(delegate { SendNotification(message, recentlyArrivedCount); lblLoadingMessage.Text = message; }); } private void NoticeMessages(string message) { InvokeOnMainThread(delegate { Debug.WriteLine("ImageViewController received message: {0}", message); lblLoadingMessage.Text = message; View.SetNeedsDisplay(); }); } public override void ViewDidLoad () { base.ViewDidLoad (); Debug.WriteLine("Image controller view did load"); scrollView = new PagingScrollView(View.Bounds); // set our scroll view to automatically resize on rotation scrollView.AutoresizingMask = UIViewAutoresizing.FlexibleDimensions; View.BackgroundColor = UIColor.White; scrollView.BackgroundColor = UIColor.Clear; View.AddSubview(scrollView); dataSource.Added += PhotoAdded; dataSource.ImagesChanged += NoticeImagesChanged; dataSource.Messages += NoticeMessages; var scrollViewDataSource = new DataSource(dataSource.Photos); scrollView.DataSource = scrollViewDataSource; if (dataSource.Photos.Length == 0) { CheckConnectionAndDisplayMessage(); } else { lblLoadingMessage.Hidden = true; } scrollView.OnScroll += delegate { // clear the icon badge number. In the future we might want to update it as cartoons are viewed UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0; SetToolbarHidden(true); // we have to do this on another thread because the scroll hasn't finished yet ThreadPool.QueueUserWorkItem(delegate { GlobalUserSettings.Get().LastViewedCartoonId = scrollViewDataSource.GetPhoto(scrollView.GetCurrentViewIndex()).Id; }); }; scrollView.AddGestureRecognizer(new UITapGestureRecognizer(this, new MonoTouch.ObjCRuntime.Selector("tapToggleToolbar"))); var spacerButton = new UIBarButtonItem(UIBarButtonSystemItem.FixedSpace); spacerButton.Width = 5; toolbar.SetItems(new UIBarButtonItem[] { // spacerButton, GetFirstImageButton(), new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace), GetLastImageButton(), spacerButton}, false); View.BringSubviewToFront(toolbar); (UIApplication.SharedApplication.Delegate as AppDelegate).FetchCartoonsIfConnected(); } public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); var id = GlobalUserSettings.Get().LastViewedCartoonId; if (null != id && id.Length > 0) { var lastViewedIndex = (scrollView.DataSource as DataSource).GetIndex(id); if (lastViewedIndex > 0) { scrollView.ScrollToView(lastViewedIndex); } scrollView.FinishRotation(lastViewedIndex); } } private UIBarButtonItem GetFirstImageButton() { return new UIBarButtonItem(UIBarButtonSystemItem.Rewind, delegate { scrollView.ScrollToView(0); }); } private UIBarButtonItem GetLastImageButton() { return new UIBarButtonItem(UIBarButtonSystemItem.FastForward, delegate { Debug.WriteLine("Width {0}", View.Frame.Width); scrollView.ScrollToView(dataSource.Photos.Length - 1); }); } [Export("tapToggleToolbar")] private void Tap(UITapGestureRecognizer sender) { // animate showing and hiding the toolbar if (sender.State == UIGestureRecognizerState.Ended) { SetToolbarHidden(!toolbar.Hidden); } } private void SetToolbarHidden(bool hide) { if (hide == toolbar.Hidden) { return; } float height = (UIDevice.CurrentDevice.Orientation == UIDeviceOrientation.LandscapeLeft || UIDevice.CurrentDevice.Orientation == UIDeviceOrientation.LandscapeRight) ? UIScreen.MainScreen.ApplicationFrame.Width : UIScreen.MainScreen.ApplicationFrame.Height; bool hidden = toolbar.Hidden; if (hidden) { toolbar.Frame = new RectangleF(toolbar.Frame.X, height, toolbar.Frame.Width, toolbar.Frame.Height); toolbar.Hidden = false; } Debug.WriteLine("{0} toolbar, y = {1}", hidden ? "show" : "hide", height); UIView.Animate(0.2, 0, UIViewAnimationOptions.TransitionFlipFromBottom, delegate() { float newY = height - (hidden ? toolbar.Frame.Height : 0); toolbar.Frame = new RectangleF(toolbar.Frame.X, newY, toolbar.Frame.Width, toolbar.Frame.Height); }, delegate() { toolbar.Hidden = !hidden; }); } public override void ViewDidUnload () { base.ViewDidUnload (); // Clear any references to subviews of the main view in order to // allow the Garbage Collector to collect them sooner. // // e.g. myOutlet.Dispose (); myOutlet = null; // remove our event listener. very important dataSource.Added -= PhotoAdded; dataSource.ImagesChanged -= NoticeImagesChanged; dataSource.Messages -= NoticeMessages; ReleaseDesignerOutlets (); Debug.WriteLine("View unload"); } public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation) { return true; } int? currentIndex; public override void WillRotate (UIInterfaceOrientation toInterfaceOrientation, double duration) { currentIndex = scrollView.PrepareForRotation(); base.WillRotate (toInterfaceOrientation, duration); } public override void DidRotate (UIInterfaceOrientation fromInterfaceOrientation) { base.DidRotate (fromInterfaceOrientation); scrollView.FinishRotation(currentIndex); } private void SendNotification(string message, int count) { Debug.WriteLine("Sending notification: {0}", message); UILocalNotification notification = new UILocalNotification{ FireDate = DateTime.Now, TimeZone = NSTimeZone.LocalTimeZone, AlertBody = message, RepeatInterval = 0, ApplicationIconBadgeNumber = count }; UIApplication.SharedApplication.InvokeOnMainThread(delegate { UIApplication.SharedApplication.ScheduleLocalNotification(notification); }); } private class DataSource : PagingViewDataSource { private readonly List<PhotosetPhoto> photos; public event Changed OnChanged; public DataSource(PhotosetPhoto[] photos) { this.photos = new List<PhotosetPhoto>(photos); if (null != OnChanged) { OnChanged(); } } public int Count { get { return photos.Count; } } public void AddPhoto(PhotosetPhoto newPhoto) { this.photos.Add(newPhoto); if (null != OnChanged) { OnChanged(); } } public UIView GetView(int index) { var view = new CaptionedImage(photos[index]); view.AutoresizingMask = UIViewAutoresizing.FlexibleDimensions; return view; } public PhotosetPhoto GetPhoto(int index) { return photos[index]; } public int GetIndex(string photoId) { for (var i = 0; i < photos.Count; i++) { PhotosetPhoto p = photos[i]; if (p.Id.Equals(photoId)) { return i; } } return -1; } } } }
using System; using System.IO; namespace Ionic.Zlib { internal enum ZlibStreamFlavor { ZLIB = 1950, DEFLATE = 1951, GZIP = 1952 } internal class ZlibBaseStream : System.IO.Stream { protected internal ZlibCodec _z = null; // deferred init... new ZlibCodec(); protected internal StreamMode _streamMode = StreamMode.Undefined; protected internal FlushType _flushMode; protected internal ZlibStreamFlavor _flavor; protected internal CompressionMode _compressionMode; protected internal CompressionLevel _level; protected internal bool _leaveOpen; protected internal byte[] _workingBuffer; protected internal int _bufferSize = ZlibConstants.WorkingBufferSizeDefault; protected internal byte[] _buf1 = new byte[1]; protected internal System.IO.Stream _stream; protected internal CompressionStrategy Strategy = CompressionStrategy.Default; // workitem 7159 Ionic.Crc.CRC32 crc; protected internal string _GzipFileName; protected internal string _GzipComment; protected internal DateTime _GzipMtime; protected internal int _gzipHeaderByteCount; internal int Crc32 { get { if (crc == null) return 0; return crc.Crc32Result; } } public ZlibBaseStream(System.IO.Stream stream, CompressionMode compressionMode, CompressionLevel level, ZlibStreamFlavor flavor, bool leaveOpen) : base() { this._flushMode = FlushType.None; //this._workingBuffer = new byte[WORKING_BUFFER_SIZE_DEFAULT]; this._stream = stream; this._leaveOpen = leaveOpen; this._compressionMode = compressionMode; this._flavor = flavor; this._level = level; // workitem 7159 if (flavor == ZlibStreamFlavor.GZIP) { this.crc = new Ionic.Crc.CRC32(); } } protected internal bool _wantCompress { get { return (this._compressionMode == CompressionMode.Compress); } } private ZlibCodec z { get { if (_z == null) { bool wantRfc1950Header = (this._flavor == ZlibStreamFlavor.ZLIB); _z = new ZlibCodec(); if (this._compressionMode == CompressionMode.Decompress) { _z.InitializeInflate(wantRfc1950Header); } else { _z.Strategy = Strategy; _z.InitializeDeflate(this._level, wantRfc1950Header); } } return _z; } } private byte[] workingBuffer { get { if (_workingBuffer == null) _workingBuffer = new byte[_bufferSize]; return _workingBuffer; } } public override void Write(System.Byte[] buffer, int offset, int count) { // workitem 7159 // calculate the CRC on the unccompressed data (before writing) if (crc != null) crc.SlurpBlock(buffer, offset, count); if (_streamMode == StreamMode.Undefined) _streamMode = StreamMode.Writer; else if (_streamMode != StreamMode.Writer) throw new ZlibException("Cannot Write after Reading."); if (count == 0) return; // first reference of z property will initialize the private var _z z.InputBuffer = buffer; _z.NextIn = offset; _z.AvailableBytesIn = count; bool done = false; do { _z.OutputBuffer = workingBuffer; _z.NextOut = 0; _z.AvailableBytesOut = _workingBuffer.Length; int rc = (_wantCompress) ? _z.Deflate(_flushMode) : _z.Inflate(_flushMode); if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) throw new ZlibException((_wantCompress ? "de" : "in") + "flating: " + _z.Message); //if (_workingBuffer.Length - _z.AvailableBytesOut > 0) _stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut); done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0; // If GZIP and de-compress, we're done when 8 bytes remain. if (_flavor == ZlibStreamFlavor.GZIP && !_wantCompress) done = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0); } while (!done); } private void finish() { if (_z == null) return; if (_streamMode == StreamMode.Writer) { bool done = false; do { _z.OutputBuffer = workingBuffer; _z.NextOut = 0; _z.AvailableBytesOut = _workingBuffer.Length; int rc = (_wantCompress) ? _z.Deflate(FlushType.Finish) : _z.Inflate(FlushType.Finish); if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK) { string verb = (_wantCompress ? "de" : "in") + "flating"; if (_z.Message == null) throw new ZlibException(String.Format("{0}: (rc = {1})", verb, rc)); else throw new ZlibException(verb + ": " + _z.Message); } if (_workingBuffer.Length - _z.AvailableBytesOut > 0) { _stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut); } done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0; // If GZIP and de-compress, we're done when 8 bytes remain. if (_flavor == ZlibStreamFlavor.GZIP && !_wantCompress) done = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0); } while (!done); Flush(); // workitem 7159 if (_flavor == ZlibStreamFlavor.GZIP) { if (_wantCompress) { // Emit the GZIP trailer: CRC32 and size mod 2^32 int c1 = crc.Crc32Result; _stream.Write(BitConverter.GetBytes(c1), 0, 4); int c2 = (Int32)(crc.TotalBytesRead & 0x00000000FFFFFFFF); _stream.Write(BitConverter.GetBytes(c2), 0, 4); } else { throw new ZlibException("Writing with decompression is not supported."); } } } // workitem 7159 else if (_streamMode == StreamMode.Reader) { if (_flavor == ZlibStreamFlavor.GZIP) { if (!_wantCompress) { // workitem 8501: handle edge case (decompress empty stream) if (_z.TotalBytesOut == 0L) return; // Read and potentially verify the GZIP trailer: // CRC32 and size mod 2^32 byte[] trailer = new byte[8]; // workitems 8679 & 12554 if (_z.AvailableBytesIn < 8) { // Make sure we have read to the end of the stream Array.Copy(_z.InputBuffer, _z.NextIn, trailer, 0, _z.AvailableBytesIn); int bytesNeeded = 8 - _z.AvailableBytesIn; int bytesRead = _stream.Read(trailer, _z.AvailableBytesIn, bytesNeeded); if (bytesNeeded != bytesRead) { throw new ZlibException(String.Format("Missing or incomplete GZIP trailer. Expected 8 bytes, got {0}.", _z.AvailableBytesIn + bytesRead)); } } else { Array.Copy(_z.InputBuffer, _z.NextIn, trailer, 0, trailer.Length); } Int32 crc32_expected = BitConverter.ToInt32(trailer, 0); Int32 crc32_actual = crc.Crc32Result; Int32 isize_expected = BitConverter.ToInt32(trailer, 4); Int32 isize_actual = (Int32)(_z.TotalBytesOut & 0x00000000FFFFFFFF); if (crc32_actual != crc32_expected) throw new ZlibException(String.Format("Bad CRC32 in GZIP trailer. (actual({0:X8})!=expected({1:X8}))", crc32_actual, crc32_expected)); if (isize_actual != isize_expected) throw new ZlibException(String.Format("Bad size in GZIP trailer. (actual({0})!=expected({1}))", isize_actual, isize_expected)); } else { throw new ZlibException("Reading with compression is not supported."); } } } } private void end() { if (z == null) return; if (_wantCompress) { _z.EndDeflate(); } else { _z.EndInflate(); } _z = null; } public override void Close() { if (_stream == null) return; try { finish(); } finally { end(); if (!_leaveOpen) _stream.Close(); _stream = null; } } public override void Flush() { _stream.Flush(); } public override System.Int64 Seek(System.Int64 offset, System.IO.SeekOrigin origin) { throw new NotImplementedException(); //_outStream.Seek(offset, origin); } public override void SetLength(System.Int64 value) { _stream.SetLength(value); } #if NOT public int Read() { if (Read(_buf1, 0, 1) == 0) return 0; // calculate CRC after reading if (crc!=null) crc.SlurpBlock(_buf1,0,1); return (_buf1[0] & 0xFF); } #endif private bool nomoreinput = false; private string ReadZeroTerminatedString() { var list = new System.Collections.Generic.List<byte>(); bool done = false; do { // workitem 7740 int n = _stream.Read(_buf1, 0, 1); if (n != 1) throw new ZlibException("Unexpected EOF reading GZIP header."); else { if (_buf1[0] == 0) done = true; else list.Add(_buf1[0]); } } while (!done); byte[] a = list.ToArray(); return GZipStream.iso8859dash1.GetString(a, 0, a.Length); } private int _ReadAndValidateGzipHeader() { int totalBytesRead = 0; // read the header on the first read byte[] header = new byte[10]; int n = _stream.Read(header, 0, header.Length); // workitem 8501: handle edge case (decompress empty stream) if (n == 0) return 0; if (n != 10) throw new ZlibException("Not a valid GZIP stream."); if (header[0] != 0x1F || header[1] != 0x8B || header[2] != 8) throw new ZlibException("Bad GZIP header."); Int32 timet = BitConverter.ToInt32(header, 4); _GzipMtime = GZipStream._unixEpoch.AddSeconds(timet); totalBytesRead += n; if ((header[3] & 0x04) == 0x04) { // read and discard extra field n = _stream.Read(header, 0, 2); // 2-byte length field totalBytesRead += n; Int16 extraLength = (Int16)(header[0] + header[1] * 256); byte[] extra = new byte[extraLength]; n = _stream.Read(extra, 0, extra.Length); if (n != extraLength) throw new ZlibException("Unexpected end-of-file reading GZIP header."); totalBytesRead += n; } if ((header[3] & 0x08) == 0x08) _GzipFileName = ReadZeroTerminatedString(); if ((header[3] & 0x10) == 0x010) _GzipComment = ReadZeroTerminatedString(); if ((header[3] & 0x02) == 0x02) Read(_buf1, 0, 1); // CRC16, ignore return totalBytesRead; } public override System.Int32 Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count) { // According to MS documentation, any implementation of the IO.Stream.Read function must: // (a) throw an exception if offset & count reference an invalid part of the buffer, // or if count < 0, or if buffer is null // (b) return 0 only upon EOF, or if count = 0 // (c) if not EOF, then return at least 1 byte, up to <count> bytes if (_streamMode == StreamMode.Undefined) { if (!this._stream.CanRead) throw new ZlibException("The stream is not readable."); // for the first read, set up some controls. _streamMode = StreamMode.Reader; // (The first reference to _z goes through the private accessor which // may initialize it.) z.AvailableBytesIn = 0; if (_flavor == ZlibStreamFlavor.GZIP) { _gzipHeaderByteCount = _ReadAndValidateGzipHeader(); // workitem 8501: handle edge case (decompress empty stream) if (_gzipHeaderByteCount == 0) return 0; } } if (_streamMode != StreamMode.Reader) throw new ZlibException("Cannot Read after Writing."); if (count == 0) return 0; if (nomoreinput && _wantCompress) return 0; // workitem 8557 if (buffer == null) throw new ArgumentNullException("buffer"); if (count < 0) throw new ArgumentOutOfRangeException("count"); if (offset < buffer.GetLowerBound(0)) throw new ArgumentOutOfRangeException("offset"); if ((offset + count) > buffer.GetLength(0)) throw new ArgumentOutOfRangeException("count"); int rc = 0; // set up the output of the deflate/inflate codec: _z.OutputBuffer = buffer; _z.NextOut = offset; _z.AvailableBytesOut = count; // This is necessary in case _workingBuffer has been resized. (new byte[]) // (The first reference to _workingBuffer goes through the private accessor which // may initialize it.) _z.InputBuffer = workingBuffer; do { // need data in _workingBuffer in order to deflate/inflate. Here, we check if we have any. if ((_z.AvailableBytesIn == 0) && (!nomoreinput)) { // No data available, so try to Read data from the captive stream. _z.NextIn = 0; _z.AvailableBytesIn = _stream.Read(_workingBuffer, 0, _workingBuffer.Length); if (_z.AvailableBytesIn == 0) nomoreinput = true; } // we have data in InputBuffer; now compress or decompress as appropriate rc = (_wantCompress) ? _z.Deflate(_flushMode) : _z.Inflate(_flushMode); if (nomoreinput && (rc == ZlibConstants.Z_BUF_ERROR)) return 0; if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) throw new ZlibException(String.Format("{0}flating: rc={1} msg={2}", (_wantCompress ? "de" : "in"), rc, _z.Message)); if ((nomoreinput || rc == ZlibConstants.Z_STREAM_END) && (_z.AvailableBytesOut == count)) break; // nothing more to read } //while (_z.AvailableBytesOut == count && rc == ZlibConstants.Z_OK); while (_z.AvailableBytesOut > 0 && !nomoreinput && rc == ZlibConstants.Z_OK); // workitem 8557 // is there more room in output? if (_z.AvailableBytesOut > 0) { if (rc == ZlibConstants.Z_OK && _z.AvailableBytesIn == 0) { // deferred } // are we completely done reading? if (nomoreinput) { // and in compression? if (_wantCompress) { // no more input data available; therefore we flush to // try to complete the read rc = _z.Deflate(FlushType.Finish); if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) throw new ZlibException(String.Format("Deflating: rc={0} msg={1}", rc, _z.Message)); } } } rc = (count - _z.AvailableBytesOut); // calculate CRC after reading if (crc != null) crc.SlurpBlock(buffer, offset, rc); return rc; } public override System.Boolean CanRead { get { return this._stream.CanRead; } } public override System.Boolean CanSeek { get { return this._stream.CanSeek; } } public override System.Boolean CanWrite { get { return this._stream.CanWrite; } } public override System.Int64 Length { get { return _stream.Length; } } public override long Position { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } internal enum StreamMode { Writer, Reader, Undefined, } public static void CompressString(String s, Stream compressor) { byte[] uncompressed = System.Text.Encoding.UTF8.GetBytes(s); using (compressor) { compressor.Write(uncompressed, 0, uncompressed.Length); } } public static void CompressBuffer(byte[] b, Stream compressor) { // workitem 8460 using (compressor) { compressor.Write(b, 0, b.Length); } } public static String UncompressString(byte[] compressed, Stream decompressor) { // workitem 8460 byte[] working = new byte[1024]; var encoding = System.Text.Encoding.UTF8; using (var output = new MemoryStream()) { using (decompressor) { int n; while ((n = decompressor.Read(working, 0, working.Length)) != 0) { output.Write(working, 0, n); } } // reset to allow read from start output.Seek(0, SeekOrigin.Begin); var sr = new StreamReader(output, encoding); return sr.ReadToEnd(); } } public static byte[] UncompressBuffer(byte[] compressed, Stream decompressor) { // workitem 8460 byte[] working = new byte[1024]; using (var output = new MemoryStream()) { using (decompressor) { int n; while ((n = decompressor.Read(working, 0, working.Length)) != 0) { output.Write(working, 0, n); } } return output.ToArray(); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================ ** ** ** ** Purpose: The boolean class serves as a wrapper for the primitive ** type boolean. ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Diagnostics.Contracts; // The Boolean class provides the // object representation of the boolean primitive type. [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public struct Boolean : IComparable, IConvertible, IComparable<Boolean>, IEquatable<Boolean> { // // Member Variables // private bool m_value; // The true value. // internal const int True = 1; // The false value. // internal const int False = 0; // // Internal Constants are real consts for performance. // // The internal string representation of true. // internal const String TrueLiteral = "True"; // The internal string representation of false. // internal const String FalseLiteral = "False"; // // Public Constants // // The public string representation of true. // public static readonly String TrueString = TrueLiteral; // The public string representation of false. // public static readonly String FalseString = FalseLiteral; // // Overriden Instance Methods // /*=================================GetHashCode================================== **Args: None **Returns: 1 or 0 depending on whether this instance represents true or false. **Exceptions: None **Overriden From: Value ==============================================================================*/ // Provides a hash code for this instance. public override int GetHashCode() { return (m_value)?True:False; } /*===================================ToString=================================== **Args: None **Returns: "True" or "False" depending on the state of the boolean. **Exceptions: None. ==============================================================================*/ // Converts the boolean value of this instance to a String. public override String ToString() { if (false == m_value) { return FalseLiteral; } return TrueLiteral; } public String ToString(IFormatProvider provider) { if (false == m_value) { return FalseLiteral; } return TrueLiteral; } // Determines whether two Boolean objects are equal. public override bool Equals (Object obj) { //If it's not a boolean, we're definitely not equal if (!(obj is Boolean)) { return false; } return (m_value==((Boolean)obj).m_value); } [System.Runtime.Versioning.NonVersionable] public bool Equals(Boolean obj) { return m_value == obj; } // Compares this object to another object, returning an integer that // indicates the relationship. For booleans, false sorts before true. // null is considered to be less than any instance. // If object is not of type boolean, this method throws an ArgumentException. // // Returns a value less than zero if this object // public int CompareTo(Object obj) { if (obj==null) { return 1; } if (!(obj is Boolean)) { throw new ArgumentException (Environment.GetResourceString("Arg_MustBeBoolean")); } if (m_value==((Boolean)obj).m_value) { return 0; } else if (m_value==false) { return -1; } return 1; } public int CompareTo(Boolean value) { if (m_value==value) { return 0; } else if (m_value==false) { return -1; } return 1; } // // Static Methods // // Determines whether a String represents true or false. // public static Boolean Parse (String value) { if (value==null) throw new ArgumentNullException("value"); Contract.EndContractBlock(); Boolean result = false; if (!TryParse(value, out result)) { throw new FormatException(Environment.GetResourceString("Format_BadBoolean")); } else { return result; } } // Determines whether a String represents true or false. // public static Boolean TryParse (String value, out Boolean result) { result = false; if (value==null) { return false; } // For perf reasons, let's first see if they're equal, then do the // trim to get rid of white space, and check again. if (TrueLiteral.Equals(value, StringComparison.OrdinalIgnoreCase)) { result = true; return true; } if (FalseLiteral.Equals(value,StringComparison.OrdinalIgnoreCase)) { result = false; return true; } // Special case: Trim whitespace as well as null characters. value = TrimWhiteSpaceAndNull(value); if (TrueLiteral.Equals(value, StringComparison.OrdinalIgnoreCase)) { result = true; return true; } if (FalseLiteral.Equals(value,StringComparison.OrdinalIgnoreCase)) { result = false; return true; } return false; } private static String TrimWhiteSpaceAndNull(String value) { int start = 0; int end = value.Length-1; char nullChar = (char) 0x0000; while (start < value.Length) { if (!Char.IsWhiteSpace(value[start]) && value[start] != nullChar) { break; } start++; } while (end >= start) { if (!Char.IsWhiteSpace(value[end]) && value[end] != nullChar) { break; } end--; } return value.Substring(start, end - start + 1); } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Boolean; } /// <internalonly/> bool IConvertible.ToBoolean(IFormatProvider provider) { return m_value; } /// <internalonly/> char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Boolean", "Char")); } /// <internalonly/> sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } /// <internalonly/> byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } /// <internalonly/> short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } /// <internalonly/> ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } /// <internalonly/> int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } /// <internalonly/> uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } /// <internalonly/> long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } /// <internalonly/> ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } /// <internalonly/> float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } /// <internalonly/> double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } /// <internalonly/> Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } /// <internalonly/> DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Boolean", "DateTime")); } /// <internalonly/> Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace BallaratMinute.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using UnityEditorInternal; using UnityEngine; using UnityEngine.PostProcessing; namespace UnityEditor.PostProcessing { public class VectorscopeMonitor : PostProcessingMonitor { static GUIContent s_MonitorTitle = new GUIContent("Vectorscope"); ComputeShader m_ComputeShader; ComputeBuffer m_Buffer; Material m_Material; RenderTexture m_VectorscopeTexture; Rect m_MonitorAreaRect; public VectorscopeMonitor() { m_ComputeShader = EditorResources.Load<ComputeShader>("Monitors/VectorscopeCompute.compute"); } public override void Dispose() { GraphicsUtils.Destroy(m_Material); GraphicsUtils.Destroy(m_VectorscopeTexture); if (m_Buffer != null) m_Buffer.Release(); m_Material = null; m_VectorscopeTexture = null; m_Buffer = null; } public override bool IsSupported() { return m_ComputeShader != null && GraphicsUtils.supportsDX11; } public override GUIContent GetMonitorTitle() { return s_MonitorTitle; } public override void OnMonitorSettings() { EditorGUI.BeginChangeCheck(); bool refreshOnPlay = m_MonitorSettings.refreshOnPlay; float exposure = m_MonitorSettings.vectorscopeExposure; bool showBackground = m_MonitorSettings.vectorscopeShowBackground; refreshOnPlay = GUILayout.Toggle(refreshOnPlay, new GUIContent(FxStyles.playIcon, "Keep refreshing the vectorscope in play mode; this may impact performances."), FxStyles.preButton); exposure = GUILayout.HorizontalSlider(exposure, 0.05f, 0.3f, FxStyles.preSlider, FxStyles.preSliderThumb, GUILayout.Width(40f)); showBackground = GUILayout.Toggle(showBackground, new GUIContent(FxStyles.checkerIcon, "Show an YUV background in the vectorscope."), FxStyles.preButton); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(m_BaseEditor.serializedObject.targetObject, "Vectorscope Settings Changed"); m_MonitorSettings.refreshOnPlay = refreshOnPlay; m_MonitorSettings.vectorscopeExposure = exposure; m_MonitorSettings.vectorscopeShowBackground = showBackground; InternalEditorUtility.RepaintAllViews(); } } public override void OnMonitorGUI(Rect r) { if (Event.current.type == EventType.Repaint) { // If m_MonitorAreaRect isn't set the preview was just opened so refresh the render to get the vectoscope data if (Mathf.Approximately(m_MonitorAreaRect.width, 0) && Mathf.Approximately(m_MonitorAreaRect.height, 0)) InternalEditorUtility.RepaintAllViews(); // Sizing float size = 0f; if (r.width < r.height) { size = m_VectorscopeTexture != null ? Mathf.Min(m_VectorscopeTexture.width, r.width - 35f) : r.width; } else { size = m_VectorscopeTexture != null ? Mathf.Min(m_VectorscopeTexture.height, r.height - 25f) : r.height; } m_MonitorAreaRect = new Rect( Mathf.Floor(r.x + r.width / 2f - size / 2f), Mathf.Floor(r.y + r.height / 2f - size / 2f - 5f), size, size ); if (m_VectorscopeTexture != null) { m_Material.SetFloat("_Exposure", m_MonitorSettings.vectorscopeExposure); var oldActive = RenderTexture.active; Graphics.Blit(null, m_VectorscopeTexture, m_Material, m_MonitorSettings.vectorscopeShowBackground ? 0 : 1); RenderTexture.active = oldActive; Graphics.DrawTexture(m_MonitorAreaRect, m_VectorscopeTexture); var color = Color.white; const float kTickSize = 10f; const int kTickCount = 24; float radius = m_MonitorAreaRect.width / 2f; float midX = m_MonitorAreaRect.x + radius; float midY = m_MonitorAreaRect.y + radius; var center = new Vector2(midX, midY); // Cross color.a *= 0.5f; Handles.color = color; Handles.DrawLine(new Vector2(midX, m_MonitorAreaRect.y), new Vector2(midX, m_MonitorAreaRect.y + m_MonitorAreaRect.height)); Handles.DrawLine(new Vector2(m_MonitorAreaRect.x, midY), new Vector2(m_MonitorAreaRect.x + m_MonitorAreaRect.width, midY)); if (m_MonitorAreaRect.width > 100f) { color.a = 1f; // Ticks Handles.color = color; for (int i = 0; i < kTickCount; i++) { float a = (float)i / (float)kTickCount; float theta = a * (Mathf.PI * 2f); float tx = Mathf.Cos(theta + (Mathf.PI / 2f)); float ty = Mathf.Sin(theta - (Mathf.PI / 2f)); var innerVec = center + new Vector2(tx, ty) * (radius - kTickSize); var outerVec = center + new Vector2(tx, ty) * radius; Handles.DrawAAPolyLine(3f, innerVec, outerVec); } // Labels (where saturation reaches 75%) color.a = 1f; var oldColor = GUI.color; GUI.color = color * 2f; var point = new Vector2(-0.254f, -0.750f) * radius + center; var rect = new Rect(point.x - 10f, point.y - 10f, 20f, 20f); GUI.Label(rect, "[R]", FxStyles.tickStyleCenter); point = new Vector2(-0.497f, 0.629f) * radius + center; rect = new Rect(point.x - 10f, point.y - 10f, 20f, 20f); GUI.Label(rect, "[G]", FxStyles.tickStyleCenter); point = new Vector2(0.750f, 0.122f) * radius + center; rect = new Rect(point.x - 10f, point.y - 10f, 20f, 20f); GUI.Label(rect, "[B]", FxStyles.tickStyleCenter); point = new Vector2(-0.750f, -0.122f) * radius + center; rect = new Rect(point.x - 10f, point.y - 10f, 20f, 20f); GUI.Label(rect, "[Y]", FxStyles.tickStyleCenter); point = new Vector2(0.254f, 0.750f) * radius + center; rect = new Rect(point.x - 10f, point.y - 10f, 20f, 20f); GUI.Label(rect, "[C]", FxStyles.tickStyleCenter); point = new Vector2(0.497f, -0.629f) * radius + center; rect = new Rect(point.x - 10f, point.y - 10f, 20f, 20f); GUI.Label(rect, "[M]", FxStyles.tickStyleCenter); GUI.color = oldColor; } } } } public override void OnFrameData(RenderTexture source) { if (Application.isPlaying && !m_MonitorSettings.refreshOnPlay) return; if (Mathf.Approximately(m_MonitorAreaRect.width, 0) || Mathf.Approximately(m_MonitorAreaRect.height, 0)) return; float ratio = (float)source.width / (float)source.height; int h = 384; int w = Mathf.FloorToInt(h * ratio); var rt = RenderTexture.GetTemporary(w, h, 0, source.format); Graphics.Blit(source, rt); ComputeVectorscope(rt); m_BaseEditor.Repaint(); RenderTexture.ReleaseTemporary(rt); } void CreateBuffer(int width, int height) { m_Buffer = new ComputeBuffer(width * height, sizeof(uint)); } void ComputeVectorscope(RenderTexture source) { if (m_Buffer == null) { CreateBuffer(source.width, source.height); } else if (m_Buffer.count != (source.width * source.height)) { m_Buffer.Release(); CreateBuffer(source.width, source.height); } var cs = m_ComputeShader; int kernel = cs.FindKernel("KVectorscopeClear"); cs.SetBuffer(kernel, "_Vectorscope", m_Buffer); cs.SetVector("_Res", new Vector4(source.width, source.height, 0f, 0f)); cs.Dispatch(kernel, Mathf.CeilToInt(source.width / 32f), Mathf.CeilToInt(source.height / 32f), 1); kernel = cs.FindKernel("KVectorscope"); cs.SetBuffer(kernel, "_Vectorscope", m_Buffer); cs.SetTexture(kernel, "_Source", source); cs.SetInt("_IsLinear", GraphicsUtils.isLinearColorSpace ? 1 : 0); cs.SetVector("_Res", new Vector4(source.width, source.height, 0f, 0f)); cs.Dispatch(kernel, Mathf.CeilToInt(source.width / 32f), Mathf.CeilToInt(source.height / 32f), 1); if (m_VectorscopeTexture == null || m_VectorscopeTexture.width != source.width || m_VectorscopeTexture.height != source.height) { GraphicsUtils.Destroy(m_VectorscopeTexture); m_VectorscopeTexture = new RenderTexture(source.width, source.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear) { hideFlags = HideFlags.DontSave, wrapMode = TextureWrapMode.Clamp, filterMode = FilterMode.Bilinear }; } if (m_Material == null) m_Material = new Material(Shader.Find("Hidden/Post FX/Monitors/Vectorscope Render")) { hideFlags = HideFlags.DontSave }; m_Material.SetBuffer("_Vectorscope", m_Buffer); m_Material.SetVector("_Size", new Vector2(m_VectorscopeTexture.width, m_VectorscopeTexture.height)); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace SINF_proj.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.ServiceModel.Description { using System.Collections.Generic; using System.Collections.ObjectModel; using System.IdentityModel.Configuration; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.Security.Claims; using System.Security.Cryptography.X509Certificates; using System.ServiceModel.Channels; using System.ServiceModel.Security; using System.ServiceModel.Security.Tokens; using System.ServiceModel.Dispatcher; public class ServiceCredentials : SecurityCredentialsManager, IServiceBehavior { UserNamePasswordServiceCredential userName; X509CertificateInitiatorServiceCredential clientCertificate; X509CertificateRecipientServiceCredential serviceCertificate; WindowsServiceCredential windows; IssuedTokenServiceCredential issuedToken; PeerCredential peer; SecureConversationServiceCredential secureConversation; bool useIdentityConfiguration = false; bool isReadOnly = false; bool saveBootstrapTokenInSession = true; IdentityConfiguration identityConfiguration; ExceptionMapper exceptionMapper; public ServiceCredentials() { this.userName = new UserNamePasswordServiceCredential(); this.clientCertificate = new X509CertificateInitiatorServiceCredential(); this.serviceCertificate = new X509CertificateRecipientServiceCredential(); this.windows = new WindowsServiceCredential(); this.issuedToken = new IssuedTokenServiceCredential(); this.peer = new PeerCredential(); this.secureConversation = new SecureConversationServiceCredential(); this.exceptionMapper = new ExceptionMapper(); this.UseIdentityConfiguration = false; } protected ServiceCredentials(ServiceCredentials other) { if (other == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("other"); } this.userName = new UserNamePasswordServiceCredential(other.userName); this.clientCertificate = new X509CertificateInitiatorServiceCredential(other.clientCertificate); this.serviceCertificate = new X509CertificateRecipientServiceCredential(other.serviceCertificate); this.windows = new WindowsServiceCredential(other.windows); this.issuedToken = new IssuedTokenServiceCredential(other.issuedToken); this.peer = new PeerCredential(other.peer); this.secureConversation = new SecureConversationServiceCredential(other.secureConversation); this.identityConfiguration = other.identityConfiguration; this.saveBootstrapTokenInSession = other.saveBootstrapTokenInSession; this.exceptionMapper = other.exceptionMapper; this.UseIdentityConfiguration = other.useIdentityConfiguration; } public UserNamePasswordServiceCredential UserNameAuthentication { get { return this.userName; } } public X509CertificateInitiatorServiceCredential ClientCertificate { get { return this.clientCertificate; } } public X509CertificateRecipientServiceCredential ServiceCertificate { get { return this.serviceCertificate; } } public WindowsServiceCredential WindowsAuthentication { get { return this.windows; } } public IssuedTokenServiceCredential IssuedTokenAuthentication { get { return this.issuedToken; } } public PeerCredential Peer { get { return this.peer; } } public SecureConversationServiceCredential SecureConversationAuthentication { get { return this.secureConversation; } } /// <summary> /// Gets or sets the ExceptionMapper to be used when throwing exceptions. /// </summary> public ExceptionMapper ExceptionMapper { get { return this.exceptionMapper; } set { ThrowIfImmutable(); if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } this.exceptionMapper = value; } } public IdentityConfiguration IdentityConfiguration { get { return this.identityConfiguration; } set { ThrowIfImmutable(); this.identityConfiguration = value; } } public bool UseIdentityConfiguration { get { return this.useIdentityConfiguration; } set { ThrowIfImmutable(); this.useIdentityConfiguration = value; if (this.identityConfiguration == null && this.useIdentityConfiguration) { this.identityConfiguration = new IdentityConfiguration(); } } } internal static ServiceCredentials CreateDefaultCredentials() { return new ServiceCredentials(); } public override SecurityTokenManager CreateSecurityTokenManager() { if (this.useIdentityConfiguration) { // // Note: the token manager we create here is always a wrapper over the default collection of token handlers // return new FederatedSecurityTokenManager(this.Clone()); } else { return new ServiceCredentialsSecurityTokenManager(this.Clone()); } } protected virtual ServiceCredentials CloneCore() { return new ServiceCredentials(this); } public ServiceCredentials Clone() { ServiceCredentials result = CloneCore(); if (result == null || result.GetType() != this.GetType()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException(SR.GetString(SR.CloneNotImplementedCorrectly, this.GetType(), (result != null) ? result.ToString() : "null"))); } return result; } void IServiceBehavior.Validate(ServiceDescription description, ServiceHostBase serviceHostBase) { // // Only pass a name if there was a name explicitly given to this class, otherwise ServiceConfig will require // a config section with the default configuration. // if (this.UseIdentityConfiguration) { ConfigureServiceHost(serviceHostBase); } } /// <summary> /// Helper method that Initializes the SecurityTokenManager used by the ServiceHost. /// By default the method sets the SecurityTokenHandlers initialized with IdentityConfiguration on the ServiceHost. /// </summary> /// <param name="serviceHost">ServiceHost instance to configure with FederatedSecurityTokenManager.</param> /// <exception cref="ArgumentNullException">One of the input argument is null.</exception> void ConfigureServiceHost(ServiceHostBase serviceHost) { if (serviceHost == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serviceHost"); } // Throw if the serviceHost is in a bad state to do the configuration if (!(serviceHost.State == CommunicationState.Created || serviceHost.State == CommunicationState.Opening)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4041, serviceHost)); } #pragma warning suppress 56506 if (this.ServiceCertificate != null) { X509Certificate2 serverCert = this.ServiceCertificate.Certificate; if (serverCert != null) { this.IdentityConfiguration.ServiceCertificate = serverCert; } } if (this.IssuedTokenAuthentication != null && this.IssuedTokenAuthentication.KnownCertificates != null && this.IssuedTokenAuthentication.KnownCertificates.Count > 0) { this.IdentityConfiguration.KnownIssuerCertificates = new List<X509Certificate2> (this.IssuedTokenAuthentication.KnownCertificates); } // // Initialize the service configuration // if (!this.IdentityConfiguration.IsInitialized) { this.IdentityConfiguration.Initialize(); } // #pragma warning suppress 56506 // serviceHost.Authorization is never null. if (serviceHost.Authorization.ServiceAuthorizationManager == null) { serviceHost.Authorization.ServiceAuthorizationManager = new IdentityModelServiceAuthorizationManager(); } else if (!(serviceHost.Authorization.ServiceAuthorizationManager is IdentityModelServiceAuthorizationManager)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4039))); } // If SecuritySessionTokenHandler is being used then null the WCF SecurityStateEncoder. if ((this.IdentityConfiguration.SecurityTokenHandlers[typeof(SecurityContextSecurityToken)] != null) && (serviceHost.Credentials.SecureConversationAuthentication.SecurityStateEncoder == null)) { serviceHost.Credentials.SecureConversationAuthentication.SecurityStateEncoder = new NoOpSecurityStateEncoder(); } } void IServiceBehavior.AddBindingParameters(ServiceDescription description, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection parameters) { if (parameters == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parameters"); } // throw if bindingParameters already has a SecurityCredentialsManager SecurityCredentialsManager otherCredentialsManager = parameters.Find<SecurityCredentialsManager>(); if (otherCredentialsManager != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MultipleSecurityCredentialsManagersInServiceBindingParameters, otherCredentialsManager))); } parameters.Add(this); } void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase serviceHostBase) { for (int i = 0; i < serviceHostBase.ChannelDispatchers.Count; i++) { ChannelDispatcher channelDispatcher = serviceHostBase.ChannelDispatchers[i] as ChannelDispatcher; if (channelDispatcher != null && !ServiceMetadataBehavior.IsHttpGetMetadataDispatcher(description, channelDispatcher)) { foreach (EndpointDispatcher endpointDispatcher in channelDispatcher.Endpoints) { DispatchRuntime behavior = endpointDispatcher.DispatchRuntime; behavior.RequireClaimsPrincipalOnOperationContext = this.useIdentityConfiguration; } } } } internal void MakeReadOnly() { this.isReadOnly = true; this.ClientCertificate.MakeReadOnly(); this.IssuedTokenAuthentication.MakeReadOnly(); this.Peer.MakeReadOnly(); this.SecureConversationAuthentication.MakeReadOnly(); this.ServiceCertificate.MakeReadOnly(); this.UserNameAuthentication.MakeReadOnly(); this.WindowsAuthentication.MakeReadOnly(); } void ThrowIfImmutable() { if (this.isReadOnly) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ObjectIsReadOnly))); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using Validation; using Xunit; namespace System.Collections.Immutable.Test { public abstract class ImmutableDictionaryTestBase : ImmutablesTestBase { [Fact] public virtual void EmptyTest() { this.EmptyTestHelper(Empty<int, bool>(), 5); } [Fact] public void EnumeratorTest() { this.EnumeratorTestHelper(this.Empty<int, GenericParameterHelper>()); } [Fact] public void ContainsTest() { this.ContainsTestHelper(Empty<int, string>(), 5, "foo"); } [Fact] public void RemoveTest() { this.RemoveTestHelper(Empty<int, GenericParameterHelper>(), 5); } [Fact] public void KeysTest() { this.KeysTestHelper(Empty<int, bool>(), 5); } [Fact] public void ValuesTest() { this.ValuesTestHelper(Empty<int, bool>(), 5); } [Fact] public void AddAscendingTest() { this.AddAscendingTestHelper(Empty<int, GenericParameterHelper>()); } [Fact] public void AddRangeTest() { var map = Empty<int, GenericParameterHelper>(); map = map.AddRange(Enumerable.Range(1, 100).Select(n => new KeyValuePair<int, GenericParameterHelper>(n, new GenericParameterHelper()))); CollectionAssertAreEquivalent(map.Select(kv => kv.Key).ToList(), Enumerable.Range(1, 100).ToList()); Assert.Equal(100, map.Count); // Test optimization for empty map. var map2 = Empty<int, GenericParameterHelper>(); var jointMap = map2.AddRange(map); Assert.Same(map, jointMap); jointMap = map2.AddRange(map.ToReadOnlyDictionary()); Assert.Same(map, jointMap); jointMap = map2.AddRange(map.ToBuilder()); Assert.Same(map, jointMap); } [Fact] public void AddDescendingTest() { this.AddDescendingTestHelper(Empty<int, GenericParameterHelper>()); } [Fact] public void AddRemoveRandomDataTest() { this.AddRemoveRandomDataTestHelper(Empty<double, GenericParameterHelper>()); } [Fact] public void AddRemoveEnumerableTest() { this.AddRemoveEnumerableTestHelper(Empty<int, int>()); } [Fact] public void SetItemTest() { var map = this.Empty<string, int>() .SetItem("Microsoft", 100) .SetItem("Corporation", 50); Assert.Equal(2, map.Count); map = map.SetItem("Microsoft", 200); Assert.Equal(2, map.Count); Assert.Equal(200, map["Microsoft"]); // Set it to the same thing again and make sure it's all good. var sameMap = map.SetItem("Microsoft", 200); Assert.Same(map, sameMap); } [Fact] public void SetItemsTest() { var template = new Dictionary<string, int> { { "Microsoft", 100 }, { "Corporation", 50 }, }; var map = this.Empty<string, int>().SetItems(template); Assert.Equal(2, map.Count); var changes = new Dictionary<string, int> { { "Microsoft", 150 }, { "Dogs", 90 }, }; map = map.SetItems(changes); Assert.Equal(3, map.Count); Assert.Equal(150, map["Microsoft"]); Assert.Equal(50, map["Corporation"]); Assert.Equal(90, map["Dogs"]); map = map.SetItems( new[] { new KeyValuePair<string, int>("Microsoft", 80), new KeyValuePair<string, int>("Microsoft", 70), }); Assert.Equal(3, map.Count); Assert.Equal(70, map["Microsoft"]); Assert.Equal(50, map["Corporation"]); Assert.Equal(90, map["Dogs"]); map = this.Empty<string, int>().SetItems(new[] { // use an array for code coverage new KeyValuePair<string, int>("a", 1), new KeyValuePair<string, int>("b", 2), new KeyValuePair<string, int>("a", 3), }); Assert.Equal(2, map.Count); Assert.Equal(3, map["a"]); Assert.Equal(2, map["b"]); } [Fact] public void ContainsKeyTest() { this.ContainsKeyTestHelper(Empty<int, GenericParameterHelper>(), 1, new GenericParameterHelper()); } [Fact] public void IndexGetNonExistingKeyThrowsTest() { Assert.Throws<KeyNotFoundException>(() => this.Empty<int, int>()[3]); } [Fact] public void IndexGetTest() { var map = this.Empty<int, int>().Add(3, 5); Assert.Equal(5, map[3]); } [Fact] public void DictionaryRemoveThrowsTest() { IDictionary<int, int> map = this.Empty<int, int>().Add(5, 3).ToReadOnlyDictionary(); Assert.Throws<NotSupportedException>(() => map.Remove(5)); } [Fact] public void DictionaryAddThrowsTest() { IDictionary<int, int> map = this.Empty<int, int>().ToReadOnlyDictionary(); Assert.Throws<NotSupportedException>(() => map.Add(5, 3)); } [Fact] public void DictionaryIndexSetThrowsTest() { IDictionary<int, int> map = this.Empty<int, int>().ToReadOnlyDictionary(); Assert.Throws<NotSupportedException>(() => map[3] = 5); } [Fact] public void EqualsTest() { Assert.False(Empty<int, int>().Equals(null)); Assert.False(Empty<int, int>().Equals("hi")); Assert.True(Empty<int, int>().Equals(Empty<int, int>())); Assert.False(Empty<int, int>().Add(3, 2).Equals(Empty<int, int>().Add(3, 2))); Assert.False(Empty<int, int>().Add(3, 2).Equals(Empty<int, int>().Add(3, 1))); Assert.False(Empty<int, int>().Add(5, 1).Equals(Empty<int, int>().Add(3, 1))); Assert.False(Empty<int, int>().Add(3, 1).Add(5, 1).Equals(Empty<int, int>().Add(3, 1))); Assert.False(Empty<int, int>().Add(3, 1).Equals(Empty<int, int>().Add(3, 1).Add(5, 1))); Assert.True(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>())); Assert.True(Empty<int, int>().Equals(Empty<int, int>().ToReadOnlyDictionary())); Assert.True(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>().ToReadOnlyDictionary())); Assert.False(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary().Equals(Empty<int, int>())); Assert.False(Empty<int, int>().Equals(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary())); Assert.False(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary())); } /// <summary> /// Verifies that the GetHashCode method returns the standard one. /// </summary> [Fact] public void GetHashCodeTest() { var dictionary = Empty<string, int>(); Assert.Equal(EqualityComparer<object>.Default.GetHashCode(dictionary), dictionary.GetHashCode()); } [Fact] public void ICollectionOfKVMembers() { var dictionary = (ICollection<KeyValuePair<string, int>>)Empty<string, int>(); Assert.Throws<NotSupportedException>(() => dictionary.Add(new KeyValuePair<string, int>())); Assert.Throws<NotSupportedException>(() => dictionary.Remove(new KeyValuePair<string, int>())); Assert.Throws<NotSupportedException>(() => dictionary.Clear()); Assert.True(dictionary.IsReadOnly); } [Fact] public void ICollectionMembers() { var dictionary = (ICollection)Empty<string, int>().Add("a", 1); Assert.True(dictionary.IsSynchronized); Assert.NotNull(dictionary.SyncRoot); Assert.Same(dictionary.SyncRoot, dictionary.SyncRoot); var array = new object[2]; dictionary.CopyTo(array, 1); Assert.Null(array[0]); Assert.Equal(new DictionaryEntry("a", 1), (DictionaryEntry)array[1]); } [Fact] public void IDictionaryOfKVMembers() { var dictionary = (IDictionary<string, int>)Empty<string, int>().Add("c", 3); Assert.Throws<NotSupportedException>(() => dictionary.Add("a", 1)); Assert.Throws<NotSupportedException>(() => dictionary.Remove("a")); Assert.Throws<NotSupportedException>(() => dictionary["a"] = 2); Assert.Throws<KeyNotFoundException>(() => dictionary["a"]); Assert.Equal(3, dictionary["c"]); } [Fact] public void IDictionaryMembers() { var dictionary = (IDictionary)Empty<string, int>().Add("c", 3); Assert.Throws<NotSupportedException>(() => dictionary.Add("a", 1)); Assert.Throws<NotSupportedException>(() => dictionary.Remove("a")); Assert.Throws<NotSupportedException>(() => dictionary["a"] = 2); Assert.Throws<NotSupportedException>(() => dictionary.Clear()); Assert.False(dictionary.Contains("a")); Assert.True(dictionary.Contains("c")); Assert.Throws<KeyNotFoundException>(() => dictionary["a"]); Assert.Equal(3, dictionary["c"]); Assert.True(dictionary.IsFixedSize); Assert.True(dictionary.IsReadOnly); Assert.Equal(new[] { "c" }, dictionary.Keys.Cast<string>().ToArray()); Assert.Equal(new[] { 3 }, dictionary.Values.Cast<int>().ToArray()); } [Fact] public void IDictionaryEnumerator() { var dictionary = (IDictionary)Empty<string, int>().Add("a", 1); var enumerator = dictionary.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.True(enumerator.MoveNext()); Assert.Equal(enumerator.Entry, enumerator.Current); Assert.Equal(enumerator.Key, enumerator.Entry.Key); Assert.Equal(enumerator.Value, enumerator.Entry.Value); Assert.Equal("a", enumerator.Key); Assert.Equal(1, enumerator.Value); Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.False(enumerator.MoveNext()); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.True(enumerator.MoveNext()); Assert.Equal(enumerator.Key, ((DictionaryEntry)enumerator.Current).Key); Assert.Equal(enumerator.Value, ((DictionaryEntry)enumerator.Current).Value); Assert.Equal("a", enumerator.Key); Assert.Equal(1, enumerator.Value); Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.False(enumerator.MoveNext()); } [Fact] public void TryGetKey() { var dictionary = Empty<int>(StringComparer.OrdinalIgnoreCase) .Add("a", 1); string actualKey; Assert.True(dictionary.TryGetKey("a", out actualKey)); Assert.Equal("a", actualKey); Assert.True(dictionary.TryGetKey("A", out actualKey)); Assert.Equal("a", actualKey); Assert.False(dictionary.TryGetKey("b", out actualKey)); Assert.Equal("b", actualKey); } protected void EmptyTestHelper<K, V>(IImmutableDictionary<K, V> empty, K someKey) { Assert.Same(empty, empty.Clear()); Assert.Equal(0, empty.Count); Assert.Equal(0, empty.Count()); Assert.Equal(0, empty.Keys.Count()); Assert.Equal(0, empty.Values.Count()); Assert.Same(EqualityComparer<V>.Default, GetValueComparer(empty)); Assert.False(empty.ContainsKey(someKey)); Assert.False(empty.Contains(new KeyValuePair<K, V>(someKey, default(V)))); Assert.Equal(default(V), empty.GetValueOrDefault(someKey)); V value; Assert.False(empty.TryGetValue(someKey, out value)); Assert.Equal(default(V), value); } private IImmutableDictionary<TKey, TValue> AddTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value) where TKey : IComparable<TKey> { Contract.Requires(map != null); Contract.Requires(key != null); IImmutableDictionary<TKey, TValue> addedMap = map.Add(key, value); Assert.NotSame(map, addedMap); ////Assert.Equal(map.Count + 1, addedMap.Count); Assert.False(map.ContainsKey(key)); Assert.True(addedMap.ContainsKey(key)); AssertAreSame(value, addedMap.GetValueOrDefault(key)); return addedMap; } protected void AddAscendingTestHelper(IImmutableDictionary<int, GenericParameterHelper> map) { Contract.Requires(map != null); for (int i = 0; i < 10; i++) { map = this.AddTestHelper(map, i, new GenericParameterHelper(i)); } Assert.Equal(10, map.Count); for (int i = 0; i < 10; i++) { Assert.True(map.ContainsKey(i)); } } protected void AddDescendingTestHelper(IImmutableDictionary<int, GenericParameterHelper> map) { for (int i = 10; i > 0; i--) { map = this.AddTestHelper(map, i, new GenericParameterHelper(i)); } Assert.Equal(10, map.Count); for (int i = 10; i > 0; i--) { Assert.True(map.ContainsKey(i)); } } protected void AddRemoveRandomDataTestHelper(IImmutableDictionary<double, GenericParameterHelper> map) { Contract.Requires(map != null); double[] inputs = GenerateDummyFillData(); for (int i = 0; i < inputs.Length; i++) { map = this.AddTestHelper(map, inputs[i], new GenericParameterHelper()); } Assert.Equal(inputs.Length, map.Count); for (int i = 0; i < inputs.Length; i++) { Assert.True(map.ContainsKey(inputs[i])); } for (int i = 0; i < inputs.Length; i++) { map = map.Remove(inputs[i]); } Assert.Equal(0, map.Count); } protected void AddRemoveEnumerableTestHelper(IImmutableDictionary<int, int> empty) { Contract.Requires(empty != null); Assert.Same(empty, empty.RemoveRange(Enumerable.Empty<int>())); Assert.Same(empty, empty.AddRange(Enumerable.Empty<KeyValuePair<int, int>>())); var list = new List<KeyValuePair<int, int>> { new KeyValuePair<int, int>(3, 5), new KeyValuePair<int, int>(8, 10) }; var nonEmpty = empty.AddRange(list); var halfRemoved = nonEmpty.RemoveRange(Enumerable.Range(1, 5)); Assert.Equal(1, halfRemoved.Count); Assert.True(halfRemoved.ContainsKey(8)); } protected void AddExistingKeySameValueTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value1, TValue value2) { Contract.Requires(map != null); Contract.Requires(key != null); Contract.Requires(GetValueComparer(map).Equals(value1, value2)); map = map.Add(key, value1); Assert.Same(map, map.Add(key, value2)); Assert.Same(map, map.AddRange(new[] { new KeyValuePair<TKey, TValue>(key, value2) })); } /// <summary> /// Verifies that adding a key-value pair where the key already is in the map but with a different value throws. /// </summary> /// <typeparam name="TKey">The type of key in the map.</typeparam> /// <typeparam name="TValue">The type of value in the map.</typeparam> /// <param name="map">The map to manipulate.</param> /// <param name="key">The key to add.</param> /// <param name="value1">The first value to add.</param> /// <param name="value2">The second value to add.</param> /// <remarks> /// Adding a key-value pair to a map where that key already exists, but with a different value, cannot fit the /// semantic of "adding", either by just returning or mutating the value on the existing key. Throwing is the only reasonable response. /// </remarks> protected void AddExistingKeyDifferentValueTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value1, TValue value2) { Contract.Requires(map != null); Contract.Requires(key != null); Contract.Requires(!GetValueComparer(map).Equals(value1, value2)); var map1 = map.Add(key, value1); var map2 = map.Add(key, value2); Assert.Throws<ArgumentException>(() => map1.Add(key, value2)); Assert.Throws<ArgumentException>(() => map2.Add(key, value1)); } protected void ContainsKeyTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value) { Assert.False(map.ContainsKey(key)); Assert.True(map.Add(key, value).ContainsKey(key)); } protected void ContainsTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value) { Assert.False(map.Contains(new KeyValuePair<TKey, TValue>(key, value))); Assert.False(map.Contains(key, value)); Assert.True(map.Add(key, value).Contains(new KeyValuePair<TKey, TValue>(key, value))); Assert.True(map.Add(key, value).Contains(key, value)); } protected void RemoveTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key) { // no-op remove Assert.Same(map, map.Remove(key)); Assert.Same(map, map.RemoveRange(Enumerable.Empty<TKey>())); // substantial remove var addedMap = map.Add(key, default(TValue)); var removedMap = addedMap.Remove(key); Assert.NotSame(addedMap, removedMap); Assert.False(removedMap.ContainsKey(key)); } protected void KeysTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key) { Assert.Equal(0, map.Keys.Count()); Assert.Equal(0, map.ToReadOnlyDictionary().Keys.Count()); var nonEmpty = map.Add(key, default(TValue)); Assert.Equal(1, nonEmpty.Keys.Count()); Assert.Equal(1, nonEmpty.ToReadOnlyDictionary().Keys.Count()); KeysOrValuesTestHelper(((IDictionary<TKey, TValue>)nonEmpty).Keys, key); } protected void ValuesTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key) { Assert.Equal(0, map.Values.Count()); Assert.Equal(0, map.ToReadOnlyDictionary().Values.Count()); var nonEmpty = map.Add(key, default(TValue)); Assert.Equal(1, nonEmpty.Values.Count()); Assert.Equal(1, nonEmpty.ToReadOnlyDictionary().Values.Count()); KeysOrValuesTestHelper(((IDictionary<TKey, TValue>)nonEmpty).Values, default(TValue)); } protected void EnumeratorTestHelper(IImmutableDictionary<int, GenericParameterHelper> map) { for (int i = 0; i < 10; i++) { map = this.AddTestHelper(map, i, new GenericParameterHelper(i)); } int j = 0; foreach (KeyValuePair<int, GenericParameterHelper> pair in map) { Assert.Equal(j, pair.Key); Assert.Equal(j, pair.Value.Data); j++; } var list = map.ToList(); Assert.Equal<KeyValuePair<int, GenericParameterHelper>>(list, ImmutableSetTest.ToListNonGeneric<KeyValuePair<int, GenericParameterHelper>>(map)); // Apply some less common uses to the enumerator to test its metal. using (var enumerator = map.GetEnumerator()) { enumerator.Reset(); // reset isn't usually called before MoveNext ManuallyEnumerateTest(list, enumerator); enumerator.Reset(); ManuallyEnumerateTest(list, enumerator); // this time only partially enumerate enumerator.Reset(); enumerator.MoveNext(); enumerator.Reset(); ManuallyEnumerateTest(list, enumerator); } var manualEnum = map.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => manualEnum.Current); while (manualEnum.MoveNext()) { } Assert.False(manualEnum.MoveNext()); Assert.Throws<InvalidOperationException>(() => manualEnum.Current); } protected abstract IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>(); protected abstract IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer); protected abstract IEqualityComparer<TValue> GetValueComparer<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary); private static void KeysOrValuesTestHelper<T>(ICollection<T> collection, T containedValue) { Requires.NotNull(collection, "collection"); Assert.True(collection.Contains(containedValue)); Assert.Throws<NotSupportedException>(() => collection.Add(default(T))); Assert.Throws<NotSupportedException>(() => collection.Clear()); var nonGeneric = (ICollection)collection; Assert.NotNull(nonGeneric.SyncRoot); Assert.Same(nonGeneric.SyncRoot, nonGeneric.SyncRoot); Assert.True(nonGeneric.IsSynchronized); Assert.True(collection.IsReadOnly); Assert.Throws<ArgumentNullException>(() => nonGeneric.CopyTo(null, 0)); var array = new T[collection.Count + 1]; nonGeneric.CopyTo(array, 1); Assert.Equal(default(T), array[0]); Assert.Equal(array.Skip(1), nonGeneric.Cast<T>().ToArray()); } } }
using System; using Rynchodon.AntennaRelay; using VRage.Game.ModAPI; using VRage.ModAPI; using VRageMath; namespace Rynchodon.Weapons { public static class TargetExtensions { public static bool IsNull(this Target t) { return t == null || t.Entity == null; } } public abstract class Target { public abstract IMyEntity Entity { get; } public abstract TargetType TType { get; } public abstract Vector3D GetPosition(); public abstract Vector3 GetLinearVelocity(); /// <summary>The direction the shot shall be fired in.</summary> public Vector3? FiringDirection { get; set; } /// <summary>The point where contact will be made. For obstruction test, do not point the weapon here!</summary> public Vector3D? ContactPoint { get; set; } } public class NoTarget : Target { public static NoTarget Instance = new NoTarget(); private NoTarget() { } public override IMyEntity Entity { get { return null; } } public override TargetType TType { get { return TargetType.None; } } public override Vector3D GetPosition() { throw new InvalidOperationException(); } public override Vector3 GetLinearVelocity() { throw new InvalidOperationException(); } } public class TurretTarget : Target { private readonly IMyEntity value_entity; private readonly TargetType value_tType; public TurretTarget(IMyEntity target, TargetType tType) { value_entity = target; value_tType = tType; } public override IMyEntity Entity { get { return value_entity; } } public override TargetType TType { get { return value_tType; } } public override Vector3D GetPosition() { return value_entity.GetCentre(); } public override Vector3 GetLinearVelocity() { return value_entity.GetLinearVelocity(); } } public class LastSeenTarget : Target { private LastSeen m_lastSeen; private IMyCubeBlock m_block; private Vector3D m_lastPostion; private TimeSpan m_lastPositionUpdate; private bool m_accel; private TargetType m_targetType; public LastSeenTarget(LastSeen seen, IMyCubeBlock block = null) { m_lastSeen = seen; m_block = block; m_lastPostion = m_lastSeen.LastKnownPosition; m_lastPositionUpdate = m_lastSeen.LastSeenAt; m_targetType = TargetingOptions.GetTargetType(seen.Entity); } public void Update(LastSeen seen, IMyCubeBlock block = null) { Logger.DebugLog("Different entity", Logger.severity.ERROR, condition: seen.Entity != m_lastSeen.Entity); m_lastSeen = seen; if (block != null) m_block = block; m_lastPostion = m_lastSeen.LastKnownPosition; m_lastPositionUpdate = m_lastSeen.LastSeenAt; } public LastSeen LastSeen { get { return m_lastSeen; } } public IMyCubeBlock Block { get { return m_block; } } public override IMyEntity Entity { get { return m_lastSeen.Entity; } } public override TargetType TType { get { return m_targetType; } } public override Vector3D GetPosition() { if (!m_accel && !Entity.Closed && (m_block == null || !m_block.Closed)) { m_accel = Vector3.DistanceSquared(m_lastSeen.Entity.Physics.LinearVelocity, m_lastSeen.LastKnownVelocity) > 1f; if (!m_accel) { m_lastPostion = m_block != null ? m_block.GetPosition() : m_lastSeen.Entity.GetCentre(); m_lastPositionUpdate = Globals.ElapsedTime; return m_lastPostion; } } return m_lastPostion + m_lastSeen.GetLinearVelocity() * (float)(Globals.ElapsedTime - m_lastPositionUpdate).TotalSeconds; } public override Vector3 GetLinearVelocity() { return m_lastSeen.LastKnownVelocity; } } public class SemiActiveTarget : Target { private readonly IMyEntity entity; private Vector3D position; private Vector3 linearVelocity; public SemiActiveTarget(IMyEntity entity) { this.entity = entity; } public void Update(IMyEntity missile) { LineSegment line = new LineSegment(entity.GetPosition(), entity.GetPosition() + entity.WorldMatrix.Forward * 1e6f); position = line.ClosestPoint(missile.GetPosition()) + missile.Physics.LinearVelocity; linearVelocity = entity.WorldMatrix.Forward * missile.Physics.LinearVelocity.Length(); } public override IMyEntity Entity { get { return entity; } } public override TargetType TType { get { return TargetType.AllGrid; } } public override Vector3D GetPosition() { return position; } public override Vector3 GetLinearVelocity() { return linearVelocity; } } public class GolisTarget : Target { private readonly IMyEntity m_entity; private readonly Vector3D m_position; public GolisTarget(IMyEntity entity, Vector3D position) { this.m_entity = entity; this.m_position = position; } public override IMyEntity Entity { get { return m_entity; } } public override TargetType TType { get { return TargetType.AllGrid; } } public override Vector3D GetPosition() { return m_position; } public override Vector3 GetLinearVelocity() { return Vector3.Zero; } } }
// // PKCS7.cs: PKCS #7 - Cryptographic Message Syntax Standard // http://www.rsasecurity.com/rsalabs/pkcs/pkcs-7/index.html // // Authors: // Sebastien Pouliot <[email protected]> // Daniel Granath <dgranath#gmail.com> // // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com) // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Security.Cryptography; using Mono.Security.X509; namespace Mono.Security { internal sealed class PKCS7 { public class Oid { // pkcs 1 public const string rsaEncryption = "1.2.840.113549.1.1.1"; // pkcs 7 public const string data = "1.2.840.113549.1.7.1"; public const string signedData = "1.2.840.113549.1.7.2"; public const string envelopedData = "1.2.840.113549.1.7.3"; public const string signedAndEnvelopedData = "1.2.840.113549.1.7.4"; public const string digestedData = "1.2.840.113549.1.7.5"; public const string encryptedData = "1.2.840.113549.1.7.6"; // pkcs 9 public const string contentType = "1.2.840.113549.1.9.3"; public const string messageDigest = "1.2.840.113549.1.9.4"; public const string signingTime = "1.2.840.113549.1.9.5"; public const string countersignature = "1.2.840.113549.1.9.6"; public Oid () { } } private PKCS7 () { } static public ASN1 Attribute (string oid, ASN1 value) { ASN1 attr = new ASN1 (0x30); attr.Add (ASN1Convert.FromOid (oid)); ASN1 aset = attr.Add (new ASN1 (0x31)); aset.Add (value); return attr; } static public ASN1 AlgorithmIdentifier (string oid) { ASN1 ai = new ASN1 (0x30); ai.Add (ASN1Convert.FromOid (oid)); ai.Add (new ASN1 (0x05)); // NULL return ai; } static public ASN1 AlgorithmIdentifier (string oid, ASN1 parameters) { ASN1 ai = new ASN1 (0x30); ai.Add (ASN1Convert.FromOid (oid)); ai.Add (parameters); return ai; } /* * IssuerAndSerialNumber ::= SEQUENCE { * issuer Name, * serialNumber CertificateSerialNumber * } */ static public ASN1 IssuerAndSerialNumber (X509Certificate x509) { ASN1 issuer = null; ASN1 serial = null; ASN1 cert = new ASN1 (x509.RawData); int tbs = 0; bool flag = false; while (tbs < cert[0].Count) { ASN1 e = cert[0][tbs++]; if (e.Tag == 0x02) serial = e; else if (e.Tag == 0x30) { if (flag) { issuer = e; break; } flag = true; } } ASN1 iasn = new ASN1 (0x30); iasn.Add (issuer); iasn.Add (serial); return iasn; } /* * ContentInfo ::= SEQUENCE { * contentType ContentType, * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL * } * ContentType ::= OBJECT IDENTIFIER */ public class ContentInfo { private string contentType; private ASN1 content; public ContentInfo () { content = new ASN1 (0xA0); } public ContentInfo (string oid) : this () { contentType = oid; } public ContentInfo (byte[] data) : this (new ASN1 (data)) {} public ContentInfo (ASN1 asn1) { // SEQUENCE with 1 or 2 elements if ((asn1.Tag != 0x30) || ((asn1.Count < 1) && (asn1.Count > 2))) throw new ArgumentException ("Invalid ASN1"); if (asn1[0].Tag != 0x06) throw new ArgumentException ("Invalid contentType"); contentType = ASN1Convert.ToOid (asn1[0]); if (asn1.Count > 1) { if (asn1[1].Tag != 0xA0) throw new ArgumentException ("Invalid content"); content = asn1[1]; } } public ASN1 ASN1 { get { return GetASN1(); } } public ASN1 Content { get { return content; } set { content = value; } } public string ContentType { get { return contentType; } set { contentType = value; } } internal ASN1 GetASN1 () { // ContentInfo ::= SEQUENCE { ASN1 contentInfo = new ASN1 (0x30); // contentType ContentType, -> ContentType ::= OBJECT IDENTIFIER contentInfo.Add (ASN1Convert.FromOid (contentType)); // content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL if ((content != null) && (content.Count > 0)) contentInfo.Add (content); return contentInfo; } public byte[] GetBytes () { return GetASN1 ().GetBytes (); } } /* * EncryptedData ::= SEQUENCE { * version INTEGER {edVer0(0)} (edVer0), * encryptedContentInfo EncryptedContentInfo * } */ public class EncryptedData { private byte _version; private ContentInfo _content; private ContentInfo _encryptionAlgorithm; private byte[] _encrypted; public EncryptedData () { _version = 0; } public EncryptedData (byte[] data) : this (new ASN1 (data)) { } public EncryptedData (ASN1 asn1) : this () { if ((asn1.Tag != 0x30) || (asn1.Count < 2)) throw new ArgumentException ("Invalid EncryptedData"); if (asn1 [0].Tag != 0x02) throw new ArgumentException ("Invalid version"); _version = asn1 [0].Value [0]; ASN1 encryptedContentInfo = asn1 [1]; if (encryptedContentInfo.Tag != 0x30) throw new ArgumentException ("missing EncryptedContentInfo"); ASN1 contentType = encryptedContentInfo [0]; if (contentType.Tag != 0x06) throw new ArgumentException ("missing EncryptedContentInfo.ContentType"); _content = new ContentInfo (ASN1Convert.ToOid (contentType)); ASN1 contentEncryptionAlgorithm = encryptedContentInfo [1]; if (contentEncryptionAlgorithm.Tag != 0x30) throw new ArgumentException ("missing EncryptedContentInfo.ContentEncryptionAlgorithmIdentifier"); _encryptionAlgorithm = new ContentInfo (ASN1Convert.ToOid (contentEncryptionAlgorithm [0])); _encryptionAlgorithm.Content = contentEncryptionAlgorithm [1]; ASN1 encryptedContent = encryptedContentInfo [2]; if (encryptedContent.Tag != 0x80) throw new ArgumentException ("missing EncryptedContentInfo.EncryptedContent"); _encrypted = encryptedContent.Value; } public ASN1 ASN1 { get { return GetASN1(); } } public ContentInfo ContentInfo { get { return _content; } } public ContentInfo EncryptionAlgorithm { get { return _encryptionAlgorithm; } } public byte[] EncryptedContent { get { if (_encrypted == null) return null; return (byte[]) _encrypted.Clone (); } } public byte Version { get { return _version; } set { _version = value; } } // methods internal ASN1 GetASN1 () { return null; } public byte[] GetBytes () { return GetASN1 ().GetBytes (); } } /* * EnvelopedData ::= SEQUENCE { * version Version, * recipientInfos RecipientInfos, * encryptedContentInfo EncryptedContentInfo * } * * RecipientInfos ::= SET OF RecipientInfo * * EncryptedContentInfo ::= SEQUENCE { * contentType ContentType, * contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier, * encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL * } * * EncryptedContent ::= OCTET STRING * */ public class EnvelopedData { private byte _version; private ContentInfo _content; private ContentInfo _encryptionAlgorithm; private ArrayList _recipientInfos; private byte[] _encrypted; public EnvelopedData () { _version = 0; _content = new ContentInfo (); _encryptionAlgorithm = new ContentInfo (); _recipientInfos = new ArrayList (); } public EnvelopedData (byte[] data) : this (new ASN1 (data)) { } public EnvelopedData (ASN1 asn1) : this () { if ((asn1[0].Tag != 0x30) || (asn1[0].Count < 3)) throw new ArgumentException ("Invalid EnvelopedData"); if (asn1[0][0].Tag != 0x02) throw new ArgumentException ("Invalid version"); _version = asn1[0][0].Value[0]; // recipientInfos ASN1 recipientInfos = asn1 [0][1]; if (recipientInfos.Tag != 0x31) throw new ArgumentException ("missing RecipientInfos"); for (int i=0; i < recipientInfos.Count; i++) { ASN1 recipientInfo = recipientInfos [i]; _recipientInfos.Add (new RecipientInfo (recipientInfo)); } ASN1 encryptedContentInfo = asn1[0][2]; if (encryptedContentInfo.Tag != 0x30) throw new ArgumentException ("missing EncryptedContentInfo"); ASN1 contentType = encryptedContentInfo [0]; if (contentType.Tag != 0x06) throw new ArgumentException ("missing EncryptedContentInfo.ContentType"); _content = new ContentInfo (ASN1Convert.ToOid (contentType)); ASN1 contentEncryptionAlgorithm = encryptedContentInfo [1]; if (contentEncryptionAlgorithm.Tag != 0x30) throw new ArgumentException ("missing EncryptedContentInfo.ContentEncryptionAlgorithmIdentifier"); _encryptionAlgorithm = new ContentInfo (ASN1Convert.ToOid (contentEncryptionAlgorithm [0])); _encryptionAlgorithm.Content = contentEncryptionAlgorithm [1]; ASN1 encryptedContent = encryptedContentInfo [2]; if (encryptedContent.Tag != 0x80) throw new ArgumentException ("missing EncryptedContentInfo.EncryptedContent"); _encrypted = encryptedContent.Value; } public ArrayList RecipientInfos { get { return _recipientInfos; } } public ASN1 ASN1 { get { return GetASN1(); } } public ContentInfo ContentInfo { get { return _content; } } public ContentInfo EncryptionAlgorithm { get { return _encryptionAlgorithm; } } public byte[] EncryptedContent { get { if (_encrypted == null) return null; return (byte[]) _encrypted.Clone (); } } public byte Version { get { return _version; } set { _version = value; } } internal ASN1 GetASN1 () { // SignedData ::= SEQUENCE { ASN1 signedData = new ASN1 (0x30); // version Version -> Version ::= INTEGER /* byte[] ver = { _version }; signedData.Add (new ASN1 (0x02, ver)); // digestAlgorithms DigestAlgorithmIdentifiers -> DigestAlgorithmIdentifiers ::= SET OF DigestAlgorithmIdentifier ASN1 digestAlgorithms = signedData.Add (new ASN1 (0x31)); if (hashAlgorithm != null) { string hashOid = CryptoConfig.MapNameToOid (hashAlgorithm); digestAlgorithms.Add (AlgorithmIdentifier (hashOid)); } // contentInfo ContentInfo, ASN1 ci = contentInfo.ASN1; signedData.Add (ci); if ((mda == null) && (hashAlgorithm != null)) { // automatically add the messageDigest authenticated attribute HashAlgorithm ha = HashAlgorithm.Create (hashAlgorithm); byte[] idcHash = ha.ComputeHash (ci[1][0].Value); ASN1 md = new ASN1 (0x30); mda = Attribute (messageDigest, md.Add (new ASN1 (0x04, idcHash))); signerInfo.AuthenticatedAttributes.Add (mda); } // certificates [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL, if (certs.Count > 0) { ASN1 a0 = signedData.Add (new ASN1 (0xA0)); foreach (X509Certificate x in certs) a0.Add (new ASN1 (x.RawData)); } // crls [1] IMPLICIT CertificateRevocationLists OPTIONAL, if (crls.Count > 0) { ASN1 a1 = signedData.Add (new ASN1 (0xA1)); foreach (byte[] crl in crls) a1.Add (new ASN1 (crl)); } // signerInfos SignerInfos -> SignerInfos ::= SET OF SignerInfo ASN1 signerInfos = signedData.Add (new ASN1 (0x31)); if (signerInfo.Key != null) signerInfos.Add (signerInfo.ASN1);*/ return signedData; } public byte[] GetBytes () { return GetASN1 ().GetBytes (); } } /* RecipientInfo ::= SEQUENCE { * version Version, * issuerAndSerialNumber IssuerAndSerialNumber, * keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier, * encryptedKey EncryptedKey * } * * KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier * * EncryptedKey ::= OCTET STRING */ public class RecipientInfo { private int _version; private string _oid; private byte[] _key; private byte[] _ski; private string _issuer; private byte[] _serial; public RecipientInfo () {} public RecipientInfo (ASN1 data) { if (data.Tag != 0x30) throw new ArgumentException ("Invalid RecipientInfo"); ASN1 version = data [0]; if (version.Tag != 0x02) throw new ArgumentException ("missing Version"); _version = version.Value [0]; // issuerAndSerialNumber IssuerAndSerialNumber ASN1 subjectIdentifierType = data [1]; if ((subjectIdentifierType.Tag == 0x80) && (_version == 3)) { _ski = subjectIdentifierType.Value; } else { _issuer = X501.ToString (subjectIdentifierType [0]); _serial = subjectIdentifierType [1].Value; } ASN1 keyEncryptionAlgorithm = data [2]; _oid = ASN1Convert.ToOid (keyEncryptionAlgorithm [0]); ASN1 encryptedKey = data [3]; _key = encryptedKey.Value; } public string Oid { get { return _oid; } } public byte[] Key { get { if (_key == null) return null; return (byte[]) _key.Clone (); } } public byte[] SubjectKeyIdentifier { get { if (_ski == null) return null; return (byte[]) _ski.Clone (); } } public string Issuer { get { return _issuer; } } public byte[] Serial { get { if (_serial == null) return null; return (byte[]) _serial.Clone (); } } public int Version { get { return _version; } } } /* * SignedData ::= SEQUENCE { * version Version, * digestAlgorithms DigestAlgorithmIdentifiers, * contentInfo ContentInfo, * certificates [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL, * crls [1] IMPLICIT CertificateRevocationLists OPTIONAL, * signerInfos SignerInfos * } */ public class SignedData { private byte version; private string hashAlgorithm; private ContentInfo contentInfo; private X509CertificateCollection certs; private ArrayList crls; private SignerInfo signerInfo; private bool mda; private bool signed; public SignedData () { version = 1; contentInfo = new ContentInfo (); certs = new X509CertificateCollection (); crls = new ArrayList (); signerInfo = new SignerInfo (); mda = true; signed = false; } public SignedData (byte[] data) : this (new ASN1 (data)) { } public SignedData (ASN1 asn1) { if ((asn1[0].Tag != 0x30) || (asn1[0].Count < 4)) throw new ArgumentException ("Invalid SignedData"); if (asn1[0][0].Tag != 0x02) throw new ArgumentException ("Invalid version"); version = asn1[0][0].Value[0]; contentInfo = new ContentInfo (asn1[0][2]); int n = 3; certs = new X509CertificateCollection (); if (asn1[0][n].Tag == 0xA0) { for (int i=0; i < asn1[0][n].Count; i++) certs.Add (new X509Certificate (asn1[0][n][i].GetBytes ())); n++; } crls = new ArrayList (); if (asn1[0][n].Tag == 0xA1) { for (int i=0; i < asn1[0][n].Count; i++) crls.Add (asn1[0][n][i].GetBytes ()); n++; } if (asn1[0][n].Count > 0) signerInfo = new SignerInfo (asn1[0][n]); else signerInfo = new SignerInfo (); // Exchange hash algorithm Oid from SignerInfo if (signerInfo.HashName != null) { HashName = OidToName(signerInfo.HashName); } // Check if SignerInfo has authenticated attributes mda = (signerInfo.AuthenticatedAttributes.Count > 0); } public ASN1 ASN1 { get { return GetASN1(); } } public X509CertificateCollection Certificates { get { return certs; } } public ContentInfo ContentInfo { get { return contentInfo; } } public ArrayList Crls { get { return crls; } } public string HashName { get { return hashAlgorithm; } // todo add validation set { hashAlgorithm = value; signerInfo.HashName = value; } } public SignerInfo SignerInfo { get { return signerInfo; } } public byte Version { get { return version; } set { version = value; } } public bool UseAuthenticatedAttributes { get { return mda; } set { mda = value; } } public bool VerifySignature (AsymmetricAlgorithm aa) { if (aa == null) { return false; } RSAPKCS1SignatureDeformatter r = new RSAPKCS1SignatureDeformatter (aa); r.SetHashAlgorithm (hashAlgorithm); HashAlgorithm ha = HashAlgorithm.Create (hashAlgorithm); byte[] signature = signerInfo.Signature; byte[] hash = null; if (mda) { ASN1 asn = new ASN1 (0x31); foreach (ASN1 attr in signerInfo.AuthenticatedAttributes) asn.Add (attr); hash = ha.ComputeHash (asn.GetBytes ()); } else { hash = ha.ComputeHash (contentInfo.Content[0].Value); } if (hash != null && signature != null) { return r.VerifySignature (hash, signature); } return false; } internal string OidToName (string oid) { switch (oid) { case "1.3.14.3.2.26" : return "SHA1"; case "1.2.840.113549.2.2" : return "MD2"; case "1.2.840.113549.2.5" : return "MD5"; case "2.16.840.1.101.3.4.1" : return "SHA256"; case "2.16.840.1.101.3.4.2" : return "SHA384"; case "2.16.840.1.101.3.4.3" : return "SHA512"; default : break; } // Unknown Oid return oid; } internal ASN1 GetASN1 () { // SignedData ::= SEQUENCE { ASN1 signedData = new ASN1 (0x30); // version Version -> Version ::= INTEGER byte[] ver = { version }; signedData.Add (new ASN1 (0x02, ver)); // digestAlgorithms DigestAlgorithmIdentifiers -> DigestAlgorithmIdentifiers ::= SET OF DigestAlgorithmIdentifier ASN1 digestAlgorithms = signedData.Add (new ASN1 (0x31)); if (hashAlgorithm != null) { string hashOid = CryptoConfig.MapNameToOID (hashAlgorithm); digestAlgorithms.Add (AlgorithmIdentifier (hashOid)); } // contentInfo ContentInfo, ASN1 ci = contentInfo.ASN1; signedData.Add (ci); if (!signed && (hashAlgorithm != null)) { if (mda) { // Use authenticated attributes for signature // Automatically add the contentType authenticated attribute ASN1 ctattr = Attribute (Oid.contentType, ci[0]); signerInfo.AuthenticatedAttributes.Add (ctattr); // Automatically add the messageDigest authenticated attribute HashAlgorithm ha = HashAlgorithm.Create (hashAlgorithm); byte[] idcHash = ha.ComputeHash (ci[1][0].Value); ASN1 md = new ASN1 (0x30); ASN1 mdattr = Attribute (Oid.messageDigest, md.Add (new ASN1 (0x04, idcHash))); signerInfo.AuthenticatedAttributes.Add (mdattr); } else { // Don't use authenticated attributes for signature -- signature is content RSAPKCS1SignatureFormatter r = new RSAPKCS1SignatureFormatter (signerInfo.Key); r.SetHashAlgorithm (hashAlgorithm); HashAlgorithm ha = HashAlgorithm.Create (hashAlgorithm); byte[] sig = ha.ComputeHash (ci[1][0].Value); signerInfo.Signature = r.CreateSignature (sig); } signed = true; } // certificates [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL, if (certs.Count > 0) { ASN1 a0 = signedData.Add (new ASN1 (0xA0)); foreach (X509Certificate x in certs) a0.Add (new ASN1 (x.RawData)); } // crls [1] IMPLICIT CertificateRevocationLists OPTIONAL, if (crls.Count > 0) { ASN1 a1 = signedData.Add (new ASN1 (0xA1)); foreach (byte[] crl in crls) a1.Add (new ASN1 (crl)); } // signerInfos SignerInfos -> SignerInfos ::= SET OF SignerInfo ASN1 signerInfos = signedData.Add (new ASN1 (0x31)); if (signerInfo.Key != null) signerInfos.Add (signerInfo.ASN1); return signedData; } public byte[] GetBytes () { return GetASN1 ().GetBytes (); } } /* * SignerInfo ::= SEQUENCE { * version Version, * issuerAndSerialNumber IssuerAndSerialNumber, * digestAlgorithm DigestAlgorithmIdentifier, * authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL, * digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier, * encryptedDigest EncryptedDigest, * unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL * } * * For version == 3 issuerAndSerialNumber may be replaced by ... */ public class SignerInfo { private byte version; private X509Certificate x509; private string hashAlgorithm; private AsymmetricAlgorithm key; private ArrayList authenticatedAttributes; private ArrayList unauthenticatedAttributes; private byte[] signature; private string issuer; private byte[] serial; private byte[] ski; public SignerInfo () { version = 1; authenticatedAttributes = new ArrayList (); unauthenticatedAttributes = new ArrayList (); } public SignerInfo (byte[] data) : this (new ASN1 (data)) {} // TODO: INCOMPLETE public SignerInfo (ASN1 asn1) : this () { if ((asn1[0].Tag != 0x30) || (asn1[0].Count < 5)) throw new ArgumentException ("Invalid SignedData"); // version Version if (asn1[0][0].Tag != 0x02) throw new ArgumentException ("Invalid version"); version = asn1[0][0].Value[0]; // issuerAndSerialNumber IssuerAndSerialNumber ASN1 subjectIdentifierType = asn1 [0][1]; if ((subjectIdentifierType.Tag == 0x80) && (version == 3)) { ski = subjectIdentifierType.Value; } else { issuer = X501.ToString (subjectIdentifierType [0]); serial = subjectIdentifierType [1].Value; } // digestAlgorithm DigestAlgorithmIdentifier ASN1 digestAlgorithm = asn1 [0][2]; hashAlgorithm = ASN1Convert.ToOid (digestAlgorithm [0]); // authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL int n = 3; ASN1 authAttributes = asn1 [0][n]; if (authAttributes.Tag == 0xA0) { n++; for (int i=0; i < authAttributes.Count; i++) authenticatedAttributes.Add (authAttributes [i]); } // digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier n++; // ASN1 digestEncryptionAlgorithm = asn1 [0][n++]; // string digestEncryptionAlgorithmOid = ASN1Convert.ToOid (digestEncryptionAlgorithm [0]); // encryptedDigest EncryptedDigest ASN1 encryptedDigest = asn1 [0][n++]; if (encryptedDigest.Tag == 0x04) signature = encryptedDigest.Value; // unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL ASN1 unauthAttributes = asn1 [0][n]; if ((unauthAttributes != null) && (unauthAttributes.Tag == 0xA1)) { for (int i=0; i < unauthAttributes.Count; i++) unauthenticatedAttributes.Add (unauthAttributes [i]); } } public string IssuerName { get { return issuer; } } public byte[] SerialNumber { get { if (serial == null) return null; return (byte[]) serial.Clone (); } } public byte[] SubjectKeyIdentifier { get { if (ski == null) return null; return (byte[]) ski.Clone (); } } public ASN1 ASN1 { get { return GetASN1(); } } public ArrayList AuthenticatedAttributes { get { return authenticatedAttributes; } } public X509Certificate Certificate { get { return x509; } set { x509 = value; } } public string HashName { get { return hashAlgorithm; } set { hashAlgorithm = value; } } public AsymmetricAlgorithm Key { get { return key; } set { key = value; } } public byte[] Signature { get { if (signature == null) return null; return (byte[]) signature.Clone (); } set { if (value != null) { signature = (byte[]) value.Clone (); } } } public ArrayList UnauthenticatedAttributes { get { return unauthenticatedAttributes; } } public byte Version { get { return version; } set { version = value; } } internal ASN1 GetASN1 () { if ((key == null) || (hashAlgorithm == null)) return null; byte[] ver = { version }; ASN1 signerInfo = new ASN1 (0x30); // version Version -> Version ::= INTEGER signerInfo.Add (new ASN1 (0x02, ver)); // issuerAndSerialNumber IssuerAndSerialNumber, signerInfo.Add (PKCS7.IssuerAndSerialNumber (x509)); // digestAlgorithm DigestAlgorithmIdentifier, string hashOid = CryptoConfig.MapNameToOID (hashAlgorithm); signerInfo.Add (AlgorithmIdentifier (hashOid)); // authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL, ASN1 aa = null; if (authenticatedAttributes.Count > 0) { aa = signerInfo.Add (new ASN1 (0xA0)); authenticatedAttributes.Sort(new SortedSet ()); foreach (ASN1 attr in authenticatedAttributes) aa.Add (attr); } // digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier, if (key is RSA) { signerInfo.Add (AlgorithmIdentifier (PKCS7.Oid.rsaEncryption)); if (aa != null) { // Calculate the signature here; otherwise it must be set from SignedData RSAPKCS1SignatureFormatter r = new RSAPKCS1SignatureFormatter (key); r.SetHashAlgorithm (hashAlgorithm); byte[] tbs = aa.GetBytes (); tbs [0] = 0x31; // not 0xA0 for signature HashAlgorithm ha = HashAlgorithm.Create (hashAlgorithm); byte[] tbsHash = ha.ComputeHash (tbs); signature = r.CreateSignature (tbsHash); } } else if (key is DSA) { throw new NotImplementedException ("not yet"); } else throw new CryptographicException ("Unknown assymetric algorithm"); // encryptedDigest EncryptedDigest, signerInfo.Add (new ASN1 (0x04, signature)); // unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL if (unauthenticatedAttributes.Count > 0) { ASN1 ua = signerInfo.Add (new ASN1 (0xA1)); unauthenticatedAttributes.Sort(new SortedSet ()); foreach (ASN1 attr in unauthenticatedAttributes) ua.Add (attr); } return signerInfo; } public byte[] GetBytes () { return GetASN1 ().GetBytes (); } } internal class SortedSet : IComparer { public int Compare (object x, object y) { if (x == null) return (y == null) ? 0 : -1; else if (y == null) return 1; ASN1 xx = x as ASN1; ASN1 yy = y as ASN1; if ((xx == null) || (yy == null)) { throw new ArgumentException (Locale.GetText ("Invalid objects.")); } byte[] xb = xx.GetBytes (); byte[] yb = yy.GetBytes (); for (int i = 0; i < xb.Length; i++) { if (i == yb.Length) break; if (xb[i] == yb[i]) continue; return (xb[i] < yb[i]) ? -1 : 1; } // The arrays are equal up to the shortest of them. if (xb.Length > yb.Length) return 1; else if (xb.Length < yb.Length) return -1; return 0; } } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using System.Runtime.Serialization; using System.Text; using System.Xml; #if NETFX_CORE using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #elif DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; #endif using Newtonsoft.Json; using System.IO; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Tests { [TestFixture] public class JsonTextWriterTest : TestFixtureBase { [Test] public void NewLine() { MemoryStream ms = new MemoryStream(); using (var streamWriter = new StreamWriter(ms, new UTF8Encoding(false)) { NewLine = "\n" }) using (var jsonWriter = new JsonTextWriter(streamWriter) { CloseOutput = true, Indentation = 2, Formatting = Formatting.Indented }) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("prop"); jsonWriter.WriteValue(true); jsonWriter.WriteEndObject(); } byte[] data = ms.ToArray(); string json = Encoding.UTF8.GetString(data, 0, data.Length); Assert.AreEqual(@"{" + '\n' + @" ""prop"": true" + '\n' + "}", json); } [Test] public void QuoteNameAndStrings() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); JsonTextWriter writer = new JsonTextWriter(sw) { QuoteName = false }; writer.WriteStartObject(); writer.WritePropertyName("name"); writer.WriteValue("value"); writer.WriteEndObject(); writer.Flush(); Assert.AreEqual(@"{name:""value""}", sb.ToString()); } [Test] public void CloseOutput() { MemoryStream ms = new MemoryStream(); JsonTextWriter writer = new JsonTextWriter(new StreamWriter(ms)); Assert.IsTrue(ms.CanRead); writer.Close(); Assert.IsFalse(ms.CanRead); ms = new MemoryStream(); writer = new JsonTextWriter(new StreamWriter(ms)) { CloseOutput = false }; Assert.IsTrue(ms.CanRead); writer.Close(); Assert.IsTrue(ms.CanRead); } #if !(PORTABLE || DNXCORE50 || NETFX_CORE) [Test] public void WriteIConvertable() { var sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteValue(new ConvertibleInt(1)); Assert.AreEqual("1", sw.ToString()); } #endif [Test] public void ValueFormatting() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue('@'); jsonWriter.WriteValue("\r\n\t\f\b?{\\r\\n\"\'"); jsonWriter.WriteValue(true); jsonWriter.WriteValue(10); jsonWriter.WriteValue(10.99); jsonWriter.WriteValue(0.99); jsonWriter.WriteValue(0.000000000000000001d); jsonWriter.WriteValue(0.000000000000000001m); jsonWriter.WriteValue((string)null); jsonWriter.WriteValue((object)null); jsonWriter.WriteValue("This is a string."); jsonWriter.WriteNull(); jsonWriter.WriteUndefined(); jsonWriter.WriteEndArray(); } string expected = @"[""@"",""\r\n\t\f\b?{\\r\\n\""'"",true,10,10.99,0.99,1E-18,0.000000000000000001,null,null,""This is a string."",null,undefined]"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void NullableValueFormatting() { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue((char?)null); jsonWriter.WriteValue((char?)'c'); jsonWriter.WriteValue((bool?)null); jsonWriter.WriteValue((bool?)true); jsonWriter.WriteValue((byte?)null); jsonWriter.WriteValue((byte?)1); jsonWriter.WriteValue((sbyte?)null); jsonWriter.WriteValue((sbyte?)1); jsonWriter.WriteValue((short?)null); jsonWriter.WriteValue((short?)1); jsonWriter.WriteValue((ushort?)null); jsonWriter.WriteValue((ushort?)1); jsonWriter.WriteValue((int?)null); jsonWriter.WriteValue((int?)1); jsonWriter.WriteValue((uint?)null); jsonWriter.WriteValue((uint?)1); jsonWriter.WriteValue((long?)null); jsonWriter.WriteValue((long?)1); jsonWriter.WriteValue((ulong?)null); jsonWriter.WriteValue((ulong?)1); jsonWriter.WriteValue((double?)null); jsonWriter.WriteValue((double?)1.1); jsonWriter.WriteValue((float?)null); jsonWriter.WriteValue((float?)1.1); jsonWriter.WriteValue((decimal?)null); jsonWriter.WriteValue((decimal?)1.1m); jsonWriter.WriteValue((DateTime?)null); jsonWriter.WriteValue((DateTime?)new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc)); #if !NET20 jsonWriter.WriteValue((DateTimeOffset?)null); jsonWriter.WriteValue((DateTimeOffset?)new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero)); #endif jsonWriter.WriteEndArray(); } string json = sw.ToString(); string expected; #if !NET20 expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""1970-01-01T00:00:00Z"",null,""1970-01-01T00:00:00+00:00""]"; #else expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""1970-01-01T00:00:00Z""]"; #endif Assert.AreEqual(expected, json); } [Test] public void WriteValueObjectWithNullable() { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { char? value = 'c'; jsonWriter.WriteStartArray(); jsonWriter.WriteValue((object)value); jsonWriter.WriteEndArray(); } string json = sw.ToString(); string expected = @"[""c""]"; Assert.AreEqual(expected, json); } [Test] public void WriteValueObjectWithUnsupportedValue() { ExceptionAssert.Throws<JsonWriterException>(() => { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(new Version(1, 1, 1, 1)); jsonWriter.WriteEndArray(); } }, @"Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation. Path ''."); } [Test] public void StringEscaping() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(@"""These pretzels are making me thirsty!"""); jsonWriter.WriteValue("Jeff's house was burninated."); jsonWriter.WriteValue("1. You don't talk about fight club.\r\n2. You don't talk about fight club."); jsonWriter.WriteValue("35% of\t statistics\n are made\r up."); jsonWriter.WriteEndArray(); } string expected = @"[""\""These pretzels are making me thirsty!\"""",""Jeff's house was burninated."",""1. You don't talk about fight club.\r\n2. You don't talk about fight club."",""35% of\t statistics\n are made\r up.""]"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void WriteEnd() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.WriteEndObject(); Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void CloseWithRemainingContent() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.Close(); } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void Indenting() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.WriteEnd(); jsonWriter.WriteEndObject(); Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); } // { // "CPU": "Intel", // "PSU": "500W", // "Drives": [ // "DVD read/writer" // /*(broken)*/, // "500 gigabyte hard drive", // "200 gigabype hard drive" // ] // } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void State() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); jsonWriter.WriteStartObject(); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual("", jsonWriter.Path); jsonWriter.WritePropertyName("CPU"); Assert.AreEqual(WriteState.Property, jsonWriter.WriteState); Assert.AreEqual("CPU", jsonWriter.Path); jsonWriter.WriteValue("Intel"); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual("CPU", jsonWriter.Path); jsonWriter.WritePropertyName("Drives"); Assert.AreEqual(WriteState.Property, jsonWriter.WriteState); Assert.AreEqual("Drives", jsonWriter.Path); jsonWriter.WriteStartArray(); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); jsonWriter.WriteValue("DVD read/writer"); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); Assert.AreEqual("Drives[0]", jsonWriter.Path); jsonWriter.WriteEnd(); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual("Drives", jsonWriter.Path); jsonWriter.WriteEndObject(); Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); Assert.AreEqual("", jsonWriter.Path); } } [Test] public void FloatingPointNonFiniteNumbers_Symbol() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ NaN, Infinity, -Infinity, NaN, Infinity, -Infinity ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void FloatingPointNonFiniteNumbers_Zero() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.DefaultValue; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteValue((double?)double.NaN); jsonWriter.WriteValue((double?)double.PositiveInfinity); jsonWriter.WriteValue((double?)double.NegativeInfinity); jsonWriter.WriteValue((float?)float.NaN); jsonWriter.WriteValue((float?)float.PositiveInfinity); jsonWriter.WriteValue((float?)float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, null, null, null, null, null, null ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void FloatingPointNonFiniteNumbers_String() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.String; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ ""NaN"", ""Infinity"", ""-Infinity"", ""NaN"", ""Infinity"", ""-Infinity"" ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void FloatingPointNonFiniteNumbers_QuoteChar() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.String; jsonWriter.QuoteChar = '\''; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ 'NaN', 'Infinity', '-Infinity', 'NaN', 'Infinity', '-Infinity' ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteRawInStart() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteRaw("[1,2,3,4,5]"); jsonWriter.WriteWhitespace(" "); jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteEndArray(); } string expected = @"[1,2,3,4,5] [ NaN ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteRawInArray() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteRaw(",[1,2,3,4,5]"); jsonWriter.WriteRaw(",[1,2,3,4,5]"); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteEndArray(); } string expected = @"[ NaN,[1,2,3,4,5],[1,2,3,4,5], NaN ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteRawInObject() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WriteRaw(@"""PropertyName"":[1,2,3,4,5]"); jsonWriter.WriteEnd(); } string expected = @"{""PropertyName"":[1,2,3,4,5]}"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void WriteToken() { JsonTextReader reader = new JsonTextReader(new StringReader("[1,2,3,4,5]")); reader.Read(); reader.Read(); StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteToken(reader); Assert.AreEqual("1", sw.ToString()); } [Test] public void WriteRawValue() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { int i = 0; string rawJson = "[1,2]"; jsonWriter.WriteStartObject(); while (i < 3) { jsonWriter.WritePropertyName("d" + i); jsonWriter.WriteRawValue(rawJson); i++; } jsonWriter.WriteEndObject(); } Assert.AreEqual(@"{""d0"":[1,2],""d1"":[1,2],""d2"":[1,2]}", sb.ToString()); } [Test] public void WriteObjectNestedInConstructor() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("con"); jsonWriter.WriteStartConstructor("Ext.data.JsonStore"); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("aa"); jsonWriter.WriteValue("aa"); jsonWriter.WriteEndObject(); jsonWriter.WriteEndConstructor(); jsonWriter.WriteEndObject(); } Assert.AreEqual(@"{""con"":new Ext.data.JsonStore({""aa"":""aa""})}", sb.ToString()); } [Test] public void WriteFloatingPointNumber() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(0.0); jsonWriter.WriteValue(0f); jsonWriter.WriteValue(0.1); jsonWriter.WriteValue(1.0); jsonWriter.WriteValue(1.000001); jsonWriter.WriteValue(0.000001); jsonWriter.WriteValue(double.Epsilon); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.MaxValue); jsonWriter.WriteValue(double.MinValue); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteEndArray(); } Assert.AreEqual(@"[0.0,0.0,0.1,1.0,1.000001,1E-06,4.94065645841247E-324,Infinity,-Infinity,NaN,1.7976931348623157E+308,-1.7976931348623157E+308,Infinity,-Infinity,NaN]", sb.ToString()); } [Test] public void WriteIntegerNumber() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw) { Formatting = Formatting.Indented }) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(int.MaxValue); jsonWriter.WriteValue(int.MinValue); jsonWriter.WriteValue(0); jsonWriter.WriteValue(-0); jsonWriter.WriteValue(9L); jsonWriter.WriteValue(9UL); jsonWriter.WriteValue(long.MaxValue); jsonWriter.WriteValue(long.MinValue); jsonWriter.WriteValue(ulong.MaxValue); jsonWriter.WriteValue(ulong.MinValue); jsonWriter.WriteEndArray(); } Console.WriteLine(sb.ToString()); StringAssert.AreEqual(@"[ 2147483647, -2147483648, 0, 0, 9, 9, 9223372036854775807, -9223372036854775808, 18446744073709551615, 0 ]", sb.ToString()); } [Test] public void WriteTokenDirect() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteToken(JsonToken.StartArray); jsonWriter.WriteToken(JsonToken.Integer, 1); jsonWriter.WriteToken(JsonToken.StartObject); jsonWriter.WriteToken(JsonToken.PropertyName, "string"); jsonWriter.WriteToken(JsonToken.Integer, int.MaxValue); jsonWriter.WriteToken(JsonToken.EndObject); jsonWriter.WriteToken(JsonToken.EndArray); } Assert.AreEqual(@"[1,{""string"":2147483647}]", sb.ToString()); } [Test] public void WriteTokenDirect_BadValue() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteToken(JsonToken.StartArray); ExceptionAssert.Throws<FormatException>(() => { jsonWriter.WriteToken(JsonToken.Integer, "three"); }, "Input string was not in a correct format."); ExceptionAssert.Throws<ArgumentNullException>(() => { jsonWriter.WriteToken(JsonToken.Integer); }, @"Value cannot be null. Parameter name: value"); } } [Test] public void BadWriteEndArray() { ExceptionAssert.Throws<JsonWriterException>(() => { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(0.0); jsonWriter.WriteEndArray(); jsonWriter.WriteEndArray(); } }, "No token to close. Path ''."); } [Test] public void InvalidQuoteChar() { ExceptionAssert.Throws<ArgumentException>(() => { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.QuoteChar = '*'; } }, @"Invalid JavaScript string quote character. Valid quote characters are ' and ""."); } [Test] public void Indentation() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting); jsonWriter.Indentation = 5; Assert.AreEqual(5, jsonWriter.Indentation); jsonWriter.IndentChar = '_'; Assert.AreEqual('_', jsonWriter.IndentChar); jsonWriter.QuoteName = true; Assert.AreEqual(true, jsonWriter.QuoteName); jsonWriter.QuoteChar = '\''; Assert.AreEqual('\'', jsonWriter.QuoteChar); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("propertyName"); jsonWriter.WriteValue(double.NaN); jsonWriter.IndentChar = '?'; Assert.AreEqual('?', jsonWriter.IndentChar); jsonWriter.Indentation = 6; Assert.AreEqual(6, jsonWriter.Indentation); jsonWriter.WritePropertyName("prop2"); jsonWriter.WriteValue(123); jsonWriter.WriteEndObject(); } string expected = @"{ _____'propertyName': NaN, ??????'prop2': 123 }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteSingleBytes() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting); jsonWriter.WriteValue(data); } string expected = @"""SGVsbG8gd29ybGQu"""; string result = sb.ToString(); Assert.AreEqual(expected, result); byte[] d2 = Convert.FromBase64String(result.Trim('"')); Assert.AreEqual(text, Encoding.UTF8.GetString(d2, 0, d2.Length)); } [Test] public void WriteBytesInArray() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting); jsonWriter.WriteStartArray(); jsonWriter.WriteValue(data); jsonWriter.WriteValue(data); jsonWriter.WriteValue((object)data); jsonWriter.WriteValue((byte[])null); jsonWriter.WriteValue((Uri)null); jsonWriter.WriteEndArray(); } string expected = @"[ ""SGVsbG8gd29ybGQu"", ""SGVsbG8gd29ybGQu"", ""SGVsbG8gd29ybGQu"", null, null ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void Path() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter writer = new JsonTextWriter(sw)) { writer.Formatting = Formatting.Indented; writer.WriteStartArray(); Assert.AreEqual("", writer.Path); writer.WriteStartObject(); Assert.AreEqual("[0]", writer.Path); writer.WritePropertyName("Property1"); Assert.AreEqual("[0].Property1", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1", writer.Path); writer.WriteValue(1); Assert.AreEqual("[0].Property1[0]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1[1]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1[1][0]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1[1][0][0]", writer.Path); writer.WriteEndObject(); Assert.AreEqual("[0]", writer.Path); writer.WriteStartObject(); Assert.AreEqual("[1]", writer.Path); writer.WritePropertyName("Property2"); Assert.AreEqual("[1].Property2", writer.Path); writer.WriteStartConstructor("Constructor1"); Assert.AreEqual("[1].Property2", writer.Path); writer.WriteNull(); Assert.AreEqual("[1].Property2[0]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[1].Property2[1]", writer.Path); writer.WriteValue(1); Assert.AreEqual("[1].Property2[1][0]", writer.Path); writer.WriteEnd(); Assert.AreEqual("[1].Property2[1]", writer.Path); writer.WriteEndObject(); Assert.AreEqual("[1]", writer.Path); writer.WriteEndArray(); Assert.AreEqual("", writer.Path); } StringAssert.AreEqual(@"[ { ""Property1"": [ 1, [ [ [] ] ] ] }, { ""Property2"": new Constructor1( null, [ 1 ] ) } ]", sb.ToString()); } [Test] public void BuildStateArray() { JsonWriter.State[][] stateArray = JsonWriter.BuildStateArray(); var valueStates = JsonWriter.StateArrayTempate[7]; foreach (JsonToken valueToken in EnumUtils.GetValues(typeof(JsonToken))) { switch (valueToken) { case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Undefined: case JsonToken.Date: case JsonToken.Bytes: Assert.AreEqual(valueStates, stateArray[(int)valueToken], "Error for " + valueToken + " states."); break; } } } [Test] public void DateTimeZoneHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { DateTimeZoneHandling = Json.DateTimeZoneHandling.Utc }; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified)); Assert.AreEqual(@"""2000-01-01T01:01:01Z""", sw.ToString()); } [Test] public void HtmlStringEscapeHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.EscapeHtml }; string script = @"<script type=""text/javascript"">alert('hi');</script>"; writer.WriteValue(script); string json = sw.ToString(); Assert.AreEqual(@"""\u003cscript type=\u0022text/javascript\u0022\u003ealert(\u0027hi\u0027);\u003c/script\u003e""", json); JsonTextReader reader = new JsonTextReader(new StringReader(json)); Assert.AreEqual(script, reader.ReadAsString()); } [Test] public void NonAsciiStringEscapeHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.EscapeNonAscii }; string unicode = "\u5f20"; writer.WriteValue(unicode); string json = sw.ToString(); Assert.AreEqual(8, json.Length); Assert.AreEqual(@"""\u5f20""", json); JsonTextReader reader = new JsonTextReader(new StringReader(json)); Assert.AreEqual(unicode, reader.ReadAsString()); sw = new StringWriter(); writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.Default }; writer.WriteValue(unicode); json = sw.ToString(); Assert.AreEqual(3, json.Length); Assert.AreEqual("\"\u5f20\"", json); } [Test] public void WriteEndOnProperty() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.QuoteChar = '\''; writer.WriteStartObject(); writer.WritePropertyName("Blah"); writer.WriteEnd(); Assert.AreEqual("{'Blah':null}", sw.ToString()); } #if !NET20 [Test] public void QuoteChar() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.Formatting = Formatting.Indented; writer.QuoteChar = '\''; writer.WriteStartArray(); writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.DateFormatString = "yyyy gg"; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.WriteValue(new byte[] { 1, 2, 3 }); writer.WriteValue(TimeSpan.Zero); writer.WriteValue(new Uri("http://www.google.com/")); writer.WriteValue(Guid.Empty); writer.WriteEnd(); StringAssert.AreEqual(@"[ '2000-01-01T01:01:01Z', '2000-01-01T01:01:01+00:00', '\/Date(946688461000)\/', '\/Date(946688461000+0000)\/', '2000 A.D.', '2000 A.D.', 'AQID', '00:00:00', 'http://www.google.com/', '00000000-0000-0000-0000-000000000000' ]", sw.ToString()); } [Test] public void Culture() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.Formatting = Formatting.Indented; writer.DateFormatString = "yyyy tt"; writer.Culture = new CultureInfo("en-NZ"); writer.QuoteChar = '\''; writer.WriteStartArray(); writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.WriteEnd(); StringAssert.AreEqual(@"[ '2000 a.m.', '2000 a.m.' ]", sw.ToString()); } #endif [Test] public void CompareNewStringEscapingWithOld() { char c = (char)0; do { StringWriter swNew = new StringWriter(); char[] buffer = null; JavaScriptUtils.WriteEscapedJavaScriptString(swNew, c.ToString(), '"', true, JavaScriptUtils.DoubleQuoteCharEscapeFlags, StringEscapeHandling.Default, ref buffer); StringWriter swOld = new StringWriter(); WriteEscapedJavaScriptStringOld(swOld, c.ToString(), '"', true); string newText = swNew.ToString(); string oldText = swOld.ToString(); if (newText != oldText) throw new Exception("Difference for char '{0}' (value {1}). Old text: {2}, New text: {3}".FormatWith(CultureInfo.InvariantCulture, c, (int)c, oldText, newText)); c++; } while (c != char.MaxValue); } private const string EscapedUnicodeText = "!"; private static void WriteEscapedJavaScriptStringOld(TextWriter writer, string s, char delimiter, bool appendDelimiters) { // leading delimiter if (appendDelimiters) writer.Write(delimiter); if (s != null) { char[] chars = null; char[] unicodeBuffer = null; int lastWritePosition = 0; for (int i = 0; i < s.Length; i++) { var c = s[i]; // don't escape standard text/numbers except '\' and the text delimiter if (c >= ' ' && c < 128 && c != '\\' && c != delimiter) continue; string escapedValue; switch (c) { case '\t': escapedValue = @"\t"; break; case '\n': escapedValue = @"\n"; break; case '\r': escapedValue = @"\r"; break; case '\f': escapedValue = @"\f"; break; case '\b': escapedValue = @"\b"; break; case '\\': escapedValue = @"\\"; break; case '\u0085': // Next Line escapedValue = @"\u0085"; break; case '\u2028': // Line Separator escapedValue = @"\u2028"; break; case '\u2029': // Paragraph Separator escapedValue = @"\u2029"; break; case '\'': // this charater is being used as the delimiter escapedValue = @"\'"; break; case '"': // this charater is being used as the delimiter escapedValue = "\\\""; break; default: if (c <= '\u001f') { if (unicodeBuffer == null) unicodeBuffer = new char[6]; StringUtils.ToCharAsUnicode(c, unicodeBuffer); // slightly hacky but it saves multiple conditions in if test escapedValue = EscapedUnicodeText; } else { escapedValue = null; } break; } if (escapedValue == null) continue; if (i > lastWritePosition) { if (chars == null) chars = s.ToCharArray(); // write unchanged chars before writing escaped text writer.Write(chars, lastWritePosition, i - lastWritePosition); } lastWritePosition = i + 1; if (!string.Equals(escapedValue, EscapedUnicodeText)) writer.Write(escapedValue); else writer.Write(unicodeBuffer); } if (lastWritePosition == 0) { // no escaped text, write entire string writer.Write(s); } else { if (chars == null) chars = s.ToCharArray(); // write remaining text writer.Write(chars, lastWritePosition, s.Length - lastWritePosition); } } // trailing delimiter if (appendDelimiters) writer.Write(delimiter); } [Test] public void CustomJsonTextWriterTests() { StringWriter sw = new StringWriter(); CustomJsonTextWriter writer = new CustomJsonTextWriter(sw) { Formatting = Formatting.Indented }; writer.WriteStartObject(); Assert.AreEqual(WriteState.Object, writer.WriteState); writer.WritePropertyName("Property1"); Assert.AreEqual(WriteState.Property, writer.WriteState); Assert.AreEqual("Property1", writer.Path); writer.WriteNull(); Assert.AreEqual(WriteState.Object, writer.WriteState); writer.WriteEndObject(); Assert.AreEqual(WriteState.Start, writer.WriteState); StringAssert.AreEqual(@"{{{ ""1ytreporP"": NULL!!! }}}", sw.ToString()); } [Test] public void QuoteDictionaryNames() { var d = new Dictionary<string, int> { { "a", 1 }, }; var jsonSerializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, }; var serializer = JsonSerializer.Create(jsonSerializerSettings); using (var stringWriter = new StringWriter()) { using (var writer = new JsonTextWriter(stringWriter) { QuoteName = false }) { serializer.Serialize(writer, d); writer.Close(); } StringAssert.AreEqual(@"{ a: 1 }", stringWriter.ToString()); } } [Test] public void WriteComments() { string json = @"//comment*//*hi*/ {//comment Name://comment true//comment after true" + StringUtils.CarriageReturn + @" ,//comment after comma" + StringUtils.CarriageReturnLineFeed + @" ""ExpiryDate""://comment" + StringUtils.LineFeed + @" new " + StringUtils.LineFeed + @"Constructor (//comment null//comment ), ""Price"": 3.99, ""Sizes"": //comment [//comment ""Small""//comment ]//comment }//comment //comment 1 "; JsonTextReader r = new JsonTextReader(new StringReader(json)); StringWriter sw = new StringWriter(); JsonTextWriter w = new JsonTextWriter(sw); w.Formatting = Formatting.Indented; w.WriteToken(r, true); StringAssert.AreEqual(@"/*comment*//*hi*/*/{/*comment*/ ""Name"": /*comment*/ true/*comment after true*//*comment after comma*/, ""ExpiryDate"": /*comment*/ new Constructor( /*comment*/, null /*comment*/ ), ""Price"": 3.99, ""Sizes"": /*comment*/ [ /*comment*/ ""Small"" /*comment*/ ]/*comment*/ }/*comment *//*comment 1 */", sw.ToString()); } } public class CustomJsonTextWriter : JsonTextWriter { private readonly TextWriter _writer; public CustomJsonTextWriter(TextWriter textWriter) : base(textWriter) { _writer = textWriter; } public override void WritePropertyName(string name) { WritePropertyName(name, true); } public override void WritePropertyName(string name, bool escape) { SetWriteState(JsonToken.PropertyName, name); if (QuoteName) _writer.Write(QuoteChar); _writer.Write(new string(name.ToCharArray().Reverse().ToArray())); if (QuoteName) _writer.Write(QuoteChar); _writer.Write(':'); } public override void WriteNull() { SetWriteState(JsonToken.Null, null); _writer.Write("NULL!!!"); } public override void WriteStartObject() { SetWriteState(JsonToken.StartObject, null); _writer.Write("{{{"); } public override void WriteEndObject() { SetWriteState(JsonToken.EndObject, null); } protected override void WriteEnd(JsonToken token) { if (token == JsonToken.EndObject) _writer.Write("}}}"); else base.WriteEnd(token); } } #if !(PORTABLE || DNXCORE50 || NETFX_CORE) public struct ConvertibleInt : IConvertible { private readonly int _value; public ConvertibleInt(int value) { _value = value; } public TypeCode GetTypeCode() { return TypeCode.Int32; } public bool ToBoolean(IFormatProvider provider) { throw new NotImplementedException(); } public byte ToByte(IFormatProvider provider) { throw new NotImplementedException(); } public char ToChar(IFormatProvider provider) { throw new NotImplementedException(); } public DateTime ToDateTime(IFormatProvider provider) { throw new NotImplementedException(); } public decimal ToDecimal(IFormatProvider provider) { throw new NotImplementedException(); } public double ToDouble(IFormatProvider provider) { throw new NotImplementedException(); } public short ToInt16(IFormatProvider provider) { throw new NotImplementedException(); } public int ToInt32(IFormatProvider provider) { throw new NotImplementedException(); } public long ToInt64(IFormatProvider provider) { throw new NotImplementedException(); } public sbyte ToSByte(IFormatProvider provider) { throw new NotImplementedException(); } public float ToSingle(IFormatProvider provider) { throw new NotImplementedException(); } public string ToString(IFormatProvider provider) { throw new NotImplementedException(); } public object ToType(Type conversionType, IFormatProvider provider) { if (conversionType == typeof(int)) return _value; throw new Exception("Type not supported: " + conversionType.FullName); } public ushort ToUInt16(IFormatProvider provider) { throw new NotImplementedException(); } public uint ToUInt32(IFormatProvider provider) { throw new NotImplementedException(); } public ulong ToUInt64(IFormatProvider provider) { throw new NotImplementedException(); } } #endif }
using UnityEngine; using System.Collections.Generic; using UMA.CharacterSystem; namespace UMA { /// <summary> /// Gloal container for various UMA objects in the scene. Marked as partial so the developer can add to this if necessary /// </summary> public abstract class UMAContextBase : MonoBehaviour { public static string IgnoreTag; private static UMAContextBase _instance; public static UMAContextBase Instance { get { if (_instance == null) { _instance = GameObject.FindObjectOfType<UMAContextBase>(); } return _instance; } set { _instance = value; } } #pragma warning disable 618 public abstract void Start(); /// <summary> /// Validates the library contents. /// </summary> public abstract void ValidateDictionaries(); /// <summary> /// Gets a race by name, if it has been added to the library /// </summary> /// <returns>The race.</returns> /// <param name="name">Name.</param> public abstract RaceData HasRace(string name); /// <summary> /// Gets a race by name hash, if it has been added to the library. /// </summary> /// <returns>The race.</returns> /// <param name="nameHash">Name hash.</param> public abstract RaceData HasRace(int nameHash); /// <summary> /// Ensure we have a race key /// </summary> /// <param name="name"></param> public abstract void EnsureRaceKey(string name); /// <summary> /// Gets a race by name, if the library is a DynamicRaceLibrary it will try to find it. /// </summary> /// <returns>The race.</returns> /// <param name="name">Name.</param> public abstract RaceData GetRace(string name); /// <summary> /// Gets a race by name hash, if the library is a DynamicRaceLibrary it will try to find it. /// </summary> /// <returns>The race.</returns> /// <param name="nameHash">Name hash.</param> public abstract RaceData GetRace(int nameHash); /// <summary> /// Get a race by name hash. possibly allowing updates. /// </summary> /// <param name="nameHash"></param> /// <param name="allowUpdate"></param> /// <returns></returns> public abstract RaceData GetRaceWithUpdate(int nameHash, bool allowUpdate); /// <summary> /// Array of all races in the context. /// </summary> /// <returns>The array of race data.</returns> public abstract RaceData[] GetAllRaces(); /// <summary> /// return races with no download /// </summary> /// <returns></returns> public abstract RaceData[] GetAllRacesBase(); /// <summary> /// Add a race to the context. /// </summary> /// <param name="race">New race.</param> public abstract void AddRace(RaceData race); /// <summary> /// Instantiate a slot by name. /// </summary> /// <returns>The slot.</returns> /// <param name="name">Name.</param> public abstract SlotData InstantiateSlot(string name); /// <summary> /// Instantiate a slot by name hash. /// </summary> /// <returns>The slot.</returns> /// <param name="nameHash">Name hash.</param> public abstract SlotData InstantiateSlot(int nameHash); /// <summary> /// Instantiate a slot by name, with overlays. /// </summary> /// <returns>The slot.</returns> /// <param name="name">Name.</param> /// <param name="overlayList">Overlay list.</param> public abstract SlotData InstantiateSlot(string name, List<OverlayData> overlayList); /// <summary> /// Instantiate a slot by name hash, with overlays. /// </summary> /// <returns>The slot.</returns> /// <param name="nameHash">Name hash.</param> /// <param name="overlayList">Overlay list.</param> public abstract SlotData InstantiateSlot(int nameHash, List<OverlayData> overlayList); /// <summary> /// Check for presence of a slot by name. /// </summary> /// <returns><c>True</c> if the slot exists in this context.</returns> /// <param name="name">Name.</param> public abstract bool HasSlot(string name); /// <summary> /// Check for presence of a slot by name hash. /// </summary> /// <returns><c>True</c> if the slot exists in this context.</returns> /// <param name="nameHash">Name hash.</param> public abstract bool HasSlot(int nameHash); /// <summary> /// Add a slot asset to the context. /// </summary> /// <param name="slot">New slot asset.</param> public abstract void AddSlotAsset(SlotDataAsset slot); /// <summary> /// Check for presence of an overlay by name. /// </summary> /// <returns><c>True</c> if the overlay exists in this context.</returns> /// <param name="name">Name.</param> public abstract bool HasOverlay(string name); /// <summary> /// Check for presence of an overlay by name hash. /// </summary> /// <returns><c>True</c> if the overlay exists in this context.</returns> /// <param name="nameHash">Name hash.</param> public abstract bool HasOverlay(int nameHash); /// <summary> /// Instantiate an overlay by name. /// </summary> /// <returns>The overlay.</returns> /// <param name="name">Name.</param> public abstract OverlayData InstantiateOverlay(string name); /// <summary> /// Instantiate an overlay by name hash. /// </summary> /// <returns>The overlay.</returns> /// <param name="nameHash">Name hash.</param> public abstract OverlayData InstantiateOverlay(int nameHash); /// <summary> /// Instantiate a tinted overlay by name. /// </summary> /// <returns>The overlay.</returns> /// <param name="name">Name.</param> /// <param name="color">Color.</param> public abstract OverlayData InstantiateOverlay(string name, Color color); /// <summary> /// Instantiate a tinted overlay by name hash. /// </summary> /// <returns>The overlay.</returns> /// <param name="nameHash">Name hash.</param> /// <param name="color">Color.</param> public abstract OverlayData InstantiateOverlay(int nameHash, Color color); /// <summary> /// Add an overlay asset to the context. /// </summary> /// <param name="overlay">New overlay asset.</param> public abstract void AddOverlayAsset(OverlayDataAsset overlay); // Get all DNA public abstract List<DynamicUMADnaAsset> GetAllDNA(); // Get a DNA Asset By Name public abstract DynamicUMADnaAsset GetDNA(string Name); public abstract RuntimeAnimatorController GetAnimatorController(string Name); public abstract List<RuntimeAnimatorController> GetAllAnimatorControllers(); public abstract void AddRecipe(UMATextRecipe recipe); public abstract bool HasRecipe(string Name); public abstract bool CheckRecipeAvailability(string recipeName); public abstract UMATextRecipe GetRecipe(string filename, bool dynamicallyAdd); public abstract UMARecipeBase GetBaseRecipe(string filename, bool dynamicallyAdd); public abstract string GetCharacterRecipe(string filename); public abstract List<string> GetRecipeFiles(); public abstract Dictionary<string, List<UMATextRecipe>> GetRecipes(string raceName); public abstract List<string> GetRecipeNamesForRaceSlot(string race, string slot); public abstract List<UMARecipeBase> GetRecipesForRaceSlot(string race, string slot); #pragma warning restore 618 /// <summary> /// Finds the singleton context in the scene. /// </summary> /// <returns>The UMA context.</returns> public static UMAContextBase FindInstance() { if (Instance == null) { var contextGO = GameObject.Find("UMAContext"); if (contextGO != null) Instance = contextGO.GetComponent<UMAContextBase>(); } if (Instance == null) { Instance = Component.FindObjectOfType<UMAContextBase>(); } return Instance; } #if UNITY_EDITOR public static GameObject CreateEditorContext() { GameObject EditorUMAContextBase = null; if (UnityEditor.BuildPipeline.isBuildingPlayer) return null; if (Application.isPlaying) { if (Debug.isDebugBuild) Debug.LogWarning("There was no UMAContext in this scene. Please add the UMA context prefab to this scene before you try to generate an UMA."); return null; } if (Debug.isDebugBuild) Debug.Log("UMA Recipe Editor created an UMAEditorContext to enable editing. This will auto delete once you have finished editing your recipe or you add a UMA prefab with a context to this scene."); //if there is already an EditorUMAContextBase use it if (UMAContextBase.FindInstance() != null) { if (UMAContextBase.FindInstance().gameObject.name == "UMAEditorContext") { EditorUMAContextBase = UMAContextBase.FindInstance().gameObject; //if the UMAContextBase itself is on this game object, it means this was created and not deleted by the previous version of 'CreateEditorContext' //(The new version creates the UMAContextBase on a child game object called 'UMAContextBase' so that UMAContextBase.FindInstance can find it properly) //so in this case delete all the components that would have been added from the found gameObject from the previous code if (EditorUMAContextBase.GetComponent<UMAContextBase>()) { UMAUtils.DestroySceneObject(EditorUMAContextBase.GetComponent<UMAContextBase>());//should also make the instance null again } } else if (UMAContextBase.FindInstance().gameObject.transform.parent.gameObject.name == "UMAEditorContext") { EditorUMAContextBase = UMAContextBase.FindInstance().gameObject.transform.parent.gameObject; } } else if (GameObject.Find("UMAEditorContext")) { EditorUMAContextBase = GameObject.Find("UMAEditorContext"); } else { EditorUMAContextBase = new GameObject(); EditorUMAContextBase.name = "UMAEditorContext"; } //Make this GameObject not show up in the scene or save EditorUMAContextBase.hideFlags = HideFlags.DontSave | HideFlags.NotEditable; //if this gameobject does not contain an UMAContextBase add it - we have to call it UMAContextBase because UMAContextBase.FindInstance searches for that game object var context = UMAContextBase.Instance = EditorUMAContextBase.GetComponentInChildren<UMAContextBase>(); if (UMAContextBase.Instance == null) { var GO = new GameObject(); GO.name = "UMAContext"; GO.transform.parent = EditorUMAContextBase.transform; context = GO.AddComponent<UMAGlobalContext>(); GO.AddComponent<UMADefaultMeshCombiner>(); var gen = GO.AddComponent<UMAGenerator>(); gen.fitAtlas = true; gen.SharperFitTextures = true; gen.AtlasOverflowFitMethod = UMAGeneratorBase.FitMethod.BestFitSquare; gen.convertRenderTexture = false; gen.editorAtlasResolution = 1024; gen.InitialScaleFactor = 2; gen.collectGarbage = false; gen.IterationCount = 1; gen.fastGeneration = true; gen.processAllPending = false; gen.NoCoroutines = true; UMAContextBase.Instance = context; } return EditorUMAContextBase; } #endif } }
using System.Linq; using System.Text.RegularExpressions; using FluentMigrator.Runner.Helpers; #region License // // Copyright (c) 2007-2009, Sean Chambers <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Data; using FluentMigrator.Builders.Execute; using FluentMigrator.Runner.Generators; using FluentMigrator.Runner.Generators.Oracle; namespace FluentMigrator.Runner.Processors.Oracle { public class OracleProcessor : GenericProcessorBase { public override string DatabaseType { get { return "Oracle"; } } public OracleProcessor(IDbConnection connection, IMigrationGenerator generator, IAnnouncer announcer, IMigrationProcessorOptions options, IDbFactory factory) : base(connection, factory, generator, announcer, options) { } public IQuoter Quoter { get { return ((OracleGenerator)this.Generator).Quoter; } } public override bool SchemaExists(string schemaName) { if (schemaName == null) throw new ArgumentNullException("schemaName"); if (schemaName.Length == 0) return false; return Exists("SELECT 1 FROM ALL_USERS WHERE USERNAME = '{0}'", schemaName.ToUpper()); } public override bool TableExists(string schemaName, string tableName) { if (tableName == null) throw new ArgumentNullException("tableName"); if (tableName.Length == 0) return false; if (string.IsNullOrEmpty(schemaName)) return Exists("SELECT 1 FROM USER_TABLES WHERE upper(TABLE_NAME) = '{0}'", FormatHelper.FormatSqlEscape(tableName.ToUpper())); return Exists("SELECT 1 FROM ALL_TABLES WHERE upper(OWNER) = '{0}' AND upper(TABLE_NAME) = '{1}'", schemaName.ToUpper(), FormatHelper.FormatSqlEscape(tableName.ToUpper())); } public override bool ColumnExists(string schemaName, string tableName, string columnName) { if (tableName == null) throw new ArgumentNullException("tableName"); if (columnName == null) throw new ArgumentNullException("columnName"); if (columnName.Length == 0 || tableName.Length == 0) return false; if (string.IsNullOrEmpty(schemaName)) return Exists("SELECT 1 FROM USER_TAB_COLUMNS WHERE upper(TABLE_NAME) = '{0}' AND upper(COLUMN_NAME) = '{1}'", FormatHelper.FormatSqlEscape(tableName.ToUpper()), FormatHelper.FormatSqlEscape(columnName.ToUpper())); return Exists("SELECT 1 FROM ALL_TAB_COLUMNS WHERE upper(OWNER) = '{0}' AND upper(TABLE_NAME) = '{1}' AND upper(COLUMN_NAME) = '{2}'", schemaName.ToUpper(), FormatHelper.FormatSqlEscape(tableName.ToUpper()), FormatHelper.FormatSqlEscape(columnName.ToUpper())); } public override bool ConstraintExists(string schemaName, string tableName, string constraintName) { if (tableName == null) throw new ArgumentNullException("tableName"); if (constraintName == null) throw new ArgumentNullException("constraintName"); //In Oracle DB constraint name is unique within the schema, so the table name is not used in the query if (constraintName.Length == 0) return false; if (String.IsNullOrEmpty(schemaName)) return Exists("SELECT 1 FROM USER_CONSTRAINTS WHERE upper(CONSTRAINT_NAME) = '{0}'", FormatHelper.FormatSqlEscape(constraintName.ToUpper())); return Exists("SELECT 1 FROM ALL_CONSTRAINTS WHERE upper(OWNER) = '{0}' AND upper(CONSTRAINT_NAME) = '{1}'", schemaName.ToUpper(), FormatHelper.FormatSqlEscape(constraintName.ToUpper())); } public override bool IndexExists(string schemaName, string tableName, string indexName) { if (tableName == null) throw new ArgumentNullException("tableName"); if (indexName == null) throw new ArgumentNullException("indexName"); //In Oracle DB index name is unique within the schema, so the table name is not used in the query if (indexName.Length == 0) return false; if (String.IsNullOrEmpty(schemaName)) return Exists("SELECT 1 FROM USER_INDEXES WHERE upper(INDEX_NAME) = '{0}'", FormatHelper.FormatSqlEscape(indexName.ToUpper())); return Exists("SELECT 1 FROM ALL_INDEXES WHERE upper(OWNER) = '{0}' AND upper(INDEX_NAME) = '{1}'", schemaName.ToUpper(), FormatHelper.FormatSqlEscape(indexName.ToUpper())); } public override bool SequenceExists(string schemaName, string sequenceName) { return false; } public override bool DefaultValueExists(string schemaName, string tableName, string columnName, object defaultValue) { return false; } public override void Execute(string template, params object[] args) { Process(string.Format(template, args)); } public override bool Exists(string template, params object[] args) { if (template == null) throw new ArgumentNullException("template"); EnsureConnectionIsOpen(); Announcer.Sql(String.Format(template, args)); using (var command = Factory.CreateCommand(String.Format(template, args), Connection)) using (var reader = command.ExecuteReader()) { return reader.Read(); } } public override DataSet ReadTableData(string schemaName, string tableName) { if (tableName == null) throw new ArgumentNullException("tableName"); if (String.IsNullOrEmpty(schemaName)) return Read("SELECT * FROM {0}", Quoter.QuoteTableName(tableName)); return Read("SELECT * FROM {0}.{1}", Quoter.QuoteSchemaName(schemaName), Quoter.QuoteTableName(tableName)); } public override DataSet Read(string template, params object[] args) { if (template == null) throw new ArgumentNullException("template"); EnsureConnectionIsOpen(); var result = new DataSet(); using (var command = Factory.CreateCommand(String.Format(template, args), Connection)) { var adapter = Factory.CreateDataAdapter(command); adapter.Fill(result); return result; } } public override void Process(PerformDBOperationExpression expression) { EnsureConnectionIsOpen(); if (expression.Operation != null) expression.Operation(Connection, null); } protected override void Process(string sql) { Announcer.Sql(sql); if (Options.PreviewOnly || string.IsNullOrEmpty(sql)) return; EnsureConnectionIsOpen(); var batches = Regex.Split(sql, @"^\s*;\s*$", RegexOptions.Multiline) .Select(x => x.Trim()) .Where(x => !string.IsNullOrEmpty(x)); foreach (var batch in batches) { using (var command = Factory.CreateCommand(batch, Connection)) command.ExecuteNonQuery(); } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V8.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V8.Services { /// <summary>Settings for <see cref="AdGroupCriterionSimulationServiceClient"/> instances.</summary> public sealed partial class AdGroupCriterionSimulationServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary> /// Get a new instance of the default <see cref="AdGroupCriterionSimulationServiceSettings"/>. /// </summary> /// <returns>A new instance of the default <see cref="AdGroupCriterionSimulationServiceSettings"/>.</returns> public static AdGroupCriterionSimulationServiceSettings GetDefault() => new AdGroupCriterionSimulationServiceSettings(); /// <summary> /// Constructs a new <see cref="AdGroupCriterionSimulationServiceSettings"/> object with default settings. /// </summary> public AdGroupCriterionSimulationServiceSettings() { } private AdGroupCriterionSimulationServiceSettings(AdGroupCriterionSimulationServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetAdGroupCriterionSimulationSettings = existing.GetAdGroupCriterionSimulationSettings; OnCopy(existing); } partial void OnCopy(AdGroupCriterionSimulationServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AdGroupCriterionSimulationServiceClient.GetAdGroupCriterionSimulation</c> and /// <c>AdGroupCriterionSimulationServiceClient.GetAdGroupCriterionSimulationAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetAdGroupCriterionSimulationSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="AdGroupCriterionSimulationServiceSettings"/> object.</returns> public AdGroupCriterionSimulationServiceSettings Clone() => new AdGroupCriterionSimulationServiceSettings(this); } /// <summary> /// Builder class for <see cref="AdGroupCriterionSimulationServiceClient"/> to provide simple configuration of /// credentials, endpoint etc. /// </summary> internal sealed partial class AdGroupCriterionSimulationServiceClientBuilder : gaxgrpc::ClientBuilderBase<AdGroupCriterionSimulationServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public AdGroupCriterionSimulationServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public AdGroupCriterionSimulationServiceClientBuilder() { UseJwtAccessWithScopes = AdGroupCriterionSimulationServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref AdGroupCriterionSimulationServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AdGroupCriterionSimulationServiceClient> task); /// <summary>Builds the resulting client.</summary> public override AdGroupCriterionSimulationServiceClient Build() { AdGroupCriterionSimulationServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<AdGroupCriterionSimulationServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<AdGroupCriterionSimulationServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private AdGroupCriterionSimulationServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return AdGroupCriterionSimulationServiceClient.Create(callInvoker, Settings); } private async stt::Task<AdGroupCriterionSimulationServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return AdGroupCriterionSimulationServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => AdGroupCriterionSimulationServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => AdGroupCriterionSimulationServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => AdGroupCriterionSimulationServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>AdGroupCriterionSimulationService client wrapper, for convenient use.</summary> /// <remarks> /// Service to fetch ad group criterion simulations. /// </remarks> public abstract partial class AdGroupCriterionSimulationServiceClient { /// <summary> /// The default endpoint for the AdGroupCriterionSimulationService service, which is a host of /// "googleads.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default AdGroupCriterionSimulationService scopes.</summary> /// <remarks> /// The default AdGroupCriterionSimulationService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="AdGroupCriterionSimulationServiceClient"/> using the default /// credentials, endpoint and settings. To specify custom credentials or other settings, use /// <see cref="AdGroupCriterionSimulationServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="AdGroupCriterionSimulationServiceClient"/>.</returns> public static stt::Task<AdGroupCriterionSimulationServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new AdGroupCriterionSimulationServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="AdGroupCriterionSimulationServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="AdGroupCriterionSimulationServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="AdGroupCriterionSimulationServiceClient"/>.</returns> public static AdGroupCriterionSimulationServiceClient Create() => new AdGroupCriterionSimulationServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="AdGroupCriterionSimulationServiceClient"/> which uses the specified call invoker for /// remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="AdGroupCriterionSimulationServiceSettings"/>.</param> /// <returns>The created <see cref="AdGroupCriterionSimulationServiceClient"/>.</returns> internal static AdGroupCriterionSimulationServiceClient Create(grpccore::CallInvoker callInvoker, AdGroupCriterionSimulationServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } AdGroupCriterionSimulationService.AdGroupCriterionSimulationServiceClient grpcClient = new AdGroupCriterionSimulationService.AdGroupCriterionSimulationServiceClient(callInvoker); return new AdGroupCriterionSimulationServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC AdGroupCriterionSimulationService client</summary> public virtual AdGroupCriterionSimulationService.AdGroupCriterionSimulationServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested ad group criterion simulation in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::AdGroupCriterionSimulation GetAdGroupCriterionSimulation(GetAdGroupCriterionSimulationRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested ad group criterion simulation in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupCriterionSimulation> GetAdGroupCriterionSimulationAsync(GetAdGroupCriterionSimulationRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested ad group criterion simulation in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupCriterionSimulation> GetAdGroupCriterionSimulationAsync(GetAdGroupCriterionSimulationRequest request, st::CancellationToken cancellationToken) => GetAdGroupCriterionSimulationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested ad group criterion simulation in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group criterion simulation to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::AdGroupCriterionSimulation GetAdGroupCriterionSimulation(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdGroupCriterionSimulation(new GetAdGroupCriterionSimulationRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested ad group criterion simulation in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group criterion simulation to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupCriterionSimulation> GetAdGroupCriterionSimulationAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdGroupCriterionSimulationAsync(new GetAdGroupCriterionSimulationRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested ad group criterion simulation in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group criterion simulation to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupCriterionSimulation> GetAdGroupCriterionSimulationAsync(string resourceName, st::CancellationToken cancellationToken) => GetAdGroupCriterionSimulationAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested ad group criterion simulation in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group criterion simulation to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::AdGroupCriterionSimulation GetAdGroupCriterionSimulation(gagvr::AdGroupCriterionSimulationName resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdGroupCriterionSimulation(new GetAdGroupCriterionSimulationRequest { ResourceNameAsAdGroupCriterionSimulationName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested ad group criterion simulation in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group criterion simulation to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupCriterionSimulation> GetAdGroupCriterionSimulationAsync(gagvr::AdGroupCriterionSimulationName resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdGroupCriterionSimulationAsync(new GetAdGroupCriterionSimulationRequest { ResourceNameAsAdGroupCriterionSimulationName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested ad group criterion simulation in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group criterion simulation to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupCriterionSimulation> GetAdGroupCriterionSimulationAsync(gagvr::AdGroupCriterionSimulationName resourceName, st::CancellationToken cancellationToken) => GetAdGroupCriterionSimulationAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>AdGroupCriterionSimulationService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to fetch ad group criterion simulations. /// </remarks> public sealed partial class AdGroupCriterionSimulationServiceClientImpl : AdGroupCriterionSimulationServiceClient { private readonly gaxgrpc::ApiCall<GetAdGroupCriterionSimulationRequest, gagvr::AdGroupCriterionSimulation> _callGetAdGroupCriterionSimulation; /// <summary> /// Constructs a client wrapper for the AdGroupCriterionSimulationService service, with the specified gRPC /// client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="AdGroupCriterionSimulationServiceSettings"/> used within this client. /// </param> public AdGroupCriterionSimulationServiceClientImpl(AdGroupCriterionSimulationService.AdGroupCriterionSimulationServiceClient grpcClient, AdGroupCriterionSimulationServiceSettings settings) { GrpcClient = grpcClient; AdGroupCriterionSimulationServiceSettings effectiveSettings = settings ?? AdGroupCriterionSimulationServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetAdGroupCriterionSimulation = clientHelper.BuildApiCall<GetAdGroupCriterionSimulationRequest, gagvr::AdGroupCriterionSimulation>(grpcClient.GetAdGroupCriterionSimulationAsync, grpcClient.GetAdGroupCriterionSimulation, effectiveSettings.GetAdGroupCriterionSimulationSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetAdGroupCriterionSimulation); Modify_GetAdGroupCriterionSimulationApiCall(ref _callGetAdGroupCriterionSimulation); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetAdGroupCriterionSimulationApiCall(ref gaxgrpc::ApiCall<GetAdGroupCriterionSimulationRequest, gagvr::AdGroupCriterionSimulation> call); partial void OnConstruction(AdGroupCriterionSimulationService.AdGroupCriterionSimulationServiceClient grpcClient, AdGroupCriterionSimulationServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC AdGroupCriterionSimulationService client</summary> public override AdGroupCriterionSimulationService.AdGroupCriterionSimulationServiceClient GrpcClient { get; } partial void Modify_GetAdGroupCriterionSimulationRequest(ref GetAdGroupCriterionSimulationRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested ad group criterion simulation in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::AdGroupCriterionSimulation GetAdGroupCriterionSimulation(GetAdGroupCriterionSimulationRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetAdGroupCriterionSimulationRequest(ref request, ref callSettings); return _callGetAdGroupCriterionSimulation.Sync(request, callSettings); } /// <summary> /// Returns the requested ad group criterion simulation in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::AdGroupCriterionSimulation> GetAdGroupCriterionSimulationAsync(GetAdGroupCriterionSimulationRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetAdGroupCriterionSimulationRequest(ref request, ref callSettings); return _callGetAdGroupCriterionSimulation.Async(request, callSettings); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V10.Services { /// <summary>Settings for <see cref="CampaignFeedServiceClient"/> instances.</summary> public sealed partial class CampaignFeedServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="CampaignFeedServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="CampaignFeedServiceSettings"/>.</returns> public static CampaignFeedServiceSettings GetDefault() => new CampaignFeedServiceSettings(); /// <summary>Constructs a new <see cref="CampaignFeedServiceSettings"/> object with default settings.</summary> public CampaignFeedServiceSettings() { } private CampaignFeedServiceSettings(CampaignFeedServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); MutateCampaignFeedsSettings = existing.MutateCampaignFeedsSettings; OnCopy(existing); } partial void OnCopy(CampaignFeedServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>CampaignFeedServiceClient.MutateCampaignFeeds</c> and /// <c>CampaignFeedServiceClient.MutateCampaignFeedsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateCampaignFeedsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="CampaignFeedServiceSettings"/> object.</returns> public CampaignFeedServiceSettings Clone() => new CampaignFeedServiceSettings(this); } /// <summary> /// Builder class for <see cref="CampaignFeedServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class CampaignFeedServiceClientBuilder : gaxgrpc::ClientBuilderBase<CampaignFeedServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public CampaignFeedServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public CampaignFeedServiceClientBuilder() { UseJwtAccessWithScopes = CampaignFeedServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref CampaignFeedServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CampaignFeedServiceClient> task); /// <summary>Builds the resulting client.</summary> public override CampaignFeedServiceClient Build() { CampaignFeedServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<CampaignFeedServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<CampaignFeedServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private CampaignFeedServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return CampaignFeedServiceClient.Create(callInvoker, Settings); } private async stt::Task<CampaignFeedServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return CampaignFeedServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => CampaignFeedServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => CampaignFeedServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => CampaignFeedServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>CampaignFeedService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage campaign feeds. /// </remarks> public abstract partial class CampaignFeedServiceClient { /// <summary> /// The default endpoint for the CampaignFeedService service, which is a host of "googleads.googleapis.com" and /// a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default CampaignFeedService scopes.</summary> /// <remarks> /// The default CampaignFeedService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="CampaignFeedServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="CampaignFeedServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="CampaignFeedServiceClient"/>.</returns> public static stt::Task<CampaignFeedServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new CampaignFeedServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="CampaignFeedServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="CampaignFeedServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="CampaignFeedServiceClient"/>.</returns> public static CampaignFeedServiceClient Create() => new CampaignFeedServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="CampaignFeedServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="CampaignFeedServiceSettings"/>.</param> /// <returns>The created <see cref="CampaignFeedServiceClient"/>.</returns> internal static CampaignFeedServiceClient Create(grpccore::CallInvoker callInvoker, CampaignFeedServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } CampaignFeedService.CampaignFeedServiceClient grpcClient = new CampaignFeedService.CampaignFeedServiceClient(callInvoker); return new CampaignFeedServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC CampaignFeedService client</summary> public virtual CampaignFeedService.CampaignFeedServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes campaign feeds. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CampaignFeedError]() /// [CollectionSizeError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FunctionError]() /// [FunctionParsingError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateCampaignFeedsResponse MutateCampaignFeeds(MutateCampaignFeedsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes campaign feeds. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CampaignFeedError]() /// [CollectionSizeError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FunctionError]() /// [FunctionParsingError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCampaignFeedsResponse> MutateCampaignFeedsAsync(MutateCampaignFeedsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes campaign feeds. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CampaignFeedError]() /// [CollectionSizeError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FunctionError]() /// [FunctionParsingError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCampaignFeedsResponse> MutateCampaignFeedsAsync(MutateCampaignFeedsRequest request, st::CancellationToken cancellationToken) => MutateCampaignFeedsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes campaign feeds. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CampaignFeedError]() /// [CollectionSizeError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FunctionError]() /// [FunctionParsingError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose campaign feeds are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual campaign feeds. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateCampaignFeedsResponse MutateCampaignFeeds(string customerId, scg::IEnumerable<CampaignFeedOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateCampaignFeeds(new MutateCampaignFeedsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes campaign feeds. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CampaignFeedError]() /// [CollectionSizeError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FunctionError]() /// [FunctionParsingError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose campaign feeds are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual campaign feeds. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCampaignFeedsResponse> MutateCampaignFeedsAsync(string customerId, scg::IEnumerable<CampaignFeedOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateCampaignFeedsAsync(new MutateCampaignFeedsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes campaign feeds. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CampaignFeedError]() /// [CollectionSizeError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FunctionError]() /// [FunctionParsingError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose campaign feeds are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual campaign feeds. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCampaignFeedsResponse> MutateCampaignFeedsAsync(string customerId, scg::IEnumerable<CampaignFeedOperation> operations, st::CancellationToken cancellationToken) => MutateCampaignFeedsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>CampaignFeedService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage campaign feeds. /// </remarks> public sealed partial class CampaignFeedServiceClientImpl : CampaignFeedServiceClient { private readonly gaxgrpc::ApiCall<MutateCampaignFeedsRequest, MutateCampaignFeedsResponse> _callMutateCampaignFeeds; /// <summary> /// Constructs a client wrapper for the CampaignFeedService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="CampaignFeedServiceSettings"/> used within this client.</param> public CampaignFeedServiceClientImpl(CampaignFeedService.CampaignFeedServiceClient grpcClient, CampaignFeedServiceSettings settings) { GrpcClient = grpcClient; CampaignFeedServiceSettings effectiveSettings = settings ?? CampaignFeedServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callMutateCampaignFeeds = clientHelper.BuildApiCall<MutateCampaignFeedsRequest, MutateCampaignFeedsResponse>(grpcClient.MutateCampaignFeedsAsync, grpcClient.MutateCampaignFeeds, effectiveSettings.MutateCampaignFeedsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateCampaignFeeds); Modify_MutateCampaignFeedsApiCall(ref _callMutateCampaignFeeds); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_MutateCampaignFeedsApiCall(ref gaxgrpc::ApiCall<MutateCampaignFeedsRequest, MutateCampaignFeedsResponse> call); partial void OnConstruction(CampaignFeedService.CampaignFeedServiceClient grpcClient, CampaignFeedServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC CampaignFeedService client</summary> public override CampaignFeedService.CampaignFeedServiceClient GrpcClient { get; } partial void Modify_MutateCampaignFeedsRequest(ref MutateCampaignFeedsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Creates, updates, or removes campaign feeds. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CampaignFeedError]() /// [CollectionSizeError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FunctionError]() /// [FunctionParsingError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateCampaignFeedsResponse MutateCampaignFeeds(MutateCampaignFeedsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateCampaignFeedsRequest(ref request, ref callSettings); return _callMutateCampaignFeeds.Sync(request, callSettings); } /// <summary> /// Creates, updates, or removes campaign feeds. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CampaignFeedError]() /// [CollectionSizeError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FunctionError]() /// [FunctionParsingError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateCampaignFeedsResponse> MutateCampaignFeedsAsync(MutateCampaignFeedsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateCampaignFeedsRequest(ref request, ref callSettings); return _callMutateCampaignFeeds.Async(request, callSettings); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Reflection.Internal; using System.Reflection.Metadata.Ecma335; using System.Text; using TestUtilities; using Xunit; namespace System.Reflection.Metadata.Tests { public class BlobReaderTests { [Fact] public unsafe void PublicBlobReaderCtorValidatesArgs() { byte* bufferPtrForLambda; byte[] buffer = new byte[4] { 0, 1, 0, 2 }; fixed (byte* bufferPtr = buffer) { bufferPtrForLambda = bufferPtr; Assert.Throws<ArgumentOutOfRangeException>(() => new BlobReader(bufferPtrForLambda, -1)); } Assert.Throws<ArgumentNullException>(() => new BlobReader(null, 1)); Assert.Equal(0, new BlobReader(null, 0).Length); // this is valid Assert.Throws<BadImageFormatException>(() => new BlobReader(null, 0).ReadByte()); // but can't read anything non-empty from it... Assert.Same(String.Empty, new BlobReader(null, 0).ReadUtf8NullTerminated()); // can read empty string. } [Fact] public unsafe void ReadFromMemoryReader() { byte[] buffer = new byte[4] { 0, 1, 0, 2 }; fixed (byte* bufferPtr = buffer) { var reader = new BlobReader(new MemoryBlock(bufferPtr, buffer.Length)); Assert.Equal(false, reader.SeekOffset(-1)); Assert.Equal(false, reader.SeekOffset(Int32.MaxValue)); Assert.Equal(false, reader.SeekOffset(Int32.MinValue)); Assert.Equal(false, reader.SeekOffset(buffer.Length)); Assert.Equal(true, reader.SeekOffset(buffer.Length - 1)); Assert.Equal(true, reader.SeekOffset(0)); Assert.Equal(0, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadUInt64()); Assert.Equal(0, reader.Offset); Assert.Equal(true, reader.SeekOffset(1)); Assert.Equal(1, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadDouble()); Assert.Equal(1, reader.Offset); Assert.Equal(true, reader.SeekOffset(2)); Assert.Equal(2, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadUInt32()); Assert.Equal((ushort)0x0200, reader.ReadUInt16()); Assert.Equal(4, reader.Offset); Assert.Equal(true, reader.SeekOffset(2)); Assert.Equal(2, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadSingle()); Assert.Equal(2, reader.Offset); Assert.Equal(true, reader.SeekOffset(0)); Assert.Equal(9.404242E-38F, reader.ReadSingle()); Assert.Equal(4, reader.Offset); Assert.Equal(true, reader.SeekOffset(3)); Assert.Equal(3, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadUInt16()); Assert.Equal((byte)0x02, reader.ReadByte()); Assert.Equal(4, reader.Offset); Assert.Equal(true, reader.SeekOffset(0)); Assert.Equal("\u0000\u0001\u0000\u0002", reader.ReadUTF8(4)); Assert.Equal(4, reader.Offset); Assert.Equal(true, reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.ReadUTF8(5)); Assert.Equal(0, reader.Offset); Assert.Equal(true, reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.ReadUTF8(-1)); Assert.Equal(0, reader.Offset); Assert.Equal(true, reader.SeekOffset(0)); Assert.Equal("\u0100\u0200", reader.ReadUTF16(4)); Assert.Equal(4, reader.Offset); Assert.Equal(true, reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.ReadUTF16(5)); Assert.Equal(0, reader.Offset); Assert.Equal(true, reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.ReadUTF16(-1)); Assert.Equal(0, reader.Offset); Assert.Equal(true, reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.ReadUTF16(6)); Assert.Equal(0, reader.Offset); Assert.Equal(true, reader.SeekOffset(0)); AssertEx.Equal(buffer, reader.ReadBytes(4)); Assert.Equal(4, reader.Offset); Assert.Equal(true, reader.SeekOffset(0)); Assert.Same(String.Empty, reader.ReadUtf8NullTerminated()); Assert.Equal(1, reader.Offset); Assert.Equal(true, reader.SeekOffset(1)); Assert.Equal("\u0001", reader.ReadUtf8NullTerminated()); Assert.Equal(3, reader.Offset); Assert.Equal(true, reader.SeekOffset(3)); Assert.Equal("\u0002", reader.ReadUtf8NullTerminated()); Assert.Equal(4, reader.Offset); Assert.Equal(true, reader.SeekOffset(0)); Assert.Same(String.Empty, reader.ReadUtf8NullTerminated()); Assert.Equal(1, reader.Offset); Assert.Equal(true, reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.ReadBytes(5)); Assert.Equal(0, reader.Offset); Assert.Equal(true, reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.ReadBytes(Int32.MinValue)); Assert.Equal(0, reader.Offset); Assert.Equal(true, reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.GetMemoryBlockAt(-1, 1)); Assert.Equal(0, reader.Offset); Assert.Equal(true, reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.GetMemoryBlockAt(1, -1)); Assert.Equal(0, reader.Offset); Assert.Equal(true, reader.SeekOffset(0)); Assert.Equal(3, reader.GetMemoryBlockAt(1, 3).Length); Assert.Equal(0, reader.Offset); Assert.Equal(true, reader.SeekOffset(3)); reader.ReadByte(); Assert.Equal(4, reader.Offset); Assert.Equal(4, reader.Offset); Assert.Equal(0, reader.ReadBytes(0).Length); Assert.Equal(4, reader.Offset); int value; Assert.Equal(false, reader.TryReadCompressedInteger(out value)); Assert.Equal(BlobReader.InvalidCompressedInteger, value); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadCompressedInteger()); Assert.Equal(4, reader.Offset); Assert.Equal(SerializationTypeCode.Invalid, reader.ReadSerializationTypeCode()); Assert.Equal(4, reader.Offset); Assert.Equal(SignatureTypeCode.Invalid, reader.ReadSignatureTypeCode()); Assert.Equal(4, reader.Offset); Assert.Equal(default(Handle), reader.ReadTypeHandle()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadBoolean()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadByte()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadSByte()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadUInt32()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadInt32()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadUInt64()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadInt64()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadSingle()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadDouble()); Assert.Equal(4, reader.Offset); } byte[] buffer2 = new byte[8] { 1, 2, 3, 4, 5, 6, 7, 8 }; fixed (byte* bufferPtr2 = buffer2) { var reader = new BlobReader(new MemoryBlock(bufferPtr2, buffer2.Length)); Assert.Equal(reader.Offset, 0); Assert.Equal(0x0807060504030201UL, reader.ReadUInt64()); Assert.Equal(reader.Offset, 8); reader.Reset(); Assert.Equal(reader.Offset, 0); Assert.Equal(0x0807060504030201L, reader.ReadInt64()); reader.Reset(); Assert.Equal(reader.Offset, 0); Assert.Equal(BitConverter.ToDouble(buffer2, 0), reader.ReadDouble()); } } [Fact] public unsafe void ValidatePeekReferenceSize() { byte[] buffer = new byte[8] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 }; fixed (byte* bufferPtr = buffer) { var block = new MemoryBlock(bufferPtr, buffer.Length); // small ref size always fits in 16 bits Assert.Equal(0xFFFFU, block.PeekReference(0, smallRefSize: true)); Assert.Equal(0xFFFFU, block.PeekReference(4, smallRefSize: true)); Assert.Equal(0xFFFFU, block.PeekTaggedReference(0, smallRefSize: true)); Assert.Equal(0xFFFFU, block.PeekTaggedReference(4, smallRefSize: true)); Assert.Equal(0x01FFU, block.PeekTaggedReference(6, smallRefSize: true)); // large ref size throws on > RIDMask when tagged variant is not used. AssertEx.Throws<BadImageFormatException>(() => block.PeekReference(0, smallRefSize: false), MetadataResources.RowIdOrHeapOffsetTooLarge); AssertEx.Throws<BadImageFormatException>(() => block.PeekReference(4, smallRefSize: false), MetadataResources.RowIdOrHeapOffsetTooLarge); // large ref size does not throw when Tagged variant is used. Assert.Equal(0xFFFFFFFFU, block.PeekTaggedReference(0, smallRefSize: false)); Assert.Equal(0x01FFFFFFU, block.PeekTaggedReference(4, smallRefSize: false)); // bounds check applies in all cases AssertEx.Throws<BadImageFormatException>(() => block.PeekReference(7, smallRefSize: true), MetadataResources.OutOfBoundsRead); AssertEx.Throws<BadImageFormatException>(() => block.PeekReference(5, smallRefSize: false), MetadataResources.OutOfBoundsRead); } } [Fact] public unsafe void ReadFromMemoryBlock() { byte[] buffer = new byte[4] { 0, 1, 0, 2 }; fixed (byte* bufferPtr = buffer) { var block = new MemoryBlock(bufferPtr, buffer.Length); Assert.Throws<BadImageFormatException>(() => block.PeekUInt32(Int32.MaxValue)); Assert.Throws<BadImageFormatException>(() => block.PeekUInt32(-1)); Assert.Throws<BadImageFormatException>(() => block.PeekUInt32(Int32.MinValue)); Assert.Throws<BadImageFormatException>(() => block.PeekUInt32(4)); Assert.Throws<BadImageFormatException>(() => block.PeekUInt32(1)); Assert.Equal(0x02000100U, block.PeekUInt32(0)); Assert.Throws<BadImageFormatException>(() => block.PeekUInt16(Int32.MaxValue)); Assert.Throws<BadImageFormatException>(() => block.PeekUInt16(-1)); Assert.Throws<BadImageFormatException>(() => block.PeekUInt16(Int32.MinValue)); Assert.Throws<BadImageFormatException>(() => block.PeekUInt16(4)); Assert.Equal(0x0200, block.PeekUInt16(2)); int bytesRead; MetadataStringDecoder stringDecoder = MetadataStringDecoder.DefaultUTF8; Assert.Throws<BadImageFormatException>(() => block.PeekUtf8NullTerminated(Int32.MaxValue, null, stringDecoder, out bytesRead)); Assert.Throws<BadImageFormatException>(() => block.PeekUtf8NullTerminated(-1, null, stringDecoder, out bytesRead)); Assert.Throws<BadImageFormatException>(() => block.PeekUtf8NullTerminated(Int32.MinValue, null, stringDecoder, out bytesRead)); Assert.Throws<BadImageFormatException>(() => block.PeekUtf8NullTerminated(5, null, stringDecoder, out bytesRead)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(-1, 1)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(1, -1)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(0, -1)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(-1, 0)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(-Int32.MaxValue, Int32.MaxValue)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(Int32.MaxValue, -Int32.MaxValue)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(Int32.MaxValue, Int32.MaxValue)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(block.Length, -1)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(-1, block.Length)); Assert.Equal("\u0001", block.PeekUtf8NullTerminated(1, null, stringDecoder, out bytesRead)); Assert.Equal(bytesRead, 2); Assert.Equal("\u0002", block.PeekUtf8NullTerminated(3, null, stringDecoder, out bytesRead)); Assert.Equal(bytesRead, 1); Assert.Equal("", block.PeekUtf8NullTerminated(4, null, stringDecoder, out bytesRead)); Assert.Equal(bytesRead, 0); byte[] helloPrefix = Encoding.UTF8.GetBytes("Hello"); Assert.Equal("Hello\u0001", block.PeekUtf8NullTerminated(1, helloPrefix, stringDecoder, out bytesRead)); Assert.Equal(bytesRead, 2); Assert.Equal("Hello\u0002", block.PeekUtf8NullTerminated(3, helloPrefix, stringDecoder, out bytesRead)); Assert.Equal(bytesRead, 1); Assert.Equal("Hello", block.PeekUtf8NullTerminated(4, helloPrefix, stringDecoder, out bytesRead)); Assert.Equal(bytesRead, 0); } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/example/library/v1/library.proto // Original file comments: // Copyright (c) 2015, Google 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. // #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using Grpc.Core; namespace Google.Example.Library.V1 { /// <summary> /// This API represents a simple digital library. It lets you manage Shelf /// resources and Book resources in the library. It defines the following /// resource model: /// /// - The API has a collection of [Shelf][google.example.library.v1.Shelf] /// resources, named `shelves/*` /// /// - Each Shelf has a collection of [Book][google.example.library.v1.Book] /// resources, named `shelves/*/books/*` /// </summary> public static class LibraryService { static readonly string __ServiceName = "google.example.library.v1.LibraryService"; static readonly Marshaller<global::Google.Example.Library.V1.CreateShelfRequest> __Marshaller_CreateShelfRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Example.Library.V1.CreateShelfRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Example.Library.V1.Shelf> __Marshaller_Shelf = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Example.Library.V1.Shelf.Parser.ParseFrom); static readonly Marshaller<global::Google.Example.Library.V1.GetShelfRequest> __Marshaller_GetShelfRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Example.Library.V1.GetShelfRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Example.Library.V1.ListShelvesRequest> __Marshaller_ListShelvesRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Example.Library.V1.ListShelvesRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Example.Library.V1.ListShelvesResponse> __Marshaller_ListShelvesResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Example.Library.V1.ListShelvesResponse.Parser.ParseFrom); static readonly Marshaller<global::Google.Example.Library.V1.DeleteShelfRequest> __Marshaller_DeleteShelfRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Example.Library.V1.DeleteShelfRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom); static readonly Marshaller<global::Google.Example.Library.V1.MergeShelvesRequest> __Marshaller_MergeShelvesRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Example.Library.V1.MergeShelvesRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Example.Library.V1.CreateBookRequest> __Marshaller_CreateBookRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Example.Library.V1.CreateBookRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Example.Library.V1.Book> __Marshaller_Book = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Example.Library.V1.Book.Parser.ParseFrom); static readonly Marshaller<global::Google.Example.Library.V1.GetBookRequest> __Marshaller_GetBookRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Example.Library.V1.GetBookRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Example.Library.V1.ListBooksRequest> __Marshaller_ListBooksRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Example.Library.V1.ListBooksRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Example.Library.V1.ListBooksResponse> __Marshaller_ListBooksResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Example.Library.V1.ListBooksResponse.Parser.ParseFrom); static readonly Marshaller<global::Google.Example.Library.V1.DeleteBookRequest> __Marshaller_DeleteBookRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Example.Library.V1.DeleteBookRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Example.Library.V1.UpdateBookRequest> __Marshaller_UpdateBookRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Example.Library.V1.UpdateBookRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Example.Library.V1.MoveBookRequest> __Marshaller_MoveBookRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Example.Library.V1.MoveBookRequest.Parser.ParseFrom); static readonly Method<global::Google.Example.Library.V1.CreateShelfRequest, global::Google.Example.Library.V1.Shelf> __Method_CreateShelf = new Method<global::Google.Example.Library.V1.CreateShelfRequest, global::Google.Example.Library.V1.Shelf>( MethodType.Unary, __ServiceName, "CreateShelf", __Marshaller_CreateShelfRequest, __Marshaller_Shelf); static readonly Method<global::Google.Example.Library.V1.GetShelfRequest, global::Google.Example.Library.V1.Shelf> __Method_GetShelf = new Method<global::Google.Example.Library.V1.GetShelfRequest, global::Google.Example.Library.V1.Shelf>( MethodType.Unary, __ServiceName, "GetShelf", __Marshaller_GetShelfRequest, __Marshaller_Shelf); static readonly Method<global::Google.Example.Library.V1.ListShelvesRequest, global::Google.Example.Library.V1.ListShelvesResponse> __Method_ListShelves = new Method<global::Google.Example.Library.V1.ListShelvesRequest, global::Google.Example.Library.V1.ListShelvesResponse>( MethodType.Unary, __ServiceName, "ListShelves", __Marshaller_ListShelvesRequest, __Marshaller_ListShelvesResponse); static readonly Method<global::Google.Example.Library.V1.DeleteShelfRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteShelf = new Method<global::Google.Example.Library.V1.DeleteShelfRequest, global::Google.Protobuf.WellKnownTypes.Empty>( MethodType.Unary, __ServiceName, "DeleteShelf", __Marshaller_DeleteShelfRequest, __Marshaller_Empty); static readonly Method<global::Google.Example.Library.V1.MergeShelvesRequest, global::Google.Example.Library.V1.Shelf> __Method_MergeShelves = new Method<global::Google.Example.Library.V1.MergeShelvesRequest, global::Google.Example.Library.V1.Shelf>( MethodType.Unary, __ServiceName, "MergeShelves", __Marshaller_MergeShelvesRequest, __Marshaller_Shelf); static readonly Method<global::Google.Example.Library.V1.CreateBookRequest, global::Google.Example.Library.V1.Book> __Method_CreateBook = new Method<global::Google.Example.Library.V1.CreateBookRequest, global::Google.Example.Library.V1.Book>( MethodType.Unary, __ServiceName, "CreateBook", __Marshaller_CreateBookRequest, __Marshaller_Book); static readonly Method<global::Google.Example.Library.V1.GetBookRequest, global::Google.Example.Library.V1.Book> __Method_GetBook = new Method<global::Google.Example.Library.V1.GetBookRequest, global::Google.Example.Library.V1.Book>( MethodType.Unary, __ServiceName, "GetBook", __Marshaller_GetBookRequest, __Marshaller_Book); static readonly Method<global::Google.Example.Library.V1.ListBooksRequest, global::Google.Example.Library.V1.ListBooksResponse> __Method_ListBooks = new Method<global::Google.Example.Library.V1.ListBooksRequest, global::Google.Example.Library.V1.ListBooksResponse>( MethodType.Unary, __ServiceName, "ListBooks", __Marshaller_ListBooksRequest, __Marshaller_ListBooksResponse); static readonly Method<global::Google.Example.Library.V1.DeleteBookRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteBook = new Method<global::Google.Example.Library.V1.DeleteBookRequest, global::Google.Protobuf.WellKnownTypes.Empty>( MethodType.Unary, __ServiceName, "DeleteBook", __Marshaller_DeleteBookRequest, __Marshaller_Empty); static readonly Method<global::Google.Example.Library.V1.UpdateBookRequest, global::Google.Example.Library.V1.Book> __Method_UpdateBook = new Method<global::Google.Example.Library.V1.UpdateBookRequest, global::Google.Example.Library.V1.Book>( MethodType.Unary, __ServiceName, "UpdateBook", __Marshaller_UpdateBookRequest, __Marshaller_Book); static readonly Method<global::Google.Example.Library.V1.MoveBookRequest, global::Google.Example.Library.V1.Book> __Method_MoveBook = new Method<global::Google.Example.Library.V1.MoveBookRequest, global::Google.Example.Library.V1.Book>( MethodType.Unary, __ServiceName, "MoveBook", __Marshaller_MoveBookRequest, __Marshaller_Book); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Google.Example.Library.V1.LibraryReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of LibraryService</summary> public abstract class LibraryServiceBase { /// <summary> /// Creates a shelf, and returns the new Shelf. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Example.Library.V1.Shelf> CreateShelf(global::Google.Example.Library.V1.CreateShelfRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Gets a shelf. Returns NOT_FOUND if the shelf does not exist. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Example.Library.V1.Shelf> GetShelf(global::Google.Example.Library.V1.GetShelfRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Lists shelves. The order is unspecified but deterministic. Newly created /// shelves will not necessarily be added to the end of this list. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Example.Library.V1.ListShelvesResponse> ListShelves(global::Google.Example.Library.V1.ListShelvesRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Deletes a shelf. Returns NOT_FOUND if the shelf does not exist. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteShelf(global::Google.Example.Library.V1.DeleteShelfRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Merges two shelves by adding all books from the shelf named /// `other_shelf_name` to shelf `name`, and deletes /// `other_shelf_name`. Returns the updated shelf. /// The book ids of the moved books may not be the same as the original books. /// /// Returns NOT_FOUND if either shelf does not exist. /// This call is a no-op if the specified shelves are the same. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Example.Library.V1.Shelf> MergeShelves(global::Google.Example.Library.V1.MergeShelvesRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Creates a book, and returns the new Book. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Example.Library.V1.Book> CreateBook(global::Google.Example.Library.V1.CreateBookRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Gets a book. Returns NOT_FOUND if the book does not exist. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Example.Library.V1.Book> GetBook(global::Google.Example.Library.V1.GetBookRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Lists books in a shelf. The order is unspecified but deterministic. Newly /// created books will not necessarily be added to the end of this list. /// Returns NOT_FOUND if the shelf does not exist. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Example.Library.V1.ListBooksResponse> ListBooks(global::Google.Example.Library.V1.ListBooksRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Deletes a book. Returns NOT_FOUND if the book does not exist. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteBook(global::Google.Example.Library.V1.DeleteBookRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Updates a book. Returns INVALID_ARGUMENT if the name of the book /// is non-empty and does equal the previous name. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Example.Library.V1.Book> UpdateBook(global::Google.Example.Library.V1.UpdateBookRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Moves a book to another shelf, and returns the new book. The book /// id of the new book may not be the same as the original book. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Example.Library.V1.Book> MoveBook(global::Google.Example.Library.V1.MoveBookRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } } /// <summary>Client for LibraryService</summary> public class LibraryServiceClient : ClientBase<LibraryServiceClient> { /// <summary>Creates a new client for LibraryService</summary> /// <param name="channel">The channel to use to make remote calls.</param> public LibraryServiceClient(Channel channel) : base(channel) { } /// <summary>Creates a new client for LibraryService that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public LibraryServiceClient(CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected LibraryServiceClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected LibraryServiceClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Creates a shelf, and returns the new Shelf. /// </summary> public virtual global::Google.Example.Library.V1.Shelf CreateShelf(global::Google.Example.Library.V1.CreateShelfRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateShelf(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a shelf, and returns the new Shelf. /// </summary> public virtual global::Google.Example.Library.V1.Shelf CreateShelf(global::Google.Example.Library.V1.CreateShelfRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateShelf, null, options, request); } /// <summary> /// Creates a shelf, and returns the new Shelf. /// </summary> public virtual AsyncUnaryCall<global::Google.Example.Library.V1.Shelf> CreateShelfAsync(global::Google.Example.Library.V1.CreateShelfRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateShelfAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a shelf, and returns the new Shelf. /// </summary> public virtual AsyncUnaryCall<global::Google.Example.Library.V1.Shelf> CreateShelfAsync(global::Google.Example.Library.V1.CreateShelfRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateShelf, null, options, request); } /// <summary> /// Gets a shelf. Returns NOT_FOUND if the shelf does not exist. /// </summary> public virtual global::Google.Example.Library.V1.Shelf GetShelf(global::Google.Example.Library.V1.GetShelfRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetShelf(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a shelf. Returns NOT_FOUND if the shelf does not exist. /// </summary> public virtual global::Google.Example.Library.V1.Shelf GetShelf(global::Google.Example.Library.V1.GetShelfRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetShelf, null, options, request); } /// <summary> /// Gets a shelf. Returns NOT_FOUND if the shelf does not exist. /// </summary> public virtual AsyncUnaryCall<global::Google.Example.Library.V1.Shelf> GetShelfAsync(global::Google.Example.Library.V1.GetShelfRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetShelfAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a shelf. Returns NOT_FOUND if the shelf does not exist. /// </summary> public virtual AsyncUnaryCall<global::Google.Example.Library.V1.Shelf> GetShelfAsync(global::Google.Example.Library.V1.GetShelfRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetShelf, null, options, request); } /// <summary> /// Lists shelves. The order is unspecified but deterministic. Newly created /// shelves will not necessarily be added to the end of this list. /// </summary> public virtual global::Google.Example.Library.V1.ListShelvesResponse ListShelves(global::Google.Example.Library.V1.ListShelvesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListShelves(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists shelves. The order is unspecified but deterministic. Newly created /// shelves will not necessarily be added to the end of this list. /// </summary> public virtual global::Google.Example.Library.V1.ListShelvesResponse ListShelves(global::Google.Example.Library.V1.ListShelvesRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListShelves, null, options, request); } /// <summary> /// Lists shelves. The order is unspecified but deterministic. Newly created /// shelves will not necessarily be added to the end of this list. /// </summary> public virtual AsyncUnaryCall<global::Google.Example.Library.V1.ListShelvesResponse> ListShelvesAsync(global::Google.Example.Library.V1.ListShelvesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListShelvesAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists shelves. The order is unspecified but deterministic. Newly created /// shelves will not necessarily be added to the end of this list. /// </summary> public virtual AsyncUnaryCall<global::Google.Example.Library.V1.ListShelvesResponse> ListShelvesAsync(global::Google.Example.Library.V1.ListShelvesRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListShelves, null, options, request); } /// <summary> /// Deletes a shelf. Returns NOT_FOUND if the shelf does not exist. /// </summary> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteShelf(global::Google.Example.Library.V1.DeleteShelfRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteShelf(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes a shelf. Returns NOT_FOUND if the shelf does not exist. /// </summary> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteShelf(global::Google.Example.Library.V1.DeleteShelfRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteShelf, null, options, request); } /// <summary> /// Deletes a shelf. Returns NOT_FOUND if the shelf does not exist. /// </summary> public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteShelfAsync(global::Google.Example.Library.V1.DeleteShelfRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteShelfAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes a shelf. Returns NOT_FOUND if the shelf does not exist. /// </summary> public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteShelfAsync(global::Google.Example.Library.V1.DeleteShelfRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteShelf, null, options, request); } /// <summary> /// Merges two shelves by adding all books from the shelf named /// `other_shelf_name` to shelf `name`, and deletes /// `other_shelf_name`. Returns the updated shelf. /// The book ids of the moved books may not be the same as the original books. /// /// Returns NOT_FOUND if either shelf does not exist. /// This call is a no-op if the specified shelves are the same. /// </summary> public virtual global::Google.Example.Library.V1.Shelf MergeShelves(global::Google.Example.Library.V1.MergeShelvesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return MergeShelves(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Merges two shelves by adding all books from the shelf named /// `other_shelf_name` to shelf `name`, and deletes /// `other_shelf_name`. Returns the updated shelf. /// The book ids of the moved books may not be the same as the original books. /// /// Returns NOT_FOUND if either shelf does not exist. /// This call is a no-op if the specified shelves are the same. /// </summary> public virtual global::Google.Example.Library.V1.Shelf MergeShelves(global::Google.Example.Library.V1.MergeShelvesRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_MergeShelves, null, options, request); } /// <summary> /// Merges two shelves by adding all books from the shelf named /// `other_shelf_name` to shelf `name`, and deletes /// `other_shelf_name`. Returns the updated shelf. /// The book ids of the moved books may not be the same as the original books. /// /// Returns NOT_FOUND if either shelf does not exist. /// This call is a no-op if the specified shelves are the same. /// </summary> public virtual AsyncUnaryCall<global::Google.Example.Library.V1.Shelf> MergeShelvesAsync(global::Google.Example.Library.V1.MergeShelvesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return MergeShelvesAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Merges two shelves by adding all books from the shelf named /// `other_shelf_name` to shelf `name`, and deletes /// `other_shelf_name`. Returns the updated shelf. /// The book ids of the moved books may not be the same as the original books. /// /// Returns NOT_FOUND if either shelf does not exist. /// This call is a no-op if the specified shelves are the same. /// </summary> public virtual AsyncUnaryCall<global::Google.Example.Library.V1.Shelf> MergeShelvesAsync(global::Google.Example.Library.V1.MergeShelvesRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_MergeShelves, null, options, request); } /// <summary> /// Creates a book, and returns the new Book. /// </summary> public virtual global::Google.Example.Library.V1.Book CreateBook(global::Google.Example.Library.V1.CreateBookRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateBook(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a book, and returns the new Book. /// </summary> public virtual global::Google.Example.Library.V1.Book CreateBook(global::Google.Example.Library.V1.CreateBookRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateBook, null, options, request); } /// <summary> /// Creates a book, and returns the new Book. /// </summary> public virtual AsyncUnaryCall<global::Google.Example.Library.V1.Book> CreateBookAsync(global::Google.Example.Library.V1.CreateBookRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateBookAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a book, and returns the new Book. /// </summary> public virtual AsyncUnaryCall<global::Google.Example.Library.V1.Book> CreateBookAsync(global::Google.Example.Library.V1.CreateBookRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateBook, null, options, request); } /// <summary> /// Gets a book. Returns NOT_FOUND if the book does not exist. /// </summary> public virtual global::Google.Example.Library.V1.Book GetBook(global::Google.Example.Library.V1.GetBookRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetBook(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a book. Returns NOT_FOUND if the book does not exist. /// </summary> public virtual global::Google.Example.Library.V1.Book GetBook(global::Google.Example.Library.V1.GetBookRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetBook, null, options, request); } /// <summary> /// Gets a book. Returns NOT_FOUND if the book does not exist. /// </summary> public virtual AsyncUnaryCall<global::Google.Example.Library.V1.Book> GetBookAsync(global::Google.Example.Library.V1.GetBookRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetBookAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a book. Returns NOT_FOUND if the book does not exist. /// </summary> public virtual AsyncUnaryCall<global::Google.Example.Library.V1.Book> GetBookAsync(global::Google.Example.Library.V1.GetBookRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetBook, null, options, request); } /// <summary> /// Lists books in a shelf. The order is unspecified but deterministic. Newly /// created books will not necessarily be added to the end of this list. /// Returns NOT_FOUND if the shelf does not exist. /// </summary> public virtual global::Google.Example.Library.V1.ListBooksResponse ListBooks(global::Google.Example.Library.V1.ListBooksRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListBooks(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists books in a shelf. The order is unspecified but deterministic. Newly /// created books will not necessarily be added to the end of this list. /// Returns NOT_FOUND if the shelf does not exist. /// </summary> public virtual global::Google.Example.Library.V1.ListBooksResponse ListBooks(global::Google.Example.Library.V1.ListBooksRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListBooks, null, options, request); } /// <summary> /// Lists books in a shelf. The order is unspecified but deterministic. Newly /// created books will not necessarily be added to the end of this list. /// Returns NOT_FOUND if the shelf does not exist. /// </summary> public virtual AsyncUnaryCall<global::Google.Example.Library.V1.ListBooksResponse> ListBooksAsync(global::Google.Example.Library.V1.ListBooksRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListBooksAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists books in a shelf. The order is unspecified but deterministic. Newly /// created books will not necessarily be added to the end of this list. /// Returns NOT_FOUND if the shelf does not exist. /// </summary> public virtual AsyncUnaryCall<global::Google.Example.Library.V1.ListBooksResponse> ListBooksAsync(global::Google.Example.Library.V1.ListBooksRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListBooks, null, options, request); } /// <summary> /// Deletes a book. Returns NOT_FOUND if the book does not exist. /// </summary> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteBook(global::Google.Example.Library.V1.DeleteBookRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteBook(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes a book. Returns NOT_FOUND if the book does not exist. /// </summary> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteBook(global::Google.Example.Library.V1.DeleteBookRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteBook, null, options, request); } /// <summary> /// Deletes a book. Returns NOT_FOUND if the book does not exist. /// </summary> public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteBookAsync(global::Google.Example.Library.V1.DeleteBookRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteBookAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes a book. Returns NOT_FOUND if the book does not exist. /// </summary> public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteBookAsync(global::Google.Example.Library.V1.DeleteBookRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteBook, null, options, request); } /// <summary> /// Updates a book. Returns INVALID_ARGUMENT if the name of the book /// is non-empty and does equal the previous name. /// </summary> public virtual global::Google.Example.Library.V1.Book UpdateBook(global::Google.Example.Library.V1.UpdateBookRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateBook(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates a book. Returns INVALID_ARGUMENT if the name of the book /// is non-empty and does equal the previous name. /// </summary> public virtual global::Google.Example.Library.V1.Book UpdateBook(global::Google.Example.Library.V1.UpdateBookRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpdateBook, null, options, request); } /// <summary> /// Updates a book. Returns INVALID_ARGUMENT if the name of the book /// is non-empty and does equal the previous name. /// </summary> public virtual AsyncUnaryCall<global::Google.Example.Library.V1.Book> UpdateBookAsync(global::Google.Example.Library.V1.UpdateBookRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateBookAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates a book. Returns INVALID_ARGUMENT if the name of the book /// is non-empty and does equal the previous name. /// </summary> public virtual AsyncUnaryCall<global::Google.Example.Library.V1.Book> UpdateBookAsync(global::Google.Example.Library.V1.UpdateBookRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpdateBook, null, options, request); } /// <summary> /// Moves a book to another shelf, and returns the new book. The book /// id of the new book may not be the same as the original book. /// </summary> public virtual global::Google.Example.Library.V1.Book MoveBook(global::Google.Example.Library.V1.MoveBookRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return MoveBook(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Moves a book to another shelf, and returns the new book. The book /// id of the new book may not be the same as the original book. /// </summary> public virtual global::Google.Example.Library.V1.Book MoveBook(global::Google.Example.Library.V1.MoveBookRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_MoveBook, null, options, request); } /// <summary> /// Moves a book to another shelf, and returns the new book. The book /// id of the new book may not be the same as the original book. /// </summary> public virtual AsyncUnaryCall<global::Google.Example.Library.V1.Book> MoveBookAsync(global::Google.Example.Library.V1.MoveBookRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return MoveBookAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Moves a book to another shelf, and returns the new book. The book /// id of the new book may not be the same as the original book. /// </summary> public virtual AsyncUnaryCall<global::Google.Example.Library.V1.Book> MoveBookAsync(global::Google.Example.Library.V1.MoveBookRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_MoveBook, null, options, request); } protected override LibraryServiceClient NewInstance(ClientBaseConfiguration configuration) { return new LibraryServiceClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> public static ServerServiceDefinition BindService(LibraryServiceBase serviceImpl) { return ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_CreateShelf, serviceImpl.CreateShelf) .AddMethod(__Method_GetShelf, serviceImpl.GetShelf) .AddMethod(__Method_ListShelves, serviceImpl.ListShelves) .AddMethod(__Method_DeleteShelf, serviceImpl.DeleteShelf) .AddMethod(__Method_MergeShelves, serviceImpl.MergeShelves) .AddMethod(__Method_CreateBook, serviceImpl.CreateBook) .AddMethod(__Method_GetBook, serviceImpl.GetBook) .AddMethod(__Method_ListBooks, serviceImpl.ListBooks) .AddMethod(__Method_DeleteBook, serviceImpl.DeleteBook) .AddMethod(__Method_UpdateBook, serviceImpl.UpdateBook) .AddMethod(__Method_MoveBook, serviceImpl.MoveBook).Build(); } } } #endregion
using System; using System.Security.Cryptography; namespace annfs1 { /// <summary> /// Extensions class contains extension methods to work with matrices /// </summary> public static class Extensions { public static double MultiplicationCounter = 0; public static void ResetMultiplicationCounter() { MultiplicationCounter = 0; } /// <summary> /// Extension method which writes a matrix to the standard out. /// </summary> /// <param name="x">The matrix to write</param> public static void Write(this double[,] x, int decimals = 10) { Console.WriteLine("- - -"); for (int i = 0; i < x.GetLength(0); i++) { for (int j = 0; j < x.GetLength(1); j++) { System.Console.Write($"{Math.Round(x[i, j], decimals)} "); } System.Console.WriteLine(); } Console.WriteLine("- - -"); } /// <summary> /// Extension method for normalizing a matrix. Normalization is changing the values in the matrix for them to be in the [0.0, 1.0] range. /// </summary> /// <param name="x">The matrix to normalize</param> /// <param name="maxValue">Optional parameter, maximum expected value. If omitted, the method will first find the maximum value in the provided matrix.</param> /// <returns>The normalized matrix</returns> public static double[,] Normalize(this double[,] x, double maxValue = Double.MinValue) { var max = 0.0; if (maxValue != Double.MinValue) { max = maxValue; } else { foreach (var n in x) { if (Math.Abs(n) > max) max = n; } } // same dimensions var result = new double[x.GetLength(0), x.GetLength(1)]; for (int i = 0; i < x.GetLength(0); i++) { for (int j = 0; j < x.GetLength(1); j++) { result[i, j] = x[i, j] / max; MultiplicationCounter++; } } return result; } /// <summary> /// Performs matrix multiplication. The dimensions must be compatible. /// </summary> /// <param name="x">The first matrix</param> /// <param name="y">The second matrix</param> /// <returns>The resulting matrix</returns> public static double[,] Dot(this double[,] x, double[,] y) { if (x.GetLength(1) != y.GetLength(0)) { throw new InvalidOperationException( $"Invalid matrix dimensions for multiplication: [{x.GetLength(0)}, {x.GetLength(1)}] x [{y.GetLength(0)}, {y.GetLength(1)}] ."); } // rows of first and columns of second var result = new double[x.GetLength(0), y.GetLength(1)]; for (int i = 0; i < result.GetLength(0); i++) { for (int j = 0; j < result.GetLength(1); j++) { var sum = 0.0; for (int k = 0; k < x.GetLength(1); k++) { sum += x[i, k] * y[k, j]; MultiplicationCounter++; } result[i, j] = sum; } } return result; } /// <summary> /// Takes a matrix, and fills it with random values between minimum and maximum /// </summary> /// <param name="x">Source matrix</param> /// <returns>The source matrix, but with randomized values</returns> public static double[,] Randomize(this double[,] x, double minimum, double maximum) { var r = new Random(); for (int i = 0; i < x.GetLength(0); i++) { for (int j = 0; j < x.GetLength(1); j++) { x[i, j] = (maximum - minimum) * r.NextDouble() + minimum; MultiplicationCounter++; } } return x; } /// <summary> /// Converts double[,] matrix to double[][] which is useful in some scenarios. /// </summary> /// <param name="x">Source double[,] matrix</param> /// <returns>The same matrix as source but double[][]</returns> public static double[][] Convert(this double[,] x) { var r = new double [x.GetLength(0)][]; for(int i = 0; i < x.GetLength(0); i++) { r[i] = new double[x.GetLength(1)]; for (int j = 0; j < x.GetLength(1); j++) { r[i][j] = x[i,j]; } } return r; } /// <summary> /// Converts double[][] matrix to double[,] which is useful in some scenarios. /// </summary> /// <param name="x">Source double[][] matrix</param> /// <returns>The same matrix as source but double[,]</returns> public static double[,] Convert(this double[][] x) { var r = new double [x.Length, x[0].Length]; for(int i = 0; i < x.Length; i++) { for (int j = 0; j < x[0].Length; j++) { r[i,j] = x[i][j]; } } return r; } /// <summary> /// Converts double[][] matrix to double[,] which is useful in some scenarios. /// </summary> /// <param name="x">Source double[][] matrix</param> /// <returns>The same matrix as source but double[,]</returns> public static double[,] Convert(this double[] x) { var r = new double [1, x.Length]; for (int i = 0; i < x.Length; i++) { r[0,i] = x[i]; } return r; } /// <summary> /// Rounds all the values in a matrix. /// </summary> /// <param name="x">Matrix to be rounded</param> /// <returns>Matrix with rounded values</returns> public static double[,] Round(this double[,] x) { for (int i = 0; i < x.GetLength(0); i++) { for (int j = 0; j < x.GetLength(1); j++) { MultiplicationCounter++; x[i, j] = Math.Round(x[i, j]); } } return x; } /// <summary> /// Removes padding (anything on the sides) from a matrix /// </summary> /// <param name="x">The padded matrix</param> /// <param name="pad">Number of rows/columns to remove</param> /// <returns>The matrix without padding</returns> public static double[,] RemovePadding(this double[,] x, int pad) { var o = new double[x.GetLength(0) - 2 * pad, x.GetLength(1) - 2 * pad]; MultiplicationCounter += 2; int k = 0; int l = 0; for (int i = pad; i < x.GetLength(0) - pad; i++) { for (int j = pad; j < x.GetLength(1) - pad; j++) { o[k, l] = x[i, j]; l++; } k++; l = 0; } return o; } /// <summary> /// Pads a matrix with certain value (default: 0d) /// </summary> /// <param name="x">The matrix to be padded</param> /// <param name="pad">Number of rows/columns to add</param> /// <param name="padWith">The value to be used for padding</param> /// <returns>The padded matrix</returns> public static double[,] Pad(this double[,] x, int pad, double padWith = 0d) { var o = new double[x.GetLength(0) + 2 * pad, x.GetLength(1) + 2 * pad]; MultiplicationCounter += 2; for (int i = 0; i < o.GetLength(0); i++) for (int j = 0; j < o.GetLength(1); j++) { o[i, j] = padWith; } int k = 0; int l = 0; for (int i = pad; i < o.GetLength(0) - pad; i++) { for (int j = pad; j < o.GetLength(1) - pad; j++) { o[i, j] = x[k, l]; l++; } k++; l = 0; } return o; } /// <summary> /// Rotates a matrix 180 degrees (horizontal flip) /// </summary> /// <param name="x">The matrix to be rotated</param> /// <returns>The rotated matrix</returns> public static double[,] Rotate(this double[,] x) { var n = x.GetLength(0); var ret = new double[n, n]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { ret[i, j] = x[n - j - 1, i]; } } return ret; } public static double[,] Transpose(this double[,] matrix) { int w = matrix.GetLength(0); int h = matrix.GetLength(1); double[,] result = new double[h, w]; for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { result[j, i] = matrix[i, j]; } } return result; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Threading.Tasks; using Azure.Core; using Azure.Core.Pipeline; using Azure.Storage.Queues.Models; using Azure.Storage.Shared; namespace Azure.Storage.Queues { /// <summary> /// Provides the client configuration options for connecting to Azure Queue /// Storage /// </summary> public class QueueClientOptions : ClientOptions, ISupportsTenantIdChallenges { /// <summary> /// The Latest service version supported by this client library. /// </summary> internal const ServiceVersion LatestVersion = StorageVersionExtensions.LatestVersion; /// <summary> /// The versions of Azure Queue Storage supported by this client /// library. /// /// For more information, see /// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/versioning-for-the-azure-storage-services"> /// Versioning for the Azure Storage services</see>. /// </summary> public enum ServiceVersion { #pragma warning disable CA1707 // Identifiers should not contain underscores /// <summary> /// The 2019-02-02 service version described at /// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/version-2019-02-02"> /// Version 2019-02-02</see>. /// </summary> V2019_02_02 = 1, /// <summary> /// The 2019-07-07 service version described at /// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/version-2019-07-07"> /// Version 2019-07-07</see>. /// </summary> V2019_07_07 = 2, /// <summary> /// The 2019-12-12 service version. /// </summary> V2019_12_12 = 3, /// <summary> /// The 2020-02-10 service version. /// </summary> V2020_02_10 = 4, /// <summary> /// The 2020-04-08 service version. /// </summary> V2020_04_08 = 5, /// <summary> /// The 2020-06-12 service version. /// </summary> V2020_06_12 = 6, /// <summary> /// The 2020-08-14 service version. /// </summary> V2020_08_04 = 7, /// <summary> /// The 2020-10-02 service version. /// </summary> V2020_10_02 = 8, /// <summary> /// The 2020-12-06 service version. /// </summary> V2020_12_06 = 9 #pragma warning restore CA1707 // Identifiers should not contain underscores } /// <summary> /// Gets the <see cref="ServiceVersion"/> of the service API used when /// making requests. For more, see /// For more information, see /// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/versioning-for-the-azure-storage-services"> /// Versioning for the Azure Storage services</see>. /// </summary> public ServiceVersion Version { get; } /// <summary> /// Initializes a new instance of the <see cref="QueueClientOptions"/> /// class. /// </summary> /// <param name="version"> /// The <see cref="ServiceVersion"/> of the service API used when /// making requests. /// </param> public QueueClientOptions(ServiceVersion version = LatestVersion) { if (ServiceVersion.V2019_02_02 <= version && version <= StorageVersionExtensions.MaxVersion) { Version = version; } else { throw Errors.VersionNotSupported(nameof(version)); } this.Initialize(); AddHeadersAndQueryParameters(); } /// <summary> /// Gets or sets the secondary storage <see cref="Uri"/> that can be read from for the storage account if the /// account is enabled for RA-GRS. /// /// If this property is set, the secondary Uri will be used for GET or HEAD requests during retries. /// If the status of the response from the secondary Uri is a 404, then subsequent retries for /// the request will not use the secondary Uri again, as this indicates that the resource /// may not have propagated there yet. Otherwise, subsequent retries will alternate back and forth /// between primary and secondary Uri. /// </summary> public Uri GeoRedundantSecondaryUri { get; set; } /// <summary> /// Gets or sets a message encoding that determines how <see cref="QueueMessage.Body"/> is represented in HTTP requests and responses. /// The default is <see cref="QueueMessageEncoding.None"/>. /// </summary> public QueueMessageEncoding MessageEncoding { get; set; } = QueueMessageEncoding.None; /// <inheritdoc /> public bool EnableTenantDiscovery { get; set; } /// <summary> /// Optional. Performs the tasks needed when a message is received or peaked from the queue but cannot be decoded. /// /// <para>Such message can be received or peaked when <see cref="QueueClient"/> is expecting certain <see cref="QueueMessageEncoding"/> /// but there's another producer that is not encoding messages in expected way. I.e. the queue contains messages with different encoding.</para> /// /// <para><see cref="QueueMessageDecodingFailedEventArgs"/> contains <see cref="QueueClient"/> that has received the message as well as /// <see cref="QueueMessageDecodingFailedEventArgs.ReceivedMessage"/> or <see cref="QueueMessageDecodingFailedEventArgs.PeekedMessage"/> /// with raw body, i.e. no decoding will be attempted so that /// body can be inspected as has been received from the queue.</para> /// /// <para>The <see cref="QueueClient"/> won't attempt to remove the message from the queue. Therefore such handling should be included into /// the event handler itself.</para> /// /// <para>The handler is potentially invoked by both synchronous and asynchronous receive and peek APIs. Therefore implementation of the handler should align with /// <see cref="QueueClient"/> APIs that are being used. /// See <see cref="SyncAsyncEventHandler{T}"/> about how to implement handler correctly. The example below shows a handler with all possible cases explored. /// <code snippet="Snippet:Azure_Storage_Queues_Samples_Sample03_MessageEncoding_MessageDecodingFailedHandlerAsync" language="csharp"> /// QueueClientOptions queueClientOptions = new QueueClientOptions() /// { /// MessageEncoding = QueueMessageEncoding.Base64 /// }; /// /// queueClientOptions.MessageDecodingFailed += async (QueueMessageDecodingFailedEventArgs args) =&gt; /// { /// if (args.PeekedMessage != null) /// { /// Console.WriteLine($&quot;Invalid message has been peeked, message id={args.PeekedMessage.MessageId} body={args.PeekedMessage.Body}&quot;); /// } /// else if (args.ReceivedMessage != null) /// { /// Console.WriteLine($&quot;Invalid message has been received, message id={args.ReceivedMessage.MessageId} body={args.ReceivedMessage.Body}&quot;); /// /// if (args.IsRunningSynchronously) /// { /// args.Queue.DeleteMessage(args.ReceivedMessage.MessageId, args.ReceivedMessage.PopReceipt); /// } /// else /// { /// await args.Queue.DeleteMessageAsync(args.ReceivedMessage.MessageId, args.ReceivedMessage.PopReceipt); /// } /// } /// }; /// /// QueueClient queueClient = new QueueClient(connectionString, queueName, queueClientOptions); /// </code> /// </para> /// </summary> public event SyncAsyncEventHandler<QueueMessageDecodingFailedEventArgs> MessageDecodingFailed; internal SyncAsyncEventHandler<QueueMessageDecodingFailedEventArgs> GetMessageDecodingFailedHandlers() => MessageDecodingFailed; #region Advanced Options internal ClientSideEncryptionOptions _clientSideEncryptionOptions; #endregion /// <summary> /// Add headers and query parameters in <see cref="DiagnosticsOptions.LoggedHeaderNames"/> and <see cref="DiagnosticsOptions.LoggedQueryParameters"/> /// </summary> private void AddHeadersAndQueryParameters() { Diagnostics.LoggedHeaderNames.Add("Access-Control-Allow-Origin"); Diagnostics.LoggedHeaderNames.Add("x-ms-date"); Diagnostics.LoggedHeaderNames.Add("x-ms-error-code"); Diagnostics.LoggedHeaderNames.Add("x-ms-request-id"); Diagnostics.LoggedHeaderNames.Add("x-ms-version"); Diagnostics.LoggedHeaderNames.Add("x-ms-approximate-messages-count"); Diagnostics.LoggedHeaderNames.Add("x-ms-popreceipt"); Diagnostics.LoggedHeaderNames.Add("x-ms-time-next-visible"); Diagnostics.LoggedQueryParameters.Add("comp"); Diagnostics.LoggedQueryParameters.Add("maxresults"); Diagnostics.LoggedQueryParameters.Add("rscc"); Diagnostics.LoggedQueryParameters.Add("rscd"); Diagnostics.LoggedQueryParameters.Add("rsce"); Diagnostics.LoggedQueryParameters.Add("rscl"); Diagnostics.LoggedQueryParameters.Add("rsct"); Diagnostics.LoggedQueryParameters.Add("se"); Diagnostics.LoggedQueryParameters.Add("si"); Diagnostics.LoggedQueryParameters.Add("sip"); Diagnostics.LoggedQueryParameters.Add("sp"); Diagnostics.LoggedQueryParameters.Add("spr"); Diagnostics.LoggedQueryParameters.Add("sr"); Diagnostics.LoggedQueryParameters.Add("srt"); Diagnostics.LoggedQueryParameters.Add("ss"); Diagnostics.LoggedQueryParameters.Add("st"); Diagnostics.LoggedQueryParameters.Add("sv"); Diagnostics.LoggedQueryParameters.Add("include"); Diagnostics.LoggedQueryParameters.Add("marker"); Diagnostics.LoggedQueryParameters.Add("prefix"); Diagnostics.LoggedQueryParameters.Add("messagettl"); Diagnostics.LoggedQueryParameters.Add("numofmessages"); Diagnostics.LoggedQueryParameters.Add("peekonly"); Diagnostics.LoggedQueryParameters.Add("popreceipt"); Diagnostics.LoggedQueryParameters.Add("visibilitytimeout"); } /// <summary> /// Create an HttpPipeline from QueueClientOptions. /// </summary> /// <param name="authentication">Optional authentication policy.</param> /// <returns>An HttpPipeline to use for Storage requests.</returns> internal HttpPipeline Build(HttpPipelinePolicy authentication = null) { return this.Build(authentication, GeoRedundantSecondaryUri); } /// <summary> /// Create an HttpPipeline from QueueClientOptions. /// </summary> /// <param name="credentials">Optional authentication credentials.</param> /// <returns>An HttpPipeline to use for Storage requests.</returns> internal HttpPipeline Build(object credentials) { return this.Build(credentials, GeoRedundantSecondaryUri); } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Searchservice { using Microsoft.Rest; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// DataSources operations. /// </summary> public partial class DataSources : IServiceOperations<SearchandStorage>, IDataSources { /// <summary> /// Initializes a new instance of the DataSources class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public DataSources(SearchandStorage client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the SearchandStorage /// </summary> public SearchandStorage Client { get; private set; } /// <summary> /// Creates a new Azure Search datasource or updates a datasource if it already /// exists. /// <see href="https://msdn.microsoft.com/library/azure/dn946900.aspx" /> /// </summary> /// <param name='dataSourceName'> /// The name of the datasource to create or update. /// </param> /// <param name='dataSource'> /// The definition of the datasource to create or update. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<DataSource>> CreateOrUpdateWithHttpMessagesAsync(string dataSourceName, DataSource dataSource, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (dataSourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "dataSourceName"); } if (dataSource == null) { throw new ValidationException(ValidationRules.CannotBeNull, "dataSource"); } if (dataSource != null) { dataSource.Validate(); } string apiVersion = "2015-02-28"; System.Guid? clientRequestId = default(System.Guid?); if (searchRequestOptions != null) { clientRequestId = searchRequestOptions.ClientRequestId; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("dataSourceName", dataSourceName); tracingParameters.Add("dataSource", dataSource); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datasources('{dataSourceName}')").ToString(); _url = _url.Replace("{dataSourceName}", System.Uri.EscapeDataString(dataSourceName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, Client.SerializationSettings).Trim('"')); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(dataSource != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(dataSource, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<DataSource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<DataSource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<DataSource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes an Azure Search datasource. /// <see href="https://msdn.microsoft.com/library/azure/dn946881.aspx" /> /// </summary> /// <param name='dataSourceName'> /// The name of the datasource to delete. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> DeleteWithHttpMessagesAsync(string dataSourceName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (dataSourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "dataSourceName"); } string apiVersion = "2015-02-28"; System.Guid? clientRequestId = default(System.Guid?); if (searchRequestOptions != null) { clientRequestId = searchRequestOptions.ClientRequestId; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("dataSourceName", dataSourceName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datasources('{dataSourceName}')").ToString(); _url = _url.Replace("{dataSourceName}", System.Uri.EscapeDataString(dataSourceName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, Client.SerializationSettings).Trim('"')); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 404) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Retrieves a datasource definition from Azure Search. /// <see href="https://msdn.microsoft.com/library/azure/dn946893.aspx" /> /// </summary> /// <param name='dataSourceName'> /// The name of the datasource to retrieve. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<DataSource>> GetWithHttpMessagesAsync(string dataSourceName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (dataSourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "dataSourceName"); } string apiVersion = "2015-02-28"; System.Guid? clientRequestId = default(System.Guid?); if (searchRequestOptions != null) { clientRequestId = searchRequestOptions.ClientRequestId; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("dataSourceName", dataSourceName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datasources('{dataSourceName}')").ToString(); _url = _url.Replace("{dataSourceName}", System.Uri.EscapeDataString(dataSourceName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, Client.SerializationSettings).Trim('"')); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<DataSource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<DataSource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists all datasources available for an Azure Search service. /// <see href="https://msdn.microsoft.com/library/azure/dn946878.aspx" /> /// </summary> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<DataSourceListResult>> ListWithHttpMessagesAsync(SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { string apiVersion = "2015-02-28"; System.Guid? clientRequestId = default(System.Guid?); if (searchRequestOptions != null) { clientRequestId = searchRequestOptions.ClientRequestId; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datasources").ToString(); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, Client.SerializationSettings).Trim('"')); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<DataSourceListResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<DataSourceListResult>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates a new Azure Search datasource. /// <see href="https://msdn.microsoft.com/library/azure/dn946876.aspx" /> /// </summary> /// <param name='dataSource'> /// The definition of the datasource to create. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<DataSource>> CreateWithHttpMessagesAsync(DataSource dataSource, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (dataSource == null) { throw new ValidationException(ValidationRules.CannotBeNull, "dataSource"); } if (dataSource != null) { dataSource.Validate(); } string apiVersion = "2015-02-28"; System.Guid? clientRequestId = default(System.Guid?); if (searchRequestOptions != null) { clientRequestId = searchRequestOptions.ClientRequestId; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("dataSource", dataSource); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datasources").ToString(); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, Client.SerializationSettings).Trim('"')); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(dataSource != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(dataSource, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<DataSource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<DataSource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.Contracts; using System.Threading.Tasks; namespace System.IO { // This class implements a text reader that reads from a string. public class StringReader : TextReader { private string _s; private int _pos; private int _length; public StringReader(string s) { if (s == null) { throw new ArgumentNullException(nameof(s)); } _s = s; _length = s.Length; } public override void Close() { Dispose(true); } protected override void Dispose(bool disposing) { _s = null; _pos = 0; _length = 0; base.Dispose(disposing); } // Returns the next available character without actually reading it from // the underlying string. The current position of the StringReader is not // changed by this operation. The returned value is -1 if no further // characters are available. // [Pure] public override int Peek() { if (_s == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed); } if (_pos == _length) { return -1; } return _s[_pos]; } // Reads the next character from the underlying string. The returned value // is -1 if no further characters are available. // public override int Read() { if (_s == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed); } if (_pos == _length) { return -1; } return _s[_pos++]; } // Reads a block of characters. This method will read up to count // characters from this StringReader into the buffer character // array starting at position index. Returns the actual number of // characters read, or zero if the end of the string is reached. // public override int Read(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (_s == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed); } int n = _length - _pos; if (n > 0) { if (n > count) { n = count; } _s.CopyTo(_pos, buffer, index, n); _pos += n; } return n; } public override string ReadToEnd() { if (_s == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed); } string s; if (_pos == 0) { s = _s; } else { s = _s.Substring(_pos, _length - _pos); } _pos = _length; return s; } // Reads a line. A line is defined as a sequence of characters followed by // a carriage return ('\r'), a line feed ('\n'), or a carriage return // immediately followed by a line feed. The resulting string does not // contain the terminating carriage return and/or line feed. The returned // value is null if the end of the underlying string has been reached. // public override string ReadLine() { if (_s == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed); } int i = _pos; while (i < _length) { char ch = _s[i]; if (ch == '\r' || ch == '\n') { string result = _s.Substring(_pos, i - _pos); _pos = i + 1; if (ch == '\r' && _pos < _length && _s[_pos] == '\n') { _pos++; } return result; } i++; } if (i > _pos) { string result = _s.Substring(_pos, i - _pos); _pos = i; return result; } return null; } #region Task based Async APIs public override Task<string> ReadLineAsync() { return Task.FromResult(ReadLine()); } public override Task<string> ReadToEndAsync() { return Task.FromResult(ReadToEnd()); } public override Task<int> ReadBlockAsync(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return Task.FromResult(ReadBlock(buffer, index, count)); } public override Task<int> ReadAsync(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return Task.FromResult(Read(buffer, index, count)); } #endregion } }
using System; using System.Collections; using System.Threading; namespace SpicyPixel.Threading { public partial class FiberFactory { /// <summary> /// Start executing a new fiber using the default scheduler on the thread. /// </summary> /// <returns> /// Returns a <see cref="Fiber"/> /// that can be yielded against to wait for the fiber to complete. /// </returns> /// <param name='coroutine'> /// A couroutine to execute on the fiber. /// </param> public Fiber StartNew(IEnumerator coroutine) { return StartNew(coroutine, cancellationToken); } /// <summary> /// Start executing a new fiber using the default scheduler on the thread. /// </summary> /// <returns> /// Returns a <see cref="Fiber"/> /// that can be yielded against to wait for the fiber to complete. /// </returns> /// <param name='coroutine'> /// A couroutine to execute on the fiber. /// </param> /// <param name="cancellationToken">Cancellation token.</param> public Fiber StartNew(IEnumerator coroutine, CancellationToken cancellationToken) { return StartNew(coroutine, cancellationToken, GetScheduler()); } /// <summary> /// Start executing a new fiber using the specified scheduler. /// </summary> /// <returns> /// Returns a <see cref="Fiber"/> /// that can be yielded against to wait for the fiber to complete. /// </returns> /// <param name='coroutine'> /// A couroutine to execute on the fiber. /// </param> /// <param name='scheduler'> /// A scheduler to execute the fiber on. /// </param> public Fiber StartNew(IEnumerator coroutine, FiberScheduler scheduler) { return StartNew(coroutine, cancellationToken, scheduler); } /// <summary> /// Start executing a new fiber using the specified scheduler. /// </summary> /// <returns> /// Returns a <see cref="Fiber"/> /// that can be yielded against to wait for the fiber to complete. /// </returns> /// <param name='coroutine'> /// A couroutine to execute on the fiber. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <param name='scheduler'> /// A scheduler to execute the fiber on. /// </param> public Fiber StartNew(IEnumerator coroutine, CancellationToken cancellationToken, FiberScheduler scheduler) { var fiber = new Fiber(coroutine, cancellationToken); fiber.Start(scheduler); return fiber; } /// <summary> /// Start executing a new fiber using the default scheduler on the thread. /// </summary> /// <returns> /// Returns a <see cref="Fiber"/> /// that can be yielded against to wait for the fiber to complete. /// </returns> /// <param name='action'> /// A non-blocking action to execute on the fiber. /// </param> public Fiber StartNew(Action action) { return StartNew(action, cancellationToken); } /// <summary> /// Start executing a new fiber using the default scheduler on the thread. /// </summary> /// <returns> /// Returns a <see cref="Fiber"/> /// that can be yielded against to wait for the fiber to complete. /// </returns> /// <param name='action'> /// A non-blocking action to execute on the fiber. /// </param> /// <param name="cancellationToken">Cancellation token.</param> public Fiber StartNew(Action action, CancellationToken cancellationToken) { return StartNew(action, cancellationToken, GetScheduler()); } /// <summary> /// Start executing a new fiber using the default scheduler on the thread. /// </summary> /// <returns> /// Returns a <see cref="Fiber"/> /// that can be yielded against to wait for the fiber to complete. /// </returns> /// <param name='action'> /// A non-blocking action to execute on the fiber. /// </param> /// <param name='scheduler'> /// A scheduler to execute the fiber on. /// </param> public Fiber StartNew(Action action, FiberScheduler scheduler) { return StartNew(action, cancellationToken, scheduler); } /// <summary> /// Start executing a new fiber using the default scheduler on the thread. /// </summary> /// <returns> /// Returns a <see cref="Fiber"/> /// that can be yielded against to wait for the fiber to complete. /// </returns> /// <param name='action'> /// A non-blocking action to execute on the fiber. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <param name='scheduler'> /// A scheduler to execute the fiber on. /// </param> public Fiber StartNew(Action action, CancellationToken cancellationToken, FiberScheduler scheduler) { var fiber = new Fiber(action, cancellationToken); fiber.Start(scheduler); return fiber; } /// <summary> /// Start executing a new fiber using the default scheduler on the thread. /// </summary> /// <returns> /// Returns a <see cref="Fiber"/> /// that can be yielded against to wait for the fiber to complete. /// </returns> /// <param name='action'> /// A non-blocking action to execute on the fiber. /// </param> /// <param name='state'> /// State to pass to the action. /// </param> public Fiber StartNew(Action<object> action, object state) { return StartNew(action, state, cancellationToken); } /// <summary> /// Start executing a new fiber using the default scheduler on the thread. /// </summary> /// <returns> /// Returns a <see cref="Fiber"/> /// that can be yielded against to wait for the fiber to complete. /// </returns> /// <param name='action'> /// A non-blocking action to execute on the fiber. /// </param> /// <param name='state'> /// State to pass to the action. /// </param> /// <param name="cancellationToken">Cancellation token.</param> public Fiber StartNew(Action<object> action, object state, CancellationToken cancellationToken) { return StartNew(action, state, cancellationToken, GetScheduler()); } /// <summary> /// Start executing a new fiber using the default scheduler on the thread. /// </summary> /// <returns> /// Returns a <see cref="Fiber"/> /// that can be yielded against to wait for the fiber to complete. /// </returns> /// <param name='action'> /// A non-blocking action to execute on the fiber. /// </param> /// <param name='state'> /// State to pass to the action. /// </param> /// <param name='scheduler'> /// A scheduler to execute the fiber on. /// </param> public Fiber StartNew(Action<object> action, object state, FiberScheduler scheduler) { return StartNew(action, state, cancellationToken, scheduler); } /// <summary> /// Start executing a new fiber using the default scheduler on the thread. /// </summary> /// <returns> /// Returns a <see cref="Fiber"/> /// that can be yielded against to wait for the fiber to complete. /// </returns> /// <param name='action'> /// A non-blocking action to execute on the fiber. /// </param> /// <param name='state'> /// State to pass to the action. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <param name='scheduler'> /// A scheduler to execute the fiber on. /// </param> public Fiber StartNew(Action<object> action, object state, CancellationToken cancellationToken, FiberScheduler scheduler) { var fiber = new Fiber(action, state, cancellationToken); fiber.Start(scheduler); return fiber; } /// <summary> /// Initializes a new instance of the <see cref="SpicyPixel.Threading.Fiber"/> class. /// </summary> /// <param name='func'> /// A non-blocking function that returns a <see cref="Fiber"/> when complete. /// </param> public Fiber StartNew(Func<FiberInstruction> func) { return StartNew(func, cancellationToken); } /// <summary> /// Initializes a new instance of the <see cref="SpicyPixel.Threading.Fiber"/> class. /// </summary> /// <param name='func'> /// A non-blocking function that returns a <see cref="Fiber"/> when complete. /// </param> /// <param name="cancellationToken">Cancellation token.</param> public Fiber StartNew(Func<FiberInstruction> func, CancellationToken cancellationToken) { return StartNew(func, cancellationToken, GetScheduler()); } /// <summary> /// Initializes a new instance of the <see cref="SpicyPixel.Threading.Fiber"/> class. /// </summary> /// <param name='func'> /// A non-blocking function that returns a <see cref="Fiber"/> when complete. /// </param> /// <param name='scheduler'> /// A scheduler to execute the fiber on. /// </param> public Fiber StartNew(Func<FiberInstruction> func, FiberScheduler scheduler) { return StartNew(func, cancellationToken, scheduler); } /// <summary> /// Initializes a new instance of the <see cref="SpicyPixel.Threading.Fiber"/> class. /// </summary> /// <param name='func'> /// A non-blocking function that returns a <see cref="Fiber"/> when complete. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <param name='scheduler'> /// A scheduler to execute the fiber on. /// </param> public Fiber StartNew(Func<FiberInstruction> func, CancellationToken cancellationToken, FiberScheduler scheduler) { var fiber = new Fiber(func, cancellationToken); fiber.Start(scheduler); return fiber; } /// <summary> /// Initializes a new instance of the <see cref="SpicyPixel.Threading.Fiber"/> class. /// </summary> /// <param name='func'> /// A non-blocking function that returns a <see cref="Fiber"/> when complete. /// </param> /// <param name='state'> /// State to pass to the function. /// </param> public Fiber StartNew(Func<object, FiberInstruction> func, object state) { return StartNew(func, state, cancellationToken); } /// <summary> /// Initializes a new instance of the <see cref="SpicyPixel.Threading.Fiber"/> class. /// </summary> /// <param name='func'> /// A non-blocking function that returns a <see cref="Fiber"/> when complete. /// </param> /// <param name='state'> /// State to pass to the function. /// </param> /// <param name="cancellationToken">Cancellation token.</param> public Fiber StartNew(Func<object, FiberInstruction> func, object state, CancellationToken cancellationToken) { return StartNew(func, state, cancellationToken, GetScheduler()); } /// <summary> /// Initializes a new instance of the <see cref="SpicyPixel.Threading.Fiber"/> class. /// </summary> /// <param name='func'> /// A non-blocking function that returns a <see cref="Fiber"/> when complete. /// </param> /// <param name='state'> /// State to pass to the function. /// </param> /// <param name='scheduler'> /// A scheduler to execute the fiber on. /// </param> public Fiber StartNew(Func<object, FiberInstruction> func, object state, FiberScheduler scheduler) { return StartNew(func, state, cancellationToken, scheduler); } /// <summary> /// Initializes a new instance of the <see cref="SpicyPixel.Threading.Fiber"/> class. /// </summary> /// <param name='func'> /// A non-blocking function that returns a <see cref="Fiber"/> when complete. /// </param> /// <param name='state'> /// State to pass to the function. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <param name='scheduler'> /// A scheduler to execute the fiber on. /// </param> public Fiber StartNew(Func<object, FiberInstruction> func, object state, CancellationToken cancellationToken, FiberScheduler scheduler) { var fiber = new Fiber(func, state, cancellationToken); fiber.Start(scheduler); return fiber; } FiberScheduler GetScheduler() { return scheduler ?? FiberScheduler.Current; } } }
using System; using Bridge.Html5; using Bridge.Test.NUnit; namespace Bridge.ClientTest.Batch3.BridgeIssues { [Category(Constants.MODULE_ISSUES)] [TestFixture(TestNameFormat = "#1381 - {0}")] public class Bridge1381 { public static int value = 4; [Test] public static void TestReservedWordsUseCase() { try { int Date = 3; var m = new DateTime().Month; Assert.AreEqual(3, Date, "Date"); } catch (Exception) { Assert.Fail("Date variable"); } try { int String = 4; var s = new System.String()[0]; Assert.AreEqual(4, String, "String"); } catch (Exception) { Assert.Fail("String variable"); } try { int Number = 7; new Double(); new Float(); Assert.AreEqual(7, Number, "Number"); } catch (Exception) { Assert.Fail("Number variable"); } try { int document = 8; var c = Document.Children; Assert.AreEqual(8, document, "document"); } catch (Exception) { Assert.Fail("document variable"); } try { int Bridge = 9; Assert.AreEqual(4, value, "value"); Assert.AreEqual(9, Bridge, "Bridge"); } catch (Exception) { Assert.Fail("Bridge variable"); } } [Test] public static void TestReservedWordsNewBatch() { // Covers next batch of reserved words (except Date, Number, String that covered in TestReservedWordsUseCase test) try { var Array = 2; var m = new int[] { 0, 2, 1 }; var i = System.Array.IndexOf(m, 1); Assert.AreEqual(2, Array, "Array"); } catch (Exception) { Assert.Fail("Array variable"); } try { var eval = 3; Script.Eval(""); Assert.AreEqual(3, eval, "eval"); } catch (Exception) { Assert.Fail("eval variable"); } try { var hasOwnProperty = 4; var o = new object(); o.HasOwnProperty("v"); Assert.AreEqual(4, hasOwnProperty, "hasOwnProperty"); } catch (Exception) { Assert.Fail("hasOwnProperty variable"); } try { var Infinity = 5; var o = Script.Infinity; Assert.AreEqual(5, Infinity, "Infinity"); } catch (Exception) { Assert.Fail("Infinity variable"); } try { var isFinite = 6; var o = Script.IsFinite(null); Assert.AreEqual(6, isFinite, "isFinite"); } catch (Exception) { Assert.Fail("isFinite variable"); } try { var isNaN = 6; var o = Script.IsNaN(null); Assert.AreEqual(6, isNaN, "isNaN"); } catch (Exception) { Assert.Fail("isNaN variable"); } try { var isPrototypeOf = 7; var o = new object().IsPrototypeOf(null); Assert.AreEqual(7, isPrototypeOf, "isPrototypeOf"); } catch (Exception) { Assert.Fail("isPrototypeOf variable"); } try { var Math = 8; var o = System.Math.Abs(0); Assert.AreEqual(8, Math, "Math"); } catch (Exception) { Assert.Fail("Math variable"); } try { var NaN = 9; var o = Script.NaN; Assert.AreEqual(9, NaN, "NaN"); Assert.AreNotEqual(o, NaN, "Not NaN"); } catch (Exception) { Assert.Fail("NaN variable"); } try { var Object = 10; var o = new object(); Assert.AreEqual(10, Object, "Object"); Assert.AreNotEqual(o, Object, "Not Object"); } catch (Exception) { Assert.Fail("Object variable"); } try { var prototype = 11; var o = Object.GetPrototype<int>(); Assert.AreEqual(11, prototype, "prototype"); Assert.AreNotEqual(o, prototype, "Not prototype"); } catch (Exception) { Assert.Fail("prototype variable"); } try { var toString = 12; var o = new object().ToString(); Assert.AreEqual(12, toString, "toString"); Assert.AreNotEqual(o, toString, "Not toString"); } catch (Exception) { Assert.Fail("toString variable"); } try { var undefined = 13; var o = Script.Undefined; Assert.AreEqual(13, undefined, "undefined"); Assert.AreNotEqual(o, undefined, "Not undefined"); } catch (Exception) { Assert.Fail("undefined variable"); } try { var valueOf = 14; var o = new object().ValueOf(); Assert.AreEqual(14, valueOf, "valueOf"); Assert.AreNotEqual(o, valueOf, "Not valueOf"); } catch (Exception) { Assert.Fail("valueOf variable"); } } } }
/* Author: Aaron Oneal, http://aarononeal.info Copyright (c) 2012 Spicy Pixel, http://spicypixel.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.Concurrent; using System.Threading; namespace SpicyPixel.Threading { /// <summary> /// This class is the system default implementation of a <see cref="FiberScheduler"/> /// and is capable of scheduling and executing fibers on the current thread. /// </summary> /// <remarks> /// Although no fibers execute after the scheduler is shutdown, none of the /// fibers are transitioned to a <see cref="FiberStatus.RanToCompletion"/> state and therefore /// it's not safe for a fiber to wait on a fiber outside of its own scheduler. /// This is currently enforced by <see cref="FiberScheduler.ExecuteFiber"/> for now although it would be /// possible to support fiber waits across schedulers in the future. /// </remarks> public class SystemFiberScheduler : FiberScheduler { /// <summary> /// Starts a new thread, creates a scheduler, starts it running, and returns it to the calling thread. /// </summary> /// <returns> /// The scheduler from the spawned thread. /// </returns> public static SystemFiberScheduler StartNew () { return StartNew (null, CancellationToken.None, 0f); } /// <summary> /// Starts a new thread, creates a scheduler, starts it running, and returns it to the calling thread. /// </summary> /// <returns> /// The scheduler from the spawned thread. /// </returns> /// <param name='token'> /// A token to cancel the thread. /// </param> /// <param name='updatesPerSecond'> /// Updates to run per second. /// </param> public static SystemFiberScheduler StartNew (CancellationToken token, float updatesPerSecond = 0f) { return StartNew (null, token, updatesPerSecond); } /// <summary> /// Starts a new thread, creates a scheduler, starts it running, and returns it to the calling thread. /// </summary> /// <returns> /// The scheduler from the spawned thread. /// </returns> /// <param name='fiber'> /// A fiber to start execution from. /// </param> public static SystemFiberScheduler StartNew (Fiber fiber) { return StartNew (fiber, CancellationToken.None, 0f); } /// <summary> /// Starts a new thread, creates a scheduler, starts it running, and returns it to the calling thread. /// </summary> /// <returns> /// The scheduler from the spawned thread. /// </returns> /// <param name='fiber'> /// A fiber to start execution from. /// </param> /// <param name='updatesPerSecond'> /// Updates to run per second. /// </param> /// <param name='token'> /// A token to cancel the thread. /// </param> public static SystemFiberScheduler StartNew (Fiber fiber, CancellationToken token, float updatesPerSecond = 0f) { SystemFiberScheduler backgroundScheduler = null; // Setup a thread to run the scheduler var wait = new ManualResetEvent (false); var thread = new Thread (() => { backgroundScheduler = (SystemFiberScheduler)FiberScheduler.Current; wait.Set (); FiberScheduler.Current.Run (fiber, token, updatesPerSecond); }); thread.Start (); wait.WaitOne (); return backgroundScheduler; } /// <summary> /// The max stack depth before breaking out of recursion. /// </summary> private const int MaxStackDepth = 10; /// <summary> /// Tracks the number of times QueueFiber is called to avoid /// inlining too much /// </summary> [ThreadStatic] private static int stackDepthQueueFiber = 0; /// <summary> /// Currently executing fibers /// </summary> private ConcurrentQueue<Fiber> executingFibers = new ConcurrentQueue<Fiber> (); /// <summary> /// Fibers sleeping until a timeout /// </summary> private ConcurrentQueue<Tuple<Fiber, float>> sleepingFibers = new ConcurrentQueue<Tuple<Fiber, float>> (); // A future queue may include waitingFibers (e.g. waiting on a signal or timeout) /// <summary> /// The current time since the start of the run loop. /// </summary> private float currentTime; /// <summary> /// The run wait handle is set when not running and used to coordinate Dispose and Run /// </summary> private ManualResetEvent runWaitHandle = new ManualResetEvent (true); /// <summary> /// Set when disposed /// </summary> private ManualResetEvent disposeWaitHandle = new ManualResetEvent (false); /// <summary> /// Run() waits on this handle when it has nothing to do. /// Signaling wakes up the thread. /// </summary> private AutoResetEvent schedulerEventWaitHandle = new AutoResetEvent (false); /// <summary> /// Gets the run wait handle. /// </summary> /// <remarks> /// The run wait handle is set when not running and used to coordinate Dispose and Run. /// </remarks> /// <value> /// The run wait handle. /// </value> protected ManualResetEvent RunWaitHandle { get { return runWaitHandle; } } /// <summary> /// Gets the dispose wait handle. /// </summary> /// <remarks> /// Run monitors this handle for a Dispose to know when to terminate. /// </remarks> /// <value> /// The dispose wait handle. /// </value> protected WaitHandle DisposeWaitHandle { get { return disposeWaitHandle; } } /// <summary> /// Gets a wait handle which can be used to wait for a scheduler /// event to occur. /// </summary> /// <remarks> /// Scheduler events trigger this handle to be signaled. /// Events occur any time a fiber is added to an execution queue, /// whether because it is new or because it is moving from /// a wait queue to an execution queue. /// /// This handle is used to sleep in Run() when there are /// no events to process, and a scheduler with a custom /// run loop may do the same. /// </remarks> /// <value> /// The scheduler event wait handle. /// </value> protected WaitHandle SchedulerEventWaitHandle { get { return schedulerEventWaitHandle; } } /// <summary> /// Gets the executing fiber count. /// </summary> /// <remarks> /// This can be used to optimize a custom run loop. /// </remarks> /// <value> /// The executing fiber count. /// </value> protected int ExecutingFiberCount { get { return executingFibers.Count; } } /// <summary> /// Gets the sleeping fiber count. /// </summary> /// <remarks> /// This can be used to optimize a custom run loop. /// </remarks> /// <value> /// The sleeping fiber count. /// </value> protected int SleepingFiberCount { get { return sleepingFibers.Count; } } /// <summary> /// True if running /// </summary> /// <value>Is running.</value> public bool IsRunning { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="SpicyPixel.Threading.FiberScheduler"/> class. /// </summary> public SystemFiberScheduler () { IsRunning = false; } /// <summary> /// Queues the fiber for execution on the scheduler. /// </summary> /// <remarks> /// Fibers queued from the scheduler thread will generally be executed /// inline whenever possible on most schedulers. /// </remarks> /// <param name='fiber'> /// The fiber to queue. /// </param> protected sealed override void QueueFiber (Fiber fiber) { //if (!IsRunning) { // throw new InvalidOperationException ("Cannot queue a fiber on a non-running scheduler"); //} // Queueing can happen from completion callbacks // which may happen once the fiber has already // executed and changed state. It would be fine // if the queue did happen because non-running // fibers are skipped, but it's better to // shortcut here. if (fiber.Status != FiberStatus.WaitingToRun && fiber.Status != FiberStatus.Running) return; // Entering queue fiber where recursion might matter Interlocked.Increment (ref stackDepthQueueFiber); try { // Execute immediately to inline as much as possible // // Note: Some applications may want to always queue to control // performance more strictly by the run loop. if (AllowInlining && SchedulerThread == Thread.CurrentThread && stackDepthQueueFiber < MaxStackDepth) { ExecuteFiberInternal (fiber); return; } else { QueueFiberForExecution (fiber); return; } } finally { // Exiting queue fiber Interlocked.Decrement (ref stackDepthQueueFiber); } } /// <summary> /// Adds a fiber to the execution queue without inlining and sets the wait handle. /// </summary> /// <param name='fiber'> /// The fiber to queue. /// </param> private void QueueFiberForExecution (Fiber fiber) { executingFibers.Enqueue (fiber); // Queueing a new execution fiber needs to trigger re-evaluation of the // next update time schedulerEventWaitHandle.Set (); } /// <summary> /// Adds a fiber to the sleep queue and sets the wait handle. /// </summary> /// <param name='fiber'> /// The fiber to queue. /// </param> /// <param name='timeToWake'> /// The future time to wake. /// </param> private void QueueFiberForSleep (Fiber fiber, float timeToWake) { var tuple = new Tuple<Fiber, float> (fiber, timeToWake); sleepingFibers.Enqueue (tuple); // Fibers can only be queued for sleep when they return // a yield instruction. This can only happen when executing // on the main thread and therefore we will never be in // a wait loop with a need to signal the scheduler event handle. } /// <summary> /// Update the scheduler which causes all queued tasks to run /// for a cycle. /// </summary> /// <remarks> /// This method is useful when updating the scheduler manually /// with a custom run loop instead of calling <see cref="Run(Fiber, CancellationToken, float)"/>. /// </remarks> /// <param name='time'> /// Time in seconds since the scheduler or application began running. /// This value is used to determine when to wake sleeping fibers. /// Using float instead of TimeSpan spares the GC. /// </param> protected void Update (float time) { currentTime = time; UpdateExecutingFibers (); UpdateSleepingFibers (); } private void UpdateExecutingFibers () { //////////////////////////// // Run executing fibers // Add null to know when to stop executingFibers.Enqueue (null); Fiber item; while (executingFibers.TryDequeue (out item)) { // If we reached the marker for this update then stop if (item == null) break; // Skip completed items if (item.IsCompleted) continue; ExecuteFiberInternal (item); } } private void UpdateSleepingFibers () { //////////////////////////// // Wake sleeping fibers that it's time for // Add null to know when to stop sleepingFibers.Enqueue (null); Tuple<Fiber, float> item; while (sleepingFibers.TryDequeue (out item)) { // If we reached the marker for this update then stop if (item == null) break; Fiber fiber = item.Item1; // Skip completed items if (fiber.IsCompleted) continue; // Run if time or cancelled otherwise re-enqueue if (item.Item2 <= currentTime || fiber.cancelToken.IsCancellationRequested) ExecuteFiberInternal (item.Item1); else sleepingFibers.Enqueue (item); } } /// <summary> /// Gets the time of the first fiber wake up. /// </summary> /// <remarks> /// This method is primarily useful when manually calling Update() /// instead of Run() to know how long the thread can sleep for. /// </remarks> /// <returns> /// True if there was a sleeping fiber, false otherwise. /// </returns> /// <param name='fiberWakeTime'> /// The time marker in seconds the first sleeping fiber needs to wake up. /// This is based on a previously passed time value to Update(). /// This value may be 0 if a sleeping fiber was aborted and /// therefore an update should process immediately. /// </param> protected bool GetNextFiberWakeTime (out float fiberWakeTime) { fiberWakeTime = -1f; // Nothig to do if there are no sleeping fibers if (sleepingFibers.Count == 0) return false; // Find the earliest wake time foreach (var fiber in sleepingFibers) { if (fiber.Item1.cancelToken.IsCancellationRequested) { fiberWakeTime = 0f; // wake immediately break; } if (fiberWakeTime == -1f || fiber.Item2 < fiberWakeTime) fiberWakeTime = fiber.Item2; } return true; } private IEnumerator CancelWhenComplete (Fiber waitOnFiber, CancellationTokenSource cancelSource) { yield return waitOnFiber; cancelSource.Cancel (); } /// <summary> /// Run the blocking scheduler loop and perform the specified number of updates per second. /// </summary> /// <remarks> /// Not all schedulers support a blocking run loop that can be invoked by the caller. /// The system scheduler is designed so that a custom run loop could be implemented /// by a derived type. Everything used to execute Run() is available to a derived scheduler. /// </remarks> /// <param name='fiber'> /// The optional fiber to start execution from. If this is <c>null</c>, the loop /// will continue to execute until cancelled. Otherwise, the loop will terminate /// when the fiber terminates. /// </param> /// <param name='updatesPerSecond'> /// Updates to all fibers per second. A value of <c>0</c> (the default) will execute fibers /// any time they are ready to do work instead of waiting to execute on a specific frequency. /// </param> /// <param name='token'> /// A cancellation token that can be used to stop execution. /// </param> public override void Run (Fiber fiber, CancellationToken token, float updatesPerSecond) { long frequencyTicks = (long)(updatesPerSecond * (float)TimeSpan.TicksPerSecond); // min time between updates (duration) long startTicks = 0; // start of update time (marker) long endTicks = 0; // end of update time (marker) long sleepTicks; // time to sleep (duration) long wakeTicks; // ticks before wake (duration) int sleepMilliseconds; // ms to sleep (duration) int wakeMilliseconds; // ms before wake (duration) float wakeMarkerInSeconds; // time of wake in seconds (marker) var mainFiberCompleteCancelSource = new CancellationTokenSource (); if (isDisposed) throw new ObjectDisposedException (GetType ().FullName); // Run is not re-entrant, make sure we're not running if (!runWaitHandle.WaitOne (0)) throw new InvalidOperationException ("Run is already executing and is not re-entrant"); // Verify arguments if (updatesPerSecond < 0f) throw new ArgumentOutOfRangeException ("updatesPerSecond", "The updatesPerSecond must be >= 0"); // Get a base time for better precision long baseTicks = DateTime.Now.Ticks; // Build wait list to terminate execution var waitHandleList = new List<WaitHandle> (4); waitHandleList.Add (schedulerEventWaitHandle); waitHandleList.Add (disposeWaitHandle); if (token.CanBeCanceled) waitHandleList.Add (token.WaitHandle); try { IsRunning = true; if (fiber != null) { // Add the main fiber to the wait list so when it completes // the wait handle falls through. waitHandleList.Add (mainFiberCompleteCancelSource.Token.WaitHandle); // Start the main fiber if it isn't running yet if (fiber.Status == FiberStatus.Created) fiber.Start (this); // Start a fiber that waits on the main fiber to complete. // When it does, it raises a cancellation. Fiber.Factory.StartNew (CancelWhenComplete (fiber, mainFiberCompleteCancelSource), this); } WaitHandle [] waitHandles = waitHandleList.ToArray (); // FIXME: Unclear why below was included as the handle // seems to be needed to wake sleeping fibers when abort is called. //waitHandleList.Remove(schedulerEventWaitHandle); WaitHandle [] sleepWaitHandles = waitHandleList.ToArray (); runWaitHandle.Reset (); while (true) { // Throw if faulted if (fiber != null && fiber.IsFaulted) { throw fiber.Exception; } // Stop executing if cancelled if ((token.CanBeCanceled && token.IsCancellationRequested) || mainFiberCompleteCancelSource.IsCancellationRequested || disposeWaitHandle.WaitOne (0)) return; // Snap current time startTicks = DateTime.Now.Ticks; // Update using this time marker (and convert ticks to s) Update ((float)((double)(startTicks - baseTicks) / (double)TimeSpan.TicksPerSecond)); // Only sleep to next frequency cycle if one was specified if (updatesPerSecond > 0f) { // Snap end time endTicks = DateTime.Now.Ticks; // Sleep at least until next update sleepTicks = frequencyTicks - (endTicks - startTicks); if (sleepTicks > 0) { sleepMilliseconds = (int)(sleepTicks / TimeSpan.TicksPerMillisecond); WaitHandle.WaitAny (sleepWaitHandles, sleepMilliseconds); // Stop executing if cancelled if ((token.CanBeCanceled && token.IsCancellationRequested) || mainFiberCompleteCancelSource.IsCancellationRequested || disposeWaitHandle.WaitOne (0)) return; } } // Now keep sleeping until it's time to update while (ExecutingFiberCount == 0 && (fiber == null || (fiber != null && !fiber.IsFaulted))) { // Assume we wait forever (e.g. until a signal) wakeMilliseconds = -1; // If there are sleeping fibers, then set a wake time if (GetNextFiberWakeTime (out wakeMarkerInSeconds)) { wakeTicks = baseTicks; wakeTicks += (long)((double)wakeMarkerInSeconds * (double)TimeSpan.TicksPerSecond); wakeTicks -= DateTime.Now.Ticks; // If there was a waiting fiber and it's already past time to awake then stop waiting if (wakeTicks <= 0) break; wakeMilliseconds = (int)(wakeTicks / TimeSpan.TicksPerMillisecond); } // FIXME: Sleeping tasks can be aborted and this should wake the scheduler. // For some reason the schedulerEventWaitHandle which would do this was not // in the wait list and removed above. Trying with it in the list again. // There was no waiting fiber and we will wait for another signal, // or there was a waiting fiber and we wait until that time. WaitHandle.WaitAny (waitHandles, wakeMilliseconds); // Stop executing if cancelled if ((token.CanBeCanceled && token.IsCancellationRequested) || mainFiberCompleteCancelSource.IsCancellationRequested || disposeWaitHandle.WaitOne (0)) return; } } } finally { // Clear queues Fiber deqeueFiber; while (executingFibers.TryDequeue (out deqeueFiber)) { } Tuple<Fiber, float> dequeueSleepingFiber; while (sleepingFibers.TryDequeue (out dequeueSleepingFiber)) { } // Reset time currentTime = 0f; // Not running IsRunning = false; // Set for dispose runWaitHandle.Set (); } } /// <summary> /// Executes the fiber. /// </summary> /// <remarks> /// Fibers executed by this method do not belong to a queue /// and must be added to one by method end if the fiber /// execution did not complete this invocation. Otherwise, /// the fiber would fall off the scheduler. /// </remarks> /// <param name='fiber'> /// The unqueued fiber to execute. /// </param> private void ExecuteFiberInternal (Fiber fiber) { Fiber currentFiber = fiber; Fiber nextFiber; while (currentFiber != null) { // Execute the fiber var fiberInstruction = ExecuteFiber (currentFiber); // Nothing more to do if stopped if (currentFiber.IsCompleted) return; // Handle special fiber instructions or queue for another update bool fiberQueued = false; OnFiberInstruction (currentFiber, fiberInstruction, out fiberQueued, out nextFiber); // If the fiber is still running but wasn't added to a special queue by // an instruction then it needs to be added to the execution queue // to run in the next Update(). // // Check alive state again in case an instruction resulted // in an inline execution and altered state. if (!fiberQueued && !currentFiber.IsCompleted) { // Send the fiber to the queue and don't execute inline // since we're done this update QueueFiberForExecution (currentFiber); } // Switch to the next fiber if an instruction says to do so currentFiber = nextFiber; } } private void OnFiberInstruction (Fiber fiber, FiberInstruction instruction, out bool fiberQueued, out Fiber nextFiber) { fiberQueued = false; nextFiber = null; YieldUntilComplete yieldUntilComplete = instruction as YieldUntilComplete; if (yieldUntilComplete != null) { // The additional complexity below is because this was going // to handle waiting for completions for fibers from other threads. // Currently fibers must belong to the same thread and this is enforced // by the instructions themselves for now. int completeOnce = 0; // FIXME: If we support multiple schedulers in the future // this callback could occur from another thread and // therefore after Dispose(). Would probably need a lock. yieldUntilComplete.Fiber.ContinueWith ((f) => { var originalCompleteOnce = Interlocked.CompareExchange (ref completeOnce, 1, 0); if (originalCompleteOnce != 0) return; QueueFiber (fiber); // optionally execute inline when the completion occurs // If f.Status != RanToCompletion then this fiber needs to transition to the same state // or faults won't propegate //if (f.Status != FiberStatus.RanToCompletion) { // if (f.IsCanceled) { // if (f.CancellationToken == fiber.CancellationToken) { // fiber.CancelContinuation (); // } else { // fiber.FaultContinuation (new System.Threading.OperationCanceledException ()); // } // } else if (f.IsFaulted) { // fiber.FaultContinuation (f.Exception); // } // RemoveFiberFromQueues (fiber); //} else { // QueueFiber (fiber); // optionally execute inline when the completion occurs //} }); fiberQueued = true; return; } YieldForSeconds yieldForSeconds = instruction as YieldForSeconds; if (yieldForSeconds != null) { QueueFiberForSleep (fiber, currentTime + yieldForSeconds.Seconds); fiberQueued = true; return; } YieldToFiber yieldToFiber = instruction as YieldToFiber; if (yieldToFiber != null) { RemoveFiberFromQueues (yieldToFiber.Fiber); nextFiber = yieldToFiber.Fiber; fiberQueued = false; return; } } /// <summary> /// Removes a fiber from the current queues. /// </summary> /// <remarks> /// The fiber being yielded to needs to be removed from the queues /// because it's about to be processed directly. /// </remarks> /// <param name='fiber'> /// Fiber. /// </param> private void RemoveFiberFromQueues (Fiber fiber) { bool found = false; if (executingFibers.Count > 0) { Fiber markerItem = new Fiber (() => { }); executingFibers.Enqueue (markerItem); Fiber item; while (executingFibers.TryDequeue (out item)) { if (item == markerItem) break; if (item == fiber) found = true; else executingFibers.Enqueue (item); } if (found) return; } if (sleepingFibers.Count > 0) { Tuple<Fiber, float> markerTuple = new Tuple<Fiber, float> (null, 0f); sleepingFibers.Enqueue (markerTuple); Tuple<Fiber, float> itemTuple; while (sleepingFibers.TryDequeue (out itemTuple)) { if (itemTuple == markerTuple) break; if (itemTuple != null && itemTuple.Item1 == fiber) found = true; else sleepingFibers.Enqueue (itemTuple); } } } #region IDisposable implementation /// <summary> /// Tracks whether the object has been disposed already /// </summary> private bool isDisposed = false; /// <summary> /// Dispose the scheduler. /// </summary> /// <remarks> /// When the scheduler is disposed, the <see cref="CancellationToken"/> is set. /// </remarks> /// <param name="disposing"> /// Disposing is true when called manually, /// false when called by the finalizer. /// </param> protected override void Dispose (bool disposing) { // Do nothing if already called if (isDisposed) return; if (disposing) { // Free other state (managed objects). disposeWaitHandle.Set (); runWaitHandle.WaitOne (); } // Free your own state (unmanaged objects). // Set large fields to null. // Mark disposed isDisposed = true; base.Dispose (disposing); } #endregion } }
using System; using System.Collections.Generic; using System.Text; namespace dotLua { /// <summary> /// Allows the manipulation of a given stack frame. /// </summary> public sealed class LuaStack { private IntPtr lua = IntPtr.Zero; /// <summary> /// Constructs a new LUA stack object from the given state. /// </summary> /// <param name="state">A valid LUA state</param> public LuaStack(LuaState state) { if (state.Handle == IntPtr.Zero) { // Invalid state passed throw new ArgumentException("state must not be Zero", "state"); } lua = state.Handle; } /// <summary> /// Creates a new LUA stack from the given state and automatically /// reserves space for a specified amount of items. /// </summary> /// <param name="state">A valid LUA state.</param> /// <param name="grow">Grows the stack.</param> public LuaStack(LuaState state, int grow) : this(state) { Grow(grow); } /// <summary> /// Sets or retrieves the index of the top level item. If set to 0 /// the entire stack is being deleted. /// </summary> public int TopIndex { get { return NativeLua.lua_gettop(lua); } set { NativeLua.lua_settop(lua, value); } } /// <summary> /// Retrieves the value of the top level item without removing /// it from the stack. /// </summary> public object TopValue { get { return this[TopIndex]; } } /// <summary> /// Retrieves the amount of items on the stack. /// <remarks>Since LUA starts counting at 1, the index of the top item and the amount of /// items on the stack is equal. Thus Count only returns the value of TopIndex.</remarks> /// </summary> public int Count { get { // Return this value return TopIndex; } } /// <summary> /// Grows the stack for the specified amount of items. The new blanks are filled /// with nils. /// </summary> /// <param name="size">Number of elements to grow the stack.</param> public void Grow(int size) { if (NativeLua.lua_checkstack(lua, size) == 0) { // Throw on allocation failure throw new LuaException("Not enough memory to grow stack"); } } /// <summary> /// Removes a specified amount of elements from the top of the stack. /// </summary> public void Pop(int items) { if (TopIndex > 0) { TopIndex = -(items) - 1; } } /// <summary> /// Removes one element from the stack. /// </summary> public void Pop() { Pop(1); } /// <summary> /// Clears the entire stack by setting TopIndex to 0. /// </summary> public void Clear() { TopIndex = 0; } /// <summary> /// Moves the top item into the given position. /// </summary> /// <param name="index">Position</param> public void Insert(int index) { NativeLua.lua_insert(lua, index); } /// <summary> /// Pushes onto the stack a copy of the element at the given index. /// </summary> /// <param name="index">The items index which should be copied.</param> public void PushValue(int index) { NativeLua.lua_pushvalue(lua, index); } /// <summary> /// Replaces the given item with the top element. /// </summary> /// <param name="index">Index to replace</param> public void Replace(int index) { NativeLua.lua_replace(lua, index); } /// <summary> /// Removes the given object and shifts the items on top down to fill the gap. /// </summary> /// <param name="index">Item to be removed</param> public void Remove(int index) { NativeLua.lua_remove(lua, index); } /// <summary> /// Retrieves the type of the given stack item. /// </summary> /// <param name="index">Index of the item</param> /// <returns>The type of the item</returns> public LuaType TypeOf(int index) { LuaType res = 0; res = (LuaType)NativeLua.lua_type(lua, index); if (res == LuaType.None) { // Nothing, invalid index throw new IndexOutOfRangeException("Invalid index for TypeOf query."); } // Return our result return res; } /// <summary> /// Compares two stack items if they are equal. /// </summary> /// <param name="index1">First index to compare.</param> /// <param name="index2">Second index to compare.</param> /// <param name="raw">If true only primitive comparision is being done without using metainformation.</param> /// <returns>True if both are equal</returns> public bool Equal(int index1, int index2, bool raw) { int res = 0; if (!raw) { // normal compare res = NativeLua.lua_equal(lua, index1, index2); } else { // raw compare res = NativeLua.lua_rawequal(lua, index1, index2); } return (res != 0); } /// <summary> /// Compares two stack items if they are equal without raw /// comparision methods. /// </summary> /// <param name="index1">First index to compare</param> /// <param name="index2">Second index to compare</param> /// <returns>True if both are equal</returns> public bool Equal(int index1, int index2) { return Equal(index1, index2, false); } /// <summary> /// Retrieves a given item from the stack. /// </summary> /// <param name="index">Index of the item to be retrieved</param> /// <returns>Value of the item</returns> public object this[int index] { get { LuaType type = TypeOf(index); object value = null; if (type == LuaType.None) { // Invalid type throw new IndexOutOfRangeException("Index does not exist or has type LUA_NONE"); } switch (type) { case LuaType.Boolean: { // A boolean value = (bool)(NativeLua.lua_toboolean(lua, index) != 0); } break; case LuaType.Nil: { // Nil this means, null value = null; } break; case LuaType.Number: { // A ordinary number :) value = (NativeLua.lua_tonumber(lua, index)); } break; case LuaType.String: { // A string value = (NativeLua.lua_tostring(lua, index)); } break; case LuaType.Function: { // A function value = (NativeLua.lua_tocfunction(lua, index)); } break; case LuaType.UserData: { // User data value = (NativeLua.lua_touserdata(lua, index)); } break; case LuaType.Thread: { value = new LuaThread(NativeLua.lua_tothread(lua, index)); } break; case LuaType.Table: { value = (object)new LuaTable(new Lua(lua), index); } break; case LuaType.LightUserData: { // But for now we even take the table into the pointers value = (NativeLua.lua_topointer(lua, index)); } break; default: { // Error... Unknown object throw new LuaException("Unknown object"); } } return value; } } /// <summary> /// Pushes a nil value on top of the stack. /// </summary> /// <returns>Returns the index of the newly pushed item.</returns> public int Push() { NativeLua.lua_pushnil(lua); return TopIndex; } /// <summary> /// Pushes the given string on top of the stack. /// </summary> /// <param name="value">Value to push, if null nil is being pushed.</param> /// <returns>Returns the index of the newly pushed item.</returns> public int Push(object value) { if (value == null) { // push nil return Push(); } if (value.GetType() == typeof(string)) { NativeLua.lua_pushstring(lua, (string)value); } else if (value.GetType() == typeof(double) || // Normal doubles value.GetType() == typeof(float) || // single precision value.GetType() == typeof(int) || // Int32 value.GetType() == typeof(long) || // Int64 value.GetType() == typeof(short) || // Int16 value.GetType() == typeof(uint) || // UInt23 ;D... just kidding value.GetType() == typeof(ushort) || // UInt16 value.GetType() == typeof(ulong) || // UInt64 value.GetType() == typeof(byte)) // __int8 :-) { NativeLua.lua_pushnumber(lua, Convert.ToDouble(value)); } else if (value.GetType() == typeof(bool)) { NativeLua.lua_pushboolean(lua, (int)value); } else if (value.GetType() == typeof(LuaCallbackFunction)) { NativeLua.lua_pushcfunction(lua, (LuaCallbackFunction)value); } else if (value.GetType() == typeof(IntPtr)) { NativeLua.lua_pushlightuserdata(lua, (IntPtr)value); } else { // Error throw new ArgumentException("value's type is not supported by the LUA subsystem", "value"); } return TopIndex; } /// <summary> /// Concenates the count values at the top of the stack, pops them, and leaves the result at the top. /// </summary> /// <param name="count">Number of items to concat</param> public void Concat(int count) { NativeLua.lua_concat(lua, count); } #if DEBUG /// <summary> /// Converts the entire stack to a human read able form. This is used to debug /// the stack. /// </summary> /// <returns>Returns the stack as string</returns> public override string ToString() { StringBuilder builder = new StringBuilder(); builder.Append("["); for (int i = 1; i <= TopIndex; ++i) { if (TypeOf(i) == LuaType.String || TypeOf(i) == LuaType.Boolean || TypeOf(i) == LuaType.Number || TypeOf(i) == LuaType.Nil) { builder.Append(String.Format(" {0}", (this[i] != null ? this[i] : "(nil)"))); } else if (TypeOf(i) == LuaType.Table) { builder.Append(" (Table)"); } else if (TypeOf(i) == LuaType.Function) { builder.Append(" (Function)"); } else { builder.Append(" (Unknown)"); } if (i != TopIndex) { // Append a comma builder.Append(","); } } builder.Append("]"); return builder.ToString(); } #endif } }
// // Migrator.cs // // Author: // Gabriel Burt <[email protected]> // // Copyright (C) 2006-2007 Gabriel Burt // Copyright (C) 2007-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Data; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using Mono.Unix; using Hyena; using Hyena.Data; using Hyena.Query; using Hyena.Data.Sqlite; using Banshee.Collection.Database; using Banshee.ServiceStack; using Banshee.Query; namespace Banshee.SmartPlaylist { internal class Migrator { private string [] criteria = new string [] { "songs", "minutes", "hours", "MB" }; private Dictionary<string, QueryOrder> order_hash = new Dictionary<string, QueryOrder> (); public static bool MigrateAll () { int version = ServiceManager.DbConnection.Query<int> ("SELECT Value FROM CoreConfiguration WHERE Key = 'SmartPlaylistVersion'"); if (version == 1) return true; try { ServiceManager.DbConnection.Execute ("BEGIN"); Migrator m = new Migrator (); using (IDataReader reader = ServiceManager.DbConnection.Query ( "SELECT SmartPlaylistID, Name, Condition, OrderBy, LimitNumber, LimitCriterion FROM CoreSmartPlaylists")) { while (reader.Read ()) { m.Migrate ( Convert.ToInt32 (reader[0]), reader[1] as string, reader[2] as string, reader[3] as string, reader[4] as string, reader[5] as string ); } } ServiceManager.DbConnection.Execute ("INSERT INTO CoreConfiguration (Key, Value) Values ('SmartPlaylistVersion', 1)"); ServiceManager.DbConnection.Execute ("COMMIT"); return true; } catch (Exception e) { ServiceManager.DbConnection.Execute ("ROLLBACK"); Log.Error ( Catalog.GetString ("Unable to Migrate Smart Playlists"), String.Format (Catalog.GetString ("Please file a bug with this error: {0}"), e.ToString ()), true ); return false; } } public Migrator () { order_hash.Add ("RANDOM()", BansheeQuery.FindOrder ("Random", true)); order_hash.Add ("AlbumTitle", BansheeQuery.FindOrder ("Album", true)); order_hash.Add ("Artist", BansheeQuery.FindOrder ("Artist", true)); order_hash.Add ("Genre", BansheeQuery.FindOrder ("Genre", true)); order_hash.Add ("Title", BansheeQuery.FindOrder ("Title", true)); order_hash.Add ("Rating DESC", BansheeQuery.FindOrder ("Rating", false)); order_hash.Add ("Rating ASC", BansheeQuery.FindOrder ("Rating", true)); order_hash.Add ("Score DESC", BansheeQuery.FindOrder ("Score", false)); order_hash.Add ("Score ASC", BansheeQuery.FindOrder ("Score", true)); order_hash.Add ("NumberOfPlays DESC", BansheeQuery.FindOrder ("PlayCount", false)); order_hash.Add ("NumberOfPlays ASC", BansheeQuery.FindOrder ("PlayCount", true)); order_hash.Add ("DateAddedStamp DESC", BansheeQuery.FindOrder ("DateAddedStamp", false)); order_hash.Add ("DateAddedStamp ASC", BansheeQuery.FindOrder ("DateAddedStamp", true)); order_hash.Add ("LastPlayedStamp DESC", BansheeQuery.FindOrder ("LastPlayedStamp", false)); order_hash.Add ("LastPlayedStamp ASC", BansheeQuery.FindOrder ("LastPlayedStamp", true)); } private void Migrate (int dbid, string Name, string Condition, string OrderBy, string LimitNumber, string LimitCriterion) { if (OrderBy != null && OrderBy != String.Empty) { QueryOrder order = order_hash [OrderBy]; OrderBy = order.Name; } LimitCriterion = criteria [Convert.ToInt32 (LimitCriterion)]; string ConditionXml = ParseCondition (Condition); ServiceManager.DbConnection.Execute (new HyenaSqliteCommand (@" UPDATE CoreSmartPlaylists SET Name = ?, Condition = ?, OrderBy = ?, LimitNumber = ?, LimitCriterion = ? WHERE SmartPlaylistID = ?", Name, ConditionXml, OrderBy, LimitNumber, LimitCriterion, dbid )); Log.Debug (String.Format ("Migrated Smart Playlist {0}", Name)); } private string ParseCondition (string value) { if (String.IsNullOrEmpty (value)) return null; // Check for ANDs or ORs and split into conditions as needed string [] conditions; bool ands = true; if (value.IndexOf(") AND (") != -1) { ands = true; conditions = System.Text.RegularExpressions.Regex.Split (value, "\\) AND \\("); } else if (value.IndexOf(") OR (") != -1) { ands = false; conditions = System.Text.RegularExpressions.Regex.Split (value, "\\) OR \\("); } else { conditions = new string [] {value}; } QueryListNode root = new QueryListNode (ands ? Keyword.And : Keyword.Or); // Remove leading spaces and parens from the first condition conditions[0] = conditions[0].Remove(0, 2); // Remove trailing spaces and last paren from the last condition string tmp = conditions[conditions.Length-1]; tmp = tmp.TrimEnd(new char[] {' '}); tmp = tmp.Substring(0, tmp.Length - 1); conditions[conditions.Length-1] = tmp; int count = 0; foreach (string condition in conditions) { // Add a new row for this condition string col, v1, v2; foreach (QueryOperator op in QueryOperator.Operators) { if (op.MatchesCondition (condition, out col, out v1, out v2)) { QueryTermNode term = new QueryTermNode (); QueryField field = BansheeQuery.FieldSet [col]; bool is_relative_date = false; if (field == null) { if (col.IndexOf ("DateAddedStamp") != -1) { field = BansheeQuery.FieldSet ["added"]; } else if (col.IndexOf ("LastPlayedStamp") != -1) { field = BansheeQuery.FieldSet ["lastplayed"]; } // Fix ugly implementation of playlist/smart playlist conditions if (op == QueryOperator.InPlaylist || op == QueryOperator.NotInPlaylist) { field = BansheeQuery.FieldSet ["playlist"]; } else if (op == QueryOperator.InSmartPlaylist || op == QueryOperator.NotInSmartPlaylist) { field = BansheeQuery.FieldSet ["smartplaylist"]; } if (field == null) { continue; } is_relative_date = true; } term.Field = field; if (op == QueryOperator.Between) { QueryListNode and = new QueryListNode (Keyword.And); QueryTermNode t2 = new QueryTermNode (); t2.Field = term.Field; if (is_relative_date) { ParseRelativeDateCondition (term, v1, field, ">="); ParseRelativeDateCondition (t2, v2, field, "<="); } else { term.Value = QueryValue.CreateFromUserQuery (v1, field); term.Operator = term.Value.OperatorSet ["<="]; t2.Value = QueryValue.CreateFromUserQuery (v2, field); t2.Operator = t2.Value.OperatorSet [">="]; } and.AddChild (term); and.AddChild (t2); root.AddChild (and); } else if (is_relative_date) { ParseRelativeDateCondition (term, v1, field, op.NewOp); root.AddChild (term); } else { term.Value = QueryValue.CreateFromUserQuery (v1, field); term.Operator = term.Value.OperatorSet [op.NewOp]; root.AddChild (term); } break; } } count++; } QueryNode node = root.Trim (); if (node != null) { //Console.WriteLine ("After XML: {0}", node.ToXml (BansheeQuery.FieldSet, true)); //Console.WriteLine ("After SQL: {0}", node.ToSql (BansheeQuery.FieldSet)); } return node == null ? String.Empty : node.ToXml (BansheeQuery.FieldSet); } private void ParseRelativeDateCondition (QueryTermNode term, string val, QueryField field, string op) { string new_op = op.Replace ('>', '^'); new_op = new_op.Replace ('<', '>'); new_op = new_op.Replace ('^', '<'); RelativeTimeSpanQueryValue date_value = new RelativeTimeSpanQueryValue (); // Have to flip the operator b/c of how we used to construct the SQL query term.Operator = date_value.OperatorSet [new_op]; // Have to negate the value b/c of how we used to constuct the SQL query date_value.SetRelativeValue (Convert.ToInt64 (val), TimeFactor.Second); term.Value = date_value; } public sealed class QueryOperator { public string NewOp; private string format; public string Format { get { return format; } } private QueryOperator (string new_op, string format) { NewOp = new_op; this.format = format; } public string FormatValues (bool text, string column, string value1, string value2) { if (text) return String.Format (format, "'", column, value1, value2); else return String.Format (format, "", column, value1, value2); } public bool MatchesCondition (string condition, out string column, out string value1, out string value2) { // Remove trailing parens from the end of the format b/c trailing parens are trimmed from the condition string regex = String.Format(format.Replace("(", "\\(").Replace(")", "\\)"), "'?", // ignore the single quotes if they exist "(.*)", // match the column "(.*)", // match the first value "(.*)" // match the second value ); //Console.WriteLine ("regex = {0}", regex); MatchCollection mc = System.Text.RegularExpressions.Regex.Matches (condition, regex); if (mc != null && mc.Count > 0 && mc[0].Groups.Count > 0) { column = mc[0].Groups[1].Captures[0].Value; value1 = mc[0].Groups[2].Captures[0].Value.Trim(new char[] {'\''}); if (mc[0].Groups.Count == 4) value2 = mc[0].Groups[3].Captures[0].Value.Trim(new char[] {'\''}); else value2 = null; return true; } else { column = value1 = value2 = null; return false; } } // calling lower() to have case insensitive comparisons with strings public static QueryOperator EQText = new QueryOperator("==", "lower({1}) = {0}{2}{0}"); public static QueryOperator NotEQText = new QueryOperator("!=", "lower({1}) != {0}{2}{0}"); public static QueryOperator EQ = new QueryOperator("==", "{1} = {0}{2}{0}"); public static QueryOperator NotEQ = new QueryOperator("!=", "{1} != {0}{2}{0}"); // TODO how to deal w/ between? public static QueryOperator Between = new QueryOperator("", "{1} BETWEEN {0}{2}{0} AND {0}{3}{0}"); public static QueryOperator LT = new QueryOperator("<", "{1} < {0}{2}{0}"); public static QueryOperator GT = new QueryOperator(">", "{1} > {0}{2}{0}"); public static QueryOperator GTE = new QueryOperator(">=", "{1} >= {0}{2}{0}"); // Note, the following lower() calls are necessary b/c of a sqlite bug which makes the LIKE // command case sensitive with certain characters. public static QueryOperator Like = new QueryOperator(":", "lower({1}) LIKE '%{2}%'"); public static QueryOperator NotLike = new QueryOperator("!:", "lower({1}) NOT LIKE '%{2}%'"); public static QueryOperator StartsWith = new QueryOperator("=", "lower({1}) LIKE '{2}%'"); public static QueryOperator EndsWith = new QueryOperator(":=", "lower({1}) LIKE '%{2}'"); // TODO these should either be made generic or moved somewhere else since they are Banshee/Track/Playlist specific. public static QueryOperator InPlaylist = new QueryOperator("==", "TrackID IN (SELECT TrackID FROM PlaylistEntries WHERE {1} = {0}{2}{0})"); public static QueryOperator NotInPlaylist = new QueryOperator("!=", "TrackID NOT IN (SELECT TrackID FROM PlaylistEntries WHERE {1} = {0}{2}{0})"); public static QueryOperator InSmartPlaylist = new QueryOperator("==", "TrackID IN (SELECT TrackID FROM SmartPlaylistEntries WHERE {1} = {0}{2}{0})"); public static QueryOperator NotInSmartPlaylist = new QueryOperator("!=", "TrackID NOT IN (SELECT TrackID FROM SmartPlaylistEntries WHERE {1} = {0}{2}{0})"); public static QueryOperator [] Operators = new QueryOperator [] { EQText, NotEQText, EQ, NotEQ, Between, LT, GT, GTE, Like, NotLike, StartsWith, InPlaylist, NotInPlaylist, InSmartPlaylist, NotInSmartPlaylist }; } /*public sealed class QueryFilter { private string name; private QueryOperator op; public string Name { get { return name; } } public QueryOperator Operator { get { return op; } } private static Hashtable filters = new Hashtable(); private static ArrayList filters_array = new ArrayList(); public static QueryFilter GetByName (string name) { return filters[name] as QueryFilter; } public static ArrayList Filters { get { return filters_array; } } private static QueryFilter NewOperation (string name, QueryOperator op) { QueryFilter filter = new QueryFilter(name, op); filters[name] = filter; filters_array.Add (filter); return filter; } private QueryFilter (string name, QueryOperator op) { this.name = name; this.op = op; } public static QueryFilter InPlaylist = NewOperation ( Catalog.GetString ("is"), QueryOperator.InPlaylist ); public static QueryFilter NotInPlaylist = NewOperation ( Catalog.GetString ("is not"), QueryOperator.NotInPlaylist ); public static QueryFilter InSmartPlaylist = NewOperation ( Catalog.GetString ("is"), QueryOperator.InSmartPlaylist ); public static QueryFilter NotInSmartPlaylist = NewOperation ( Catalog.GetString ("is not"), QueryOperator.NotInSmartPlaylist ); // caution: the equal/not-equal operators for text fields (TextIs and TextNotIs) have to be defined // before the ones for non-text fields. Otherwise MatchesCondition will not return the right column names. // (because the regular expression for non-string fields machtes also for string fields) public static QueryFilter TextIs = NewOperation ( Catalog.GetString ("is"), QueryOperator.EQText ); public static QueryFilter TextIsNot = NewOperation ( Catalog.GetString ("is not"), QueryOperator.NotEQText ); public static QueryFilter Is = NewOperation ( Catalog.GetString ("is"), QueryOperator.EQ ); public static QueryFilter IsNot = NewOperation ( Catalog.GetString ("is not"), QueryOperator.NotEQ ); public static QueryFilter IsLessThan = NewOperation ( Catalog.GetString ("is less than"), QueryOperator.LT ); public static QueryFilter IsGreaterThan = NewOperation ( Catalog.GetString ("is greater than"), QueryOperator.GT ); public static QueryFilter MoreThan = NewOperation ( Catalog.GetString ("more than"), QueryOperator.GT ); public static QueryFilter LessThan = NewOperation ( Catalog.GetString ("less than"), QueryOperator.LT ); public static QueryFilter IsAtLeast = NewOperation ( Catalog.GetString ("is at least"), QueryOperator.GTE ); public static QueryFilter Contains = NewOperation ( Catalog.GetString ("contains"), QueryOperator.Like ); public static QueryFilter DoesNotContain = NewOperation ( Catalog.GetString ("does not contain"), QueryOperator.NotLike ); public static QueryFilter StartsWith = NewOperation ( Catalog.GetString ("starts with"), QueryOperator.StartsWith ); public static QueryFilter EndsWith = NewOperation ( Catalog.GetString ("ends with"), QueryOperator.EndsWith ); public static QueryFilter IsBefore = NewOperation ( Catalog.GetString ("is before"), QueryOperator.LT ); public static QueryFilter IsAfter = NewOperation ( Catalog.GetString ("is after"), QueryOperator.GT ); public static QueryFilter IsInTheRange = NewOperation ( Catalog.GetString ("is between"), QueryOperator.Between ); public static QueryFilter Between = NewOperation ( Catalog.GetString ("between"), QueryOperator.Between ); }*/ } }
using System; using System.Collections.Generic; using System.Text; namespace Lucene.Net.Search.Spans { /* * 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 AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using IBits = Lucene.Net.Util.IBits; using IndexReader = Lucene.Net.Index.IndexReader; using Term = Lucene.Net.Index.Term; using TermContext = Lucene.Net.Index.TermContext; /// <summary> /// Wraps any <see cref="MultiTermQuery"/> as a <see cref="SpanQuery"/>, /// so it can be nested within other <see cref="SpanQuery"/> classes. /// <para/> /// The query is rewritten by default to a <see cref="SpanOrQuery"/> containing /// the expanded terms, but this can be customized. /// <para/> /// Example: /// <code> /// WildcardQuery wildcard = new WildcardQuery(new Term("field", "bro?n")); /// SpanQuery spanWildcard = new SpanMultiTermQueryWrapper&lt;WildcardQuery&gt;(wildcard); /// // do something with spanWildcard, such as use it in a SpanFirstQuery /// </code> /// </summary> public class SpanMultiTermQueryWrapper<Q> : SpanQuery, ISpanMultiTermQueryWrapper where Q : MultiTermQuery { protected readonly Q m_query; /// <summary> /// Create a new <see cref="SpanMultiTermQueryWrapper{Q}"/>. /// </summary> /// <param name="query"> Query to wrap. /// <para/> /// NOTE: This will set <see cref="MultiTermQuery.MultiTermRewriteMethod"/> /// on the wrapped <paramref name="query"/>, changing its rewrite method to a suitable one for spans. /// Be sure to not change the rewrite method on the wrapped query afterwards! Doing so will /// throw <see cref="NotSupportedException"/> on rewriting this query! </param> public SpanMultiTermQueryWrapper(Q query) { this.m_query = query; MultiTermQuery.RewriteMethod method = this.m_query.MultiTermRewriteMethod; if (method is ITopTermsRewrite topTermsRewrite) { MultiTermRewriteMethod = new TopTermsSpanBooleanQueryRewrite(topTermsRewrite.Count); } else { MultiTermRewriteMethod = SCORING_SPAN_QUERY_REWRITE; } } /// <summary> /// Expert: Gets or Sets the rewrite method. This only makes sense /// to be a span rewrite method. /// </summary> public SpanRewriteMethod MultiTermRewriteMethod { get { MultiTermQuery.RewriteMethod m = m_query.MultiTermRewriteMethod; if (!(m is SpanRewriteMethod spanRewriteMethod)) { throw UnsupportedOperationException.Create("You can only use SpanMultiTermQueryWrapper with a suitable SpanRewriteMethod."); } return spanRewriteMethod; } set => m_query.MultiTermRewriteMethod = value; } public override Spans GetSpans(AtomicReaderContext context, IBits acceptDocs, IDictionary<Term, TermContext> termContexts) { throw UnsupportedOperationException.Create("Query should have been rewritten"); } public override string Field => m_query.Field; /// <summary> /// Returns the wrapped query </summary> public virtual Query WrappedQuery => m_query; public override string ToString(string field) { StringBuilder builder = new StringBuilder(); builder.Append("SpanMultiTermQueryWrapper("); builder.Append(m_query.ToString(field)); builder.Append(")"); if (Boost != 1F) { builder.Append('^'); builder.Append(Boost); } return builder.ToString(); } public override Query Rewrite(IndexReader reader) { Query q = m_query.Rewrite(reader); if (!(q is SpanQuery)) { throw UnsupportedOperationException.Create("You can only use SpanMultiTermQueryWrapper with a suitable SpanRewriteMethod."); } q.Boost = q.Boost * Boost; // multiply boost return q; } public override int GetHashCode() { const int prime = 31; int result = base.GetHashCode(); result = prime * result + m_query.GetHashCode(); return result; } public override bool Equals(object obj) { if (this == obj) { return true; } if (!base.Equals(obj)) { return false; } if (this.GetType() != obj.GetType()) { return false; } var other = (SpanMultiTermQueryWrapper<Q>)obj; if (!m_query.Equals(other.m_query)) { return false; } return true; } // LUCENENET NOTE: Moved SpanRewriteMethod outside of this class /// <summary> /// A rewrite method that first translates each term into a <see cref="SpanTermQuery"/> in a /// <see cref="Occur.SHOULD"/> clause in a <see cref="BooleanQuery"/>, and keeps the /// scores as computed by the query. /// </summary> /// <seealso cref="MultiTermRewriteMethod"/> public static readonly SpanRewriteMethod SCORING_SPAN_QUERY_REWRITE = new SpanRewriteMethodAnonymousClass(); private class SpanRewriteMethodAnonymousClass : SpanRewriteMethod { public SpanRewriteMethodAnonymousClass() { } private readonly ScoringRewrite<SpanOrQuery> @delegate = new ScoringRewriteAnonymousClass(); private class ScoringRewriteAnonymousClass : ScoringRewrite<SpanOrQuery> { public ScoringRewriteAnonymousClass() { } protected override SpanOrQuery GetTopLevelQuery() { return new SpanOrQuery(); } protected override void CheckMaxClauseCount(int count) { // we accept all terms as SpanOrQuery has no limits } protected override void AddClause(SpanOrQuery topLevel, Term term, int docCount, float boost, TermContext states) { // TODO: would be nice to not lose term-state here. // we could add a hack option to SpanOrQuery, but the hack would only work if this is the top-level Span // (if you put this thing in another span query, it would extractTerms/double-seek anyway) SpanTermQuery q = new SpanTermQuery(term); q.Boost = boost; topLevel.AddClause(q); } } public override Query Rewrite(IndexReader reader, MultiTermQuery query) { return @delegate.Rewrite(reader, query); } } /// <summary> /// A rewrite method that first translates each term into a <see cref="SpanTermQuery"/> in a /// <see cref="Occur.SHOULD"/> clause in a <see cref="BooleanQuery"/>, and keeps the /// scores as computed by the query. /// /// <para/> /// This rewrite method only uses the top scoring terms so it will not overflow /// the boolean max clause count. /// </summary> /// <seealso cref="MultiTermRewriteMethod"/> public sealed class TopTermsSpanBooleanQueryRewrite : SpanRewriteMethod { private readonly TopTermsRewrite<SpanOrQuery> @delegate; /// <summary> /// Create a <see cref="TopTermsSpanBooleanQueryRewrite"/> for /// at most <paramref name="size"/> terms. /// </summary> public TopTermsSpanBooleanQueryRewrite(int size) { @delegate = new TopTermsRewriteAnonymousClass(size); } private class TopTermsRewriteAnonymousClass : TopTermsRewrite<SpanOrQuery> { public TopTermsRewriteAnonymousClass(int size) : base(size) { } protected override int MaxSize => int.MaxValue; protected override SpanOrQuery GetTopLevelQuery() { return new SpanOrQuery(); } protected override void AddClause(SpanOrQuery topLevel, Term term, int docFreq, float boost, TermContext states) { SpanTermQuery q = new SpanTermQuery(term); q.Boost = boost; topLevel.AddClause(q); } } /// <summary> /// return the maximum priority queue size. /// <para/> /// NOTE: This was size() in Lucene. /// </summary> public int Count => @delegate.Count; public override Query Rewrite(IndexReader reader, MultiTermQuery query) { return @delegate.Rewrite(reader, query); } public override int GetHashCode() { return 31 * @delegate.GetHashCode(); } public override bool Equals(object obj) { if (this == obj) { return true; } if (obj is null) { return false; } if (this.GetType() != obj.GetType()) { return false; } TopTermsSpanBooleanQueryRewrite other = (TopTermsSpanBooleanQueryRewrite)obj; return @delegate.Equals(other.@delegate); } } } /// <summary> /// Abstract class that defines how the query is rewritten. </summary> // LUCENENET specific - moved this class outside of SpanMultiTermQueryWrapper<Q> public abstract class SpanRewriteMethod : MultiTermQuery.RewriteMethod { public override abstract Query Rewrite(IndexReader reader, MultiTermQuery query); } /// <summary> /// LUCENENET specific interface for referring to/identifying a <see cref="Search.Spans.SpanMultiTermQueryWrapper{Q}"/> without /// referring to its generic closing type. /// </summary> public interface ISpanMultiTermQueryWrapper { /// <summary> /// Expert: Gets or Sets the rewrite method. This only makes sense /// to be a span rewrite method. /// </summary> SpanRewriteMethod MultiTermRewriteMethod { get; } Spans GetSpans(AtomicReaderContext context, IBits acceptDocs, IDictionary<Term, TermContext> termContexts); string Field { get; } /// <summary> /// Returns the wrapped query </summary> Query WrappedQuery { get; } Query Rewrite(IndexReader reader); } }
using System; using System.Data; using System.IO; using System.Text; using Mirabeau.DatabaseReleaseTool.Arguments; using Mirabeau.DatabaseReleaseTool.Connection; using Mirabeau.DatabaseReleaseTool.Logging; using Mirabeau.DatabaseReleaseTool.Policies; using NUnit.Framework; using Rhino.Mocks; namespace Mirabeau.DatabaseReleaseTool.UnitTests { [TestFixture] public class DatabaseCreateScenario { #region Public Methods and Operators [Test] public void ShouldCallExecuteAllScriptsForDatabaseWhenExecuteAllScriptsForDatabaseIsNotCalled() { // arrange DatabaseReleaseTool databaseReleaseToolMock = MockRepository.GeneratePartialMock<DatabaseReleaseTool>( Environment.CurrentDirectory, new CreateDatabasePolicyComposite(), new FileStructurePolicyComposite(), new ConsoleOutputLogger(), new ConnectionStringFactory(), null); DatabaseConnectionParameters databaseConnectionParameters = new DatabaseConnectionParameters { BeforeExecuteScriptsAction = BeforeExecuteScriptsAction .None }; databaseReleaseToolMock.Expect( x => x.ExecuteAllScriptsForDatabase("1.0.0", "2.0.0", databaseConnectionParameters, Encoding.ASCII)) .Repeat.Once() .Return(new ExcecutionResult()); // act databaseReleaseToolMock.Execute("1.0.0", "2.0.0", databaseConnectionParameters, Encoding.ASCII); // assert databaseReleaseToolMock.VerifyAllExpectations(); } [Test] public void ShouldCallExecuteCreateDatabaseAndExecuteAllScriptsForDatabaseWhenBeforeExecuteScriptsActionIsCreateDatabaseAndANdResultOfExecuteCreateDatabaseIsSucces() { // arrange DatabaseReleaseTool databaseReleaseToolMock = MockRepository.GeneratePartialMock<DatabaseReleaseTool>( Environment.CurrentDirectory, new CreateDatabasePolicyComposite(), new FileStructurePolicyComposite(), new ConsoleOutputLogger(), new ConnectionStringFactory(), null); DatabaseConnectionParameters databaseConnectionParameters = new DatabaseConnectionParameters { BeforeExecuteScriptsAction = BeforeExecuteScriptsAction .CreateDatabase }; databaseReleaseToolMock.Expect(x => x.ExecuteCreateDatabase(databaseConnectionParameters, Encoding.UTF7)) .Repeat.Once() .Return(new ExcecutionResult { Success = true }); databaseReleaseToolMock.Expect( x => x.ExecuteAllScriptsForDatabase("1.0.0", "2.0.0", databaseConnectionParameters, Encoding.UTF7)) .Repeat.Once() .Return(new ExcecutionResult()); // act databaseReleaseToolMock.Execute("1.0.0", "2.0.0", databaseConnectionParameters, Encoding.UTF7); // assert databaseReleaseToolMock.VerifyAllExpectations(); } [Test] public void ShouldCallExecuteCreateDatabaseWhenBeforeExecuteScriptsActionIsCreateDatabase() { // arrange DatabaseReleaseTool databaseReleaseToolMock = MockRepository.GeneratePartialMock<DatabaseReleaseTool>( Environment.CurrentDirectory, new CreateDatabasePolicyComposite(), new FileStructurePolicyComposite(), new ConsoleOutputLogger(), new ConnectionStringFactory(), null); DatabaseConnectionParameters databaseConnectionParameters = new DatabaseConnectionParameters { BeforeExecuteScriptsAction = BeforeExecuteScriptsAction .CreateDatabase }; databaseReleaseToolMock.Expect(x => x.ExecuteCreateDatabase(databaseConnectionParameters, Encoding.ASCII)) .Repeat.Once() .Return(new ExcecutionResult()); // act databaseReleaseToolMock.Execute(string.Empty, string.Empty, databaseConnectionParameters, Encoding.ASCII); // assert databaseReleaseToolMock.VerifyAllExpectations(); } [Test] public void ShouldReturnTrueWhenNoCreateDatabaseScriptIsGiven() { // Setup DirectoryInfo directoryInfo = DirectoryStructureHelper.CreateValidDatabaseDirStructure("ShouldReturnTrueWhenNoCreateDatabaseScriptIsGiven"); IDatabaseConnectionFactory databaseConnectionFactory = MockRepository.GenerateMock<IDatabaseConnectionFactory>(); IDbConnection connection = MockRepository.GenerateStub<IDbConnection>(); IDbTransaction transaction = MockRepository.GenerateStub<IDbTransaction>(); IDbCommand command = MockRepository.GenerateStub<IDbCommand>(); databaseConnectionFactory.Expect( c => c.CreateDatabaseConnection("Data Source=.;Initial Catalog=master;User ID=testUser;Password=testPassword", DatabaseType.MsSql)) .Repeat.Once() .Return(connection); connection.Expect(method => method.BeginTransaction()).Return(transaction); connection.Expect(method => method.CreateCommand()).Return(command); DatabaseReleaseTool dbreleaseTool = new DatabaseReleaseTool( directoryInfo.FullName, new CreateDatabasePolicyComposite(), null, new ConsoleOutputLogger(), new ConnectionStringFactory(), databaseConnectionFactory); DatabaseConnectionParameters parameters = new DatabaseConnectionParameters(); parameters.BeforeExecuteScriptsAction = BeforeExecuteScriptsAction.CreateDatabase; parameters.DatabaseType = DatabaseType.MsSql; parameters.CreationType = ConnectionStringCreationType.FromArguments; parameters.Arguments.Hostname = "."; parameters.Arguments.Username = "testUser"; parameters.Arguments.Password = "testPassword"; parameters.Arguments.Database = "testdb"; // Act ExcecutionResult result = dbreleaseTool.ExecuteCreateDatabase(parameters, Encoding.Default); // Assert Assert.That(result.Success, Is.True, "error: {0} ", result.Errors); } [Test] public void ShouldReturnTrueWhenNoScriptIsExecuted() { // Setup DirectoryInfo directoryInfo = DirectoryStructureHelper.CreateValidDatabaseDirStructure("ShouldReturnTrueWhenNoScriptIsExecuted"); DirectoryStructureHelper.CreateEmptyFile(Path.Combine(directoryInfo.GetDirectories()[1].FullName, "1.1.0_AnyFile.sql")); IDatabaseConnectionFactory databaseConnectionFactory = MockRepository.GenerateMock<IDatabaseConnectionFactory>(); IDbConnection connection = MockRepository.GenerateStub<IDbConnection>(); IDbTransaction transaction = MockRepository.GenerateStub<IDbTransaction>(); IDbCommand command = MockRepository.GenerateStub<IDbCommand>(); databaseConnectionFactory.Expect( c => c.CreateDatabaseConnection("Data Source=.;Initial Catalog=master;User ID=testUser;Password=testPassword", DatabaseType.MsSql)) .Repeat.Once() .Return(connection); connection.Expect(method => method.BeginTransaction()).Return(transaction); connection.Expect(method => method.CreateCommand()).Return(command); DatabaseReleaseTool dbreleaseTool = new DatabaseReleaseTool( directoryInfo.FullName, new CreateDatabasePolicyComposite(), null, new ConsoleOutputLogger(), new ConnectionStringFactory(), databaseConnectionFactory); DatabaseConnectionParameters parameters = new DatabaseConnectionParameters(); parameters.BeforeExecuteScriptsAction = BeforeExecuteScriptsAction.CreateDatabase; parameters.DatabaseType = DatabaseType.MsSql; parameters.CreationType = ConnectionStringCreationType.FromArguments; parameters.Arguments.Hostname = "."; parameters.Arguments.Username = "testUser"; parameters.Arguments.Password = "testPassword"; parameters.Arguments.Database = "testdb"; // Act ExcecutionResult result = dbreleaseTool.ExecuteCreateDatabase(parameters, Encoding.Default); // Assert Assert.That(result.Success, Is.True, "error: {0} ", result.Errors); } [Test] public void ShouldUseDbConnectionToMasterWhenBeforeExecuteScriptsActionIsCreateDatabase() { // Arrange DirectoryInfo directoryInfo = DirectoryStructureHelper.CreateValidDatabaseDirStructure( "ShouldUseDbConnectionToMasterWhenBeforeExecuteScriptsActionIsCreateDatabase"); DirectoryStructureHelper.CreateEmptyFile(Path.Combine(directoryInfo.GetDirectories()[1].FullName, "CreateDatabase.sql")); IDatabaseConnectionFactory databaseConnectionFactory = MockRepository.GenerateMock<IDatabaseConnectionFactory>(); IDbConnection connection = MockRepository.GenerateStub<IDbConnection>(); IDbTransaction transaction = MockRepository.GenerateStub<IDbTransaction>(); IDbCommand command = MockRepository.GenerateStub<IDbCommand>(); databaseConnectionFactory.Expect( c => c.CreateDatabaseConnection("Data Source=.;Initial Catalog=master;User ID=testUser;Password=testPassword", DatabaseType.MsSql)) .Repeat.Once() .Return(connection); connection.Expect(method => method.BeginTransaction()).Return(transaction); connection.Expect(method => method.CreateCommand()).Return(command); DatabaseReleaseTool dbreleaseTool = new DatabaseReleaseTool( directoryInfo.FullName, new CreateDatabasePolicyComposite(), null, new ConsoleOutputLogger(), new ConnectionStringFactory(), databaseConnectionFactory); DatabaseConnectionParameters parameters = new DatabaseConnectionParameters { BeforeExecuteScriptsAction = BeforeExecuteScriptsAction.CreateDatabase, DatabaseType = DatabaseType.MsSql, CreationType = ConnectionStringCreationType.FromArguments, Arguments = { Hostname = ".", Username = "testUser", Password = "testPassword", Database = "FruitDB" } }; // Act dbreleaseTool.ExecuteCreateDatabase(parameters, Encoding.Default); // Assert databaseConnectionFactory.VerifyAllExpectations(); } [Test] public void SmokeTest() { // Setup DirectoryInfo directoryInfo = DirectoryStructureHelper.CreateValidDatabaseDirStructure("SmokeTest"); DirectoryStructureHelper.CreateEmptyFile(Path.Combine(directoryInfo.GetDirectories()[1].FullName, "CreateDatabase.sql")); IDatabaseConnectionFactory databaseConnectionFactory = MockRepository.GenerateMock<IDatabaseConnectionFactory>(); IDbConnection connection = MockRepository.GenerateStub<IDbConnection>(); IDbTransaction transaction = MockRepository.GenerateStub<IDbTransaction>(); IDbCommand command = MockRepository.GenerateStub<IDbCommand>(); databaseConnectionFactory.Expect( c => c.CreateDatabaseConnection("Data Source=.;Initial Catalog=master;User ID=testUser;Password=testPassword", DatabaseType.MsSql)) .Repeat.Once() .Return(connection); connection.Expect(method => method.BeginTransaction()).Return(transaction); connection.Expect(method => method.CreateCommand()).Return(command); DatabaseReleaseTool dbreleaseTool = new DatabaseReleaseTool( directoryInfo.FullName, new CreateDatabasePolicyComposite(), null, new ConsoleOutputLogger(), new ConnectionStringFactory(), databaseConnectionFactory); DatabaseConnectionParameters parameters = new DatabaseConnectionParameters(); parameters.BeforeExecuteScriptsAction = BeforeExecuteScriptsAction.CreateDatabase; parameters.DatabaseType = DatabaseType.MsSql; parameters.CreationType = ConnectionStringCreationType.FromArguments; parameters.Arguments.Hostname = "."; parameters.Arguments.Username = "testUser"; parameters.Arguments.Password = "testPassword"; parameters.Arguments.Database = "testdb"; // Act ExcecutionResult result = dbreleaseTool.ExecuteCreateDatabase(parameters, Encoding.Default); // Assert Assert.That(result.Success, Is.True, "error: {0} ", result.Errors); } #endregion } }
/* * MindTouch Core - open source enterprise collaborative networking * Copyright (c) 2006-2010 MindTouch Inc. * www.mindtouch.com [email protected] * * For community documentation and downloads visit www.opengarden.org; * please review the licensing section. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * http://www.gnu.org/copyleft/gpl.html */ using System; using System.Collections; using System.Collections.Generic; using System.Text; using MindTouch.Dream; using MindTouch.Tasking; using MindTouch.Xml; namespace MindTouch.Deki.Services { using Yield = IEnumerator<IYield>; [DreamService("MindTouch Yahoo! Extension", "Copyright (c) 2006-2010 MindTouch Inc.", Info = "http://developer.mindtouch.com/App_Catalog/Yahoo%21", SID = new string[] { "sid://mindtouch.com/2007/06/yahoo", "http://services.mindtouch.com/deki/draft/2007/06/yahoo" } )] [DreamServiceConfig("finance-app-id", "string", "Yahoo! Finance Application ID")] [DreamServiceConfig("finance-sig", "string", "Yahoo! Finance Signature")] [DreamServiceConfig("yahoo-app-id", "string?", "Yahoo! Application ID (default: \"YahooDemo\")")] [DreamServiceBlueprint("deki/service-type", "extension")] [DekiExtLibrary( Label = "Yahoo!", Namespace = "yahoo", Description = "This extension contains functions for embedding Yahoo! widgets.", Logo = "$files/yahoo-logo.png" )] [DekiExtLibraryFiles(Prefix = "MindTouch.Deki.Services.Resources", Filenames = new string[] { "yahoo-logo.png" })] public class YahooService : DekiExtService { //--- Functions --- [DekiExtFunction(Description = "Embed Yahoo! finance stock quote widget")] public XDoc StockQuote( [DekiExtParam("stock ticker symbol")] string symbol ) { // check keys string app = Config["finance-app-id"].AsText; string sig = Config["finance-sig"].AsText; if(string.IsNullOrEmpty(app) || string.IsNullOrEmpty(sig)) { return new XDoc("html").Start("body").Start("span").Attr("style", "color:red;font-weight:bold;").Value("The Yahoo! Finance Application ID or Signature are missing").End().End(); } // create control symbol = symbol.ToUpperInvariant(); XDoc result = new XDoc("html").Start("body").Start("iframe") .Attr("allowtransparency", "true") .Attr("marginwidth", "0") .Attr("marginheight", "0") .Attr("hspace", "0") .Attr("vspace", "0") .Attr("frameborder", "0") .Attr("scrolling", "no") .Attr("src", string.Format("http://api.finance.yahoo.com/instrument/1.0/{0}/badge;quote/HTML?AppID={1}&sig={2}", XUri.EncodeSegment(symbol), XUri.EncodeQuery(app), XUri.EncodeQuery(sig))) .Attr("width", "200px") .Attr("height", "250px") .Start("a").Attr("href", "http://finance.yahoo.com").Value("Yahoo! Finance").End() .Elem("br") .Start("a").Attr("href", string.Format("http://finance.yahoo.com/q?s={0}", XUri.EncodeQuery(symbol))).Value(string.Format("Quote for {0}", symbol)).End() .End().End(); return result; } [DekiExtFunction(Description = "Embed Yahoo! finance stock chart widget")] public XDoc StockChart( [DekiExtParam("stock ticker symbol")] string symbol ) { // check keys string app = Config["finance-app-id"].AsText; string sig = Config["finance-sig"].AsText; if(string.IsNullOrEmpty(app) || string.IsNullOrEmpty(sig)) { return new XDoc("html").Start("body").Start("span").Attr("style", "color:red;font-weight:bold;").Value("The Yahoo! Finance Application ID or Signature are missing").End().End(); } // create control symbol = symbol.ToUpperInvariant(); XDoc result = new XDoc("html").Start("body").Start("iframe") .Attr("allowtransparency", "true") .Attr("marginwidth", "0") .Attr("marginheight", "0") .Attr("hspace", "0") .Attr("vspace", "0") .Attr("frameborder", "0") .Attr("scrolling", "no") .Attr("src", string.Format("http://api.finance.yahoo.com/instrument/1.0/{0}/badge;chart=1y;quote/HTML?AppID={1}&sig={2}", XUri.EncodeSegment(symbol), XUri.EncodeQuery(app), XUri.EncodeQuery(sig))) .Attr("width", "200px") .Attr("height", "390px") .Start("a").Attr("href", "http://finance.yahoo.com").Value("Yahoo! Finance").End() .Elem("br") .Start("a").Attr("href", "http://finance.yahoo.com/q?s=^GSPC/").Value("Quote for ^GSPC").End() .End().End(); return result; } [DekiExtFunction(Description = "Publish terms extracted from content")] public XDoc ExtractTerms( [DekiExtParam("content to extract terms from (default: nil)", true)] string content, [DekiExtParam("max number of terms to extract (default: 3)", true)] int? max, [DekiExtParam("publish on channel (default: \"default\")", true)] string publish, [DekiExtParam("subscribe to channel (default: nil)", true)] string subscribe ) { XDoc result = new XDoc("html"); // head string id = StringUtil.CreateAlphaNumericKey(8); StringBuilder javascript = new StringBuilder(); javascript.AppendLine( @"var data = { service: '{service}', max: {max}, channel: '{publish}' }; Deki.subscribe('{id}', null, yahoo_analyzecontent_data, data);" .Replace("{id}", id) .Replace("{publish}", StringUtil.EscapeString(publish ?? "default")) .Replace("{service}", DreamContext.Current.AsPublicUri(Self.At("proxy").At("extractterms").With("dream.out.format", "json")).ToString()) .Replace("{max}", (max ?? 3).ToString()) ); if(subscribe != null) { javascript.AppendLine(@"Deki.subscribe('{subscribe}', null, yahoo_analyzecontent_data, data);".Replace("{subscribe}", StringUtil.EscapeString(subscribe))); } result.Start("head") .Start("script").Attr("type", "text/javascript").Value( @"function yahoo_analyzecontent_data(c, m, d) { $.post(d.service, { context: m.text }, function(r) { var response = YAHOO.lang.JSON.parse(r); if(typeof(response.Result) == 'string') { Deki.publish(d.channel, { text: response.Result }); } else if(typeof(response.Result) == 'object') { Deki.publish(d.channel, { text: response.Result.slice(0, d.max).join(', ') }); } else { Deki.publish('debug', { text: 'term extraction failed for: ' + m.text }); } }); }" ).End() .Start("script").Attr("type", "text/javascript").Value(javascript.ToString()).End() .End(); // tail if(!string.IsNullOrEmpty(content)) { result.Start("tail") .Start("script").Attr("type", "text/javascript").Value("Deki.publish('{id}', { text: '{content}' });".Replace("{id}", id).Replace("{content}", StringUtil.EscapeString(content))).End() .End(); } return result; } [DekiExtFunction(Description = "Get geocode information from a location.")] public Hashtable GeoLocation( [DekiExtParam("full address to geocode")] string location ) { return GetGeoCode(location, null, null, null, null); } [DekiExtFunction(Description = "Get geocode information from an address")] public Hashtable GeoCode( [DekiExtParam("street name with optional number", true)] string street, [DekiExtParam("city name", true)] string city, [DekiExtParam("state (US only)", true)] string state, [DekiExtParam("zipcode", true)] string zip ) { return GetGeoCode(null, street, city, state, zip); } //--- Features --- [DreamFeature("POST:proxy/extractterms", "The 'Term Extraction Web Service' provides a list of significant words or phrases extracted from a larger content.")] [DreamFeatureParam("content", "string", "content to extract terms from (utf-8 encoded)")] [DreamFeatureParam("query", "string?", "optional query to help with the extraction process")] public Yield PostAnalyzeContent(DreamContext context, DreamMessage request, Result<DreamMessage> response) { XDoc doc = request.ToDocument(); // proxy to analysis service Result<DreamMessage> res; yield return res = Plug.New("http://search.yahooapis.com/ContentAnalysisService/V1/termExtraction").With("appid", Config["yahoo-app-id"].AsText ?? "YahooDemom").With("context", doc["context"].Contents).With("query", doc["query"].Contents).PostAsync(); response.Return(res.Value); } //--- Methods --- private Hashtable GetGeoCode(string location, string street, string city, string state, string zip) { // fetch geocode information Plug plug = Plug.New("http://local.yahooapis.com/MapsService/V1/geocode").With("appid", Config["yahoo-app-id"].AsText ?? "YahooDemom") .With("location", location) .With("street", street) .With("city", city) .With("state", state) .With("zip", zip); DreamMessage response = plug.GetAsync().Wait(); // convert result Hashtable result = null; if(response.IsSuccessful) { XDoc geo = response.ToDocument()["_:Result"]; result = new Hashtable(StringComparer.CurrentCultureIgnoreCase); result.Add("latitude", geo["Latitude"].AsDouble); result.Add("longitude", geo["Longitude"].AsDouble); result.Add("address", geo["Address"].AsText); result.Add("city", geo["City"].AsText); result.Add("state", geo["State"].AsText); result.Add("zip", geo["Zip"].AsText); result.Add("country", geo["Country"].AsText); } return result; } } }